--- /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 start = pivot;
+ if (id <= messageItemAt(pivot)->msgId())
+ end = pivot;
+ else
+ start = pivot;
}
}
-
void MessageModel::changeOfDay()
{
_dayChangeTimer.setInterval(DAY_IN_MSECS);
_nextDayChange = _nextDayChange.addMSecs(DAY_IN_MSECS);
}
-
-void MessageModel::insertErrorMessage(BufferInfo bufferInfo, const QString &errorString)
+void MessageModel::insertErrorMessage(BufferInfo bufferInfo, const QString& errorString)
{
int idx = messageCount();
beginInsertRows(QModelIndex(), idx, idx);
Message msg(bufferInfo, Message::Error, errorString);
if (!messagesIsEmpty())
- msg.setMsgId(messageItemAt(idx-1)->msgId());
+ msg.setMsgId(messageItemAt(idx - 1)->msgId());
else
msg.setMsgId(0);
insertMessage__(idx, msg);
endInsertRows();
}
-
void MessageModel::requestBacklog(BufferId bufferId)
{
if (_messagesWaiting.contains(bufferId))
if (messageItemAt(i)->bufferId() == bufferId) {
_messagesWaiting[bufferId] = requestCount;
Client::backlogManager()->emitMessagesRequested(tr("Requesting %1 messages from backlog for buffer %2:%3")
- .arg(requestCount)
- .arg(Client::networkModel()->networkName(bufferId))
- .arg(Client::networkModel()->bufferName(bufferId)));
+ .arg(requestCount)
+ .arg(Client::networkModel()->networkName(bufferId))
+ .arg(Client::networkModel()->bufferName(bufferId)));
Client::backlogManager()->requestBacklog(bufferId, -1, messageItemAt(i)->msgId(), requestCount);
return;
}
}
}
-
void MessageModel::messagesReceived(BufferId bufferId, int count)
{
if (!_messagesWaiting.contains(bufferId))
}
}
-
void MessageModel::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2)
{
for (int i = 0; i < messageCount(); i++) {
}
}
-
// ========================================
// MessageModelItem
// ========================================
}
}
-
-bool MessageModelItem::setData(int column, const QVariant &value, int role)
+bool MessageModelItem::setData(int column, const QVariant& value, int role)
{
Q_UNUSED(column);
}
}
-
// Stuff for later
-bool MessageModelItem::lessThan(const MessageModelItem *m1, const MessageModelItem *m2)
+bool MessageModelItem::lessThan(const MessageModelItem* m1, const MessageModelItem* m2)
{
return (*m1) < (*m2);
}
-
-bool MessageModelItem::operator<(const MessageModelItem &other) const
+bool MessageModelItem::operator<(const MessageModelItem& other) const
{
return msgId() < other.msgId();
}
-
-bool MessageModelItem::operator==(const MessageModelItem &other) const
+bool MessageModelItem::operator==(const MessageModelItem& other) const
{
return msgId() == other.msgId();
}
-
-bool MessageModelItem::operator>(const MessageModelItem &other) const
+bool MessageModelItem::operator>(const MessageModelItem& other) const
{
return msgId() > other.msgId();
}
-
-QDebug operator<<(QDebug dbg, const MessageModelItem &msgItem)
+QDebug operator<<(QDebug dbg, const MessageModelItem& msgItem)
{
- dbg.nospace() << qPrintable(QString("MessageModelItem(MsgId:")) << msgItem.msgId()
- << qPrintable(QString(",")) << msgItem.timestamp()
- << qPrintable(QString(", Type:")) << msgItem.msgType()
- << qPrintable(QString(", Flags:")) << msgItem.msgFlags() << qPrintable(QString(")"))
- << msgItem.data(1, Qt::DisplayRole).toString() << ":" << msgItem.data(2, Qt::DisplayRole).toString();
+ dbg.nospace() << qPrintable(QString("MessageModelItem(MsgId:")) << msgItem.msgId() << qPrintable(QString(",")) << msgItem.timestamp()
+ << qPrintable(QString(", Type:")) << msgItem.msgType() << qPrintable(QString(", Flags:")) << msgItem.msgFlags()
+ << qPrintable(QString(")")) << msgItem.data(1, Qt::DisplayRole).toString() << ":"
+ << msgItem.data(2, Qt::DisplayRole).toString();
return dbg;
}
Q_OBJECT
public:
- enum MessageModelRole {
+ enum MessageModelRole
+ {
DisplayRole = Qt::DisplayRole,
EditRole = Qt::EditRole,
BackgroundRole = Qt::BackgroundRole,
UserRole
};
- enum ColumnType {
- TimestampColumn, SenderColumn, ContentsColumn, UserColumnType
+ enum ColumnType
+ {
+ TimestampColumn,
+ SenderColumn,
+ ContentsColumn,
+ UserColumnType
};
- MessageModel(QObject *parent);
+ MessageModel(QObject* parent);
- inline QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
- inline QModelIndex parent(const QModelIndex &) const override { return {}; }
- inline int rowCount(const QModelIndex &parent = QModelIndex()) const override { return parent.isValid() ? 0 : messageCount(); }
- inline int columnCount(const QModelIndex & /*parent*/ = QModelIndex()) const override { return 3; }
+ inline QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override;
+ inline QModelIndex parent(const QModelIndex&) const override { return {}; }
+ inline int rowCount(const QModelIndex& parent = QModelIndex()) const override { return parent.isValid() ? 0 : messageCount(); }
+ inline int columnCount(const QModelIndex& /*parent*/ = QModelIndex()) const override { return 3; }
- QVariant data(const QModelIndex &index, int role) const override;
- bool setData(const QModelIndex &index, const QVariant &value, int role) override;
+ QVariant data(const QModelIndex& index, int role) const override;
+ bool setData(const QModelIndex& index, const QVariant& value, int role) override;
- //virtual Qt::ItemFlags flags(const QModelIndex &index) const;
+ // virtual Qt::ItemFlags flags(const QModelIndex &index) const;
- bool insertMessage(const Message &, bool fakeMsg = false);
- void insertMessages(const QList<Message> &);
+ bool insertMessage(const Message&, bool fakeMsg = false);
+ void insertMessages(const QList<Message>&);
void clear();
void requestBacklog(BufferId bufferId);
void messagesReceived(BufferId bufferId, int count);
void buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2);
- void insertErrorMessage(BufferInfo bufferInfo, const QString &errorString);
+ void insertErrorMessage(BufferInfo bufferInfo, const QString& errorString);
protected:
-// virtual MessageModelItem *createMessageModelItem(const Message &) = 0;
+ // virtual MessageModelItem *createMessageModelItem(const Message &) = 0;
virtual int messageCount() const = 0;
virtual bool messagesIsEmpty() const = 0;
- virtual const MessageModelItem *messageItemAt(int i) const = 0;
- virtual MessageModelItem *messageItemAt(int i) = 0;
- virtual const MessageModelItem *firstMessageItem() const = 0;
- virtual MessageModelItem *firstMessageItem() = 0;
- virtual const MessageModelItem *lastMessageItem() const = 0;
- virtual MessageModelItem *lastMessageItem() = 0;
- virtual void insertMessage__(int pos, const Message &) = 0;
- virtual void insertMessages__(int pos, const QList<Message> &) = 0;
+ virtual const MessageModelItem* messageItemAt(int i) const = 0;
+ virtual MessageModelItem* messageItemAt(int i) = 0;
+ virtual const MessageModelItem* firstMessageItem() const = 0;
+ virtual MessageModelItem* firstMessageItem() = 0;
+ virtual const MessageModelItem* lastMessageItem() const = 0;
+ virtual MessageModelItem* lastMessageItem() = 0;
+ virtual void insertMessage__(int pos, const Message&) = 0;
+ virtual void insertMessages__(int pos, const QList<Message>&) = 0;
virtual void removeMessageAt(int i) = 0;
virtual void removeAllMessages() = 0;
virtual Message takeMessageAt(int i) = 0;
- void customEvent(QEvent *event) override;
+ void customEvent(QEvent* event) override;
private slots:
void changeOfDay();
private:
- void insertMessageGroup(const QList<Message> &);
- int insertMessagesGracefully(const QList<Message> &); // inserts as many contiguous msgs as possible. returns numer of inserted msgs.
+ void insertMessageGroup(const QList<Message>&);
+ int insertMessagesGracefully(const QList<Message>&); // inserts as many contiguous msgs as possible. returns numer of inserted msgs.
int indexForId(MsgId);
// QList<MessageModelItem *> _messageList;
const qint64 DAY_IN_MSECS = 24 * 60 * 60 * 1000;
};
-
// inlines
-QModelIndex MessageModel::index(int row, int column, const QModelIndex &parent) const
+QModelIndex MessageModel::index(int row, int column, const QModelIndex& parent) const
{
if (row < 0 || row >= rowCount(parent) || column < 0 || column >= columnCount(parent))
return {};
return createIndex(row, column);
}
-
// **************************************************
// MessageModelItem
// **************************************************
inline virtual ~MessageModelItem() = default;
virtual QVariant data(int column, int role) const;
- virtual bool setData(int column, const QVariant &value, int role);
+ virtual bool setData(int column, const QVariant& value, int role);
- virtual const Message &message() const = 0;
- virtual const QDateTime ×tamp() const = 0;
- virtual const MsgId &msgId() const = 0;
- virtual const BufferId &bufferId() const = 0;
+ virtual const Message& message() const = 0;
+ virtual const QDateTime& timestamp() const = 0;
+ virtual const MsgId& msgId() const = 0;
+ virtual const BufferId& bufferId() const = 0;
virtual void setBufferId(BufferId bufferId) = 0;
virtual Message::Type msgType() const = 0;
virtual Message::Flags msgFlags() const = 0;
// For sorting
- bool operator<(const MessageModelItem &) const;
- bool operator==(const MessageModelItem &) const;
- bool operator>(const MessageModelItem &) const;
- static bool lessThan(const MessageModelItem *m1, const MessageModelItem *m2);
+ bool operator<(const MessageModelItem&) const;
+ bool operator==(const MessageModelItem&) const;
+ bool operator>(const MessageModelItem&) const;
+ static bool lessThan(const MessageModelItem* m1, const MessageModelItem* m2);
private:
BufferId _redirectedTo;
};
-
-QDebug operator<<(QDebug dbg, const MessageModelItem &msgItem);
+QDebug operator<<(QDebug dbg, const MessageModelItem& msgItem);
#include "networkmodel.h"
+#include <utility>
+
#include <QAbstractItemView>
#include <QMimeData>
-#include <utility>
#include "buffermodel.h"
#include "buffersettings.h"
+#include "buffersyncer.h"
#include "client.h"
#include "clientignorelistmanager.h"
#include "clientsettings.h"
#include "ircchannel.h"
#include "network.h"
#include "signalproxy.h"
-#include "buffersyncer.h"
/*****************************************
-* Network Items
-*****************************************/
-NetworkItem::NetworkItem(const NetworkId &netid, AbstractTreeItem *parent)
- : PropertyMapItem(parent),
- _networkId(netid),
- _statusBufferItem(nullptr)
+ * Network Items
+ *****************************************/
+NetworkItem::NetworkItem(const NetworkId& netid, AbstractTreeItem* parent)
+ : PropertyMapItem(parent)
+ , _networkId(netid)
+ , _statusBufferItem(nullptr)
{
// DO NOT EMIT dataChanged() DIRECTLY IN NetworkItem
// use networkDataChanged() instead. Otherwise you will end up in a infinite loop
connect(this, &NetworkItem::beginRemoveChilds, this, &NetworkItem::onBeginRemoveChilds);
}
-
QStringList NetworkItem::propertyOrder() const
{
static QStringList order{"networkName", "currentServer", "nickCount"};
return order;
}
-
QVariant NetworkItem::data(int column, int role) const
{
switch (role) {
}
}
-QString NetworkItem::escapeHTML(const QString &string, bool useNonbreakingSpaces)
+QString NetworkItem::escapeHTML(const QString& string, bool useNonbreakingSpaces)
{
// QString.replace() doesn't guarantee the source string will remain constant.
// Use a local variable to avoid compiler errors.
return (useNonbreakingSpaces ? formattedString.replace(" ", " ") : formattedString);
}
-
// FIXME shouldn't we check the bufferItemCache here?
-BufferItem *NetworkItem::findBufferItem(BufferId bufferId)
+BufferItem* NetworkItem::findBufferItem(BufferId bufferId)
{
- BufferItem *bufferItem = nullptr;
+ BufferItem* bufferItem = nullptr;
for (int i = 0; i < childCount(); i++) {
- bufferItem = qobject_cast<BufferItem *>(child(i));
+ bufferItem = qobject_cast<BufferItem*>(child(i));
if (!bufferItem)
continue;
if (bufferItem->bufferId() == bufferId)
return nullptr;
}
-
-BufferItem *NetworkItem::bufferItem(const BufferInfo &bufferInfo)
+BufferItem* NetworkItem::bufferItem(const BufferInfo& bufferInfo)
{
- BufferItem *bufferItem = findBufferItem(bufferInfo);
+ BufferItem* bufferItem = findBufferItem(bufferInfo);
if (bufferItem)
return bufferItem;
// postprocess... this is necessary because Qt doesn't seem to like adding children which already have children on their own
switch (bufferInfo.type()) {
- case BufferInfo::ChannelBuffer:
- {
- auto *channelBufferItem = static_cast<ChannelBufferItem *>(bufferItem);
+ case BufferInfo::ChannelBuffer: {
+ auto* channelBufferItem = static_cast<ChannelBufferItem*>(bufferItem);
if (_network) {
- IrcChannel *ircChannel = _network->ircChannel(bufferInfo.bufferName());
+ IrcChannel* ircChannel = _network->ircChannel(bufferInfo.bufferName());
if (ircChannel)
channelBufferItem->attachIrcChannel(ircChannel);
}
- }
- break;
+ } break;
default:
break;
}
- BufferSyncer *bufferSyncer = Client::bufferSyncer();
+ BufferSyncer* bufferSyncer = Client::bufferSyncer();
if (bufferSyncer) {
- bufferItem->addActivity(
- bufferSyncer->activity(bufferItem->bufferId()),
- bufferSyncer->highlightCount(bufferItem->bufferId()) > 0
- );
+ bufferItem->addActivity(bufferSyncer->activity(bufferItem->bufferId()), bufferSyncer->highlightCount(bufferItem->bufferId()) > 0);
}
return bufferItem;
}
-
-void NetworkItem::attachNetwork(Network *network)
+void NetworkItem::attachNetwork(Network* network)
{
if (!network)
return;
_network = network;
- connect(network, &Network::networkNameSet,
- this, &NetworkItem::setNetworkName);
- connect(network, &Network::currentServerSet,
- this, &NetworkItem::setCurrentServer);
- connect(network, &Network::ircChannelAdded,
- this, &NetworkItem::attachIrcChannel);
- connect(network, &Network::ircUserAdded,
- this, &NetworkItem::attachIrcUser);
- connect(network, &Network::connectedSet,
- this, [this]() { emit networkDataChanged(); });
- connect(network, &QObject::destroyed,
- this, &NetworkItem::onNetworkDestroyed);
+ connect(network, &Network::networkNameSet, this, &NetworkItem::setNetworkName);
+ connect(network, &Network::currentServerSet, this, &NetworkItem::setCurrentServer);
+ connect(network, &Network::ircChannelAdded, this, &NetworkItem::attachIrcChannel);
+ connect(network, &Network::ircUserAdded, this, &NetworkItem::attachIrcUser);
+ connect(network, &Network::connectedSet, this, [this]() { emit networkDataChanged(); });
+ connect(network, &QObject::destroyed, this, &NetworkItem::onNetworkDestroyed);
emit networkDataChanged();
}
-
-void NetworkItem::attachIrcChannel(IrcChannel *ircChannel)
+void NetworkItem::attachIrcChannel(IrcChannel* ircChannel)
{
- ChannelBufferItem *channelItem;
+ ChannelBufferItem* channelItem;
for (int i = 0; i < childCount(); i++) {
- channelItem = qobject_cast<ChannelBufferItem *>(child(i));
+ channelItem = qobject_cast<ChannelBufferItem*>(child(i));
if (!channelItem)
continue;
}
}
-
-void NetworkItem::attachIrcUser(IrcUser *ircUser)
+void NetworkItem::attachIrcUser(IrcUser* ircUser)
{
- QueryBufferItem *queryItem = nullptr;
+ QueryBufferItem* queryItem = nullptr;
for (int i = 0; i < childCount(); i++) {
- queryItem = qobject_cast<QueryBufferItem *>(child(i));
+ queryItem = qobject_cast<QueryBufferItem*>(child(i));
if (!queryItem)
continue;
}
}
-
-void NetworkItem::setNetworkName(const QString &networkName)
+void NetworkItem::setNetworkName(const QString& networkName)
{
Q_UNUSED(networkName);
emit networkDataChanged(0);
}
-
-void NetworkItem::setCurrentServer(const QString &serverName)
+void NetworkItem::setCurrentServer(const QString& serverName)
{
Q_UNUSED(serverName);
emit networkDataChanged(1);
}
-
QString NetworkItem::toolTip(int column) const
{
Q_UNUSED(column);
QString strTooltip;
- QTextStream tooltip( &strTooltip, QIODevice::WriteOnly );
+ QTextStream tooltip(&strTooltip, QIODevice::WriteOnly);
tooltip << "<qt><style>.bold { font-weight: bold; } .italic { font-style: italic; }</style>";
// Function to add a row to the tooltip table
addRow(tr("Lag"), NetworkItem::escapeHTML(tr("%1 msecs").arg(_network->latency()), true), true);
tooltip << "</table>";
- } else {
+ }
+ else {
tooltip << "<p class='italic' align='center'>" << tr("Not connected") << "</p>";
}
tooltip << "</qt>";
return strTooltip;
}
-
void NetworkItem::onBeginRemoveChilds(int start, int end)
{
for (int i = start; i <= end; i++) {
- auto *statusBufferItem = qobject_cast<StatusBufferItem *>(child(i));
+ auto* statusBufferItem = qobject_cast<StatusBufferItem*>(child(i));
if (statusBufferItem) {
_statusBufferItem = nullptr;
break;
}
}
-
void NetworkItem::onNetworkDestroyed()
{
_network = nullptr;
removeAllChilds();
}
-
/*****************************************
-* Fancy Buffer Items
-*****************************************/
-BufferItem::BufferItem(BufferInfo bufferInfo, AbstractTreeItem *parent)
- : PropertyMapItem(parent),
- _bufferInfo(std::move(bufferInfo)),
- _activity(BufferInfo::NoActivity)
+ * Fancy Buffer Items
+ *****************************************/
+BufferItem::BufferItem(BufferInfo bufferInfo, AbstractTreeItem* parent)
+ : PropertyMapItem(parent)
+ , _bufferInfo(std::move(bufferInfo))
+ , _activity(BufferInfo::NoActivity)
{
setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled);
}
-
QStringList BufferItem::propertyOrder() const
{
static QStringList order{"bufferName", "topic", "nickCount"};
return order;
}
-
void BufferItem::setActivityLevel(BufferInfo::ActivityLevel level)
{
if (_activity != level) {
}
}
-
void BufferItem::clearActivityLevel()
{
if (Client::isCoreFeatureEnabled(Quassel::Feature::BufferActivitySync)) {
// If the core handles activity sync, clear only the highlight flag
_activity &= ~BufferInfo::Highlight;
- } else {
+ }
+ else {
_activity = BufferInfo::NoActivity;
}
_firstUnreadMsgId = MsgId();
emit dataChanged();
}
-
-void BufferItem::updateActivityLevel(const Message &msg)
+void BufferItem::updateActivityLevel(const Message& msg)
{
// If the core handles activity, and this message is not a highlight, ignore this
if (Client::isCoreFeatureEnabled(Quassel::Feature::BufferActivitySync) && !msg.flags().testFlag(Message::Highlight)) {
return;
}
- if (msg.flags() & Message::Self) // don't update activity for our own messages
+ if (msg.flags() & Message::Self) // don't update activity for our own messages
return;
- if (Client::ignoreListManager()
- && Client::ignoreListManager()->match(msg, qobject_cast<NetworkItem *>(parent())->networkName()))
+ if (Client::ignoreListManager() && Client::ignoreListManager()->match(msg, qobject_cast<NetworkItem*>(parent())->networkName()))
return;
if (msg.msgId() <= lastSeenMsgId())
// If the core handles activities, ignore types
if (Client::isCoreFeatureEnabled(Quassel::Feature::BufferActivitySync)) {
type = Message::Types();
- } else {
+ }
+ else {
type = msg.type();
}
}
}
-void BufferItem::setActivity(Message::Types type, bool highlight) {
+void BufferItem::setActivity(Message::Types type, bool highlight)
+{
BufferInfo::ActivityLevel oldLevel = activityLevel();
_activity &= BufferInfo::Highlight;
}
}
-bool BufferItem::addActivity(Message::Types type, bool highlight) {
+bool BufferItem::addActivity(Message::Types type, bool highlight)
+{
auto oldActivity = activityLevel();
if (type != Message::Types())
return oldActivity != _activity;
}
-
QVariant BufferItem::data(int column, int role) const
{
switch (role) {
}
}
-
-bool BufferItem::setData(int column, const QVariant &value, int role)
+bool BufferItem::setData(int column, const QVariant& value, int role)
{
switch (role) {
case NetworkModel::BufferActivityRole:
return true;
}
-
-void BufferItem::setBufferName(const QString &name)
+void BufferItem::setBufferName(const QString& name)
{
_bufferInfo = BufferInfo(_bufferInfo.bufferId(), _bufferInfo.networkId(), _bufferInfo.type(), _bufferInfo.groupId(), name);
emit dataChanged(0);
}
-
void BufferItem::setLastSeenMsgId(MsgId msgId)
{
_lastSeenMsgId = msgId;
setActivityLevel(BufferInfo::NoActivity);
}
-
void BufferItem::setMarkerLineMsgId(MsgId msgId)
{
_markerLineMsgId = msgId;
emit dataChanged();
}
-
bool BufferItem::isCurrentBuffer() const
{
return _bufferInfo.bufferId() == Client::bufferModel()->currentIndex().data(NetworkModel::BufferIdRole).value<BufferId>();
}
-
QString BufferItem::toolTip(int column) const
{
Q_UNUSED(column);
return tr("<p> %1 - %2 </p>").arg(bufferInfo().bufferId().toInt()).arg(bufferName());
}
-
/*****************************************
-* StatusBufferItem
-*****************************************/
-StatusBufferItem::StatusBufferItem(const BufferInfo &bufferInfo, NetworkItem *parent)
+ * StatusBufferItem
+ *****************************************/
+StatusBufferItem::StatusBufferItem(const BufferInfo& bufferInfo, NetworkItem* parent)
: BufferItem(bufferInfo, parent)
-{
-}
-
+{}
QString StatusBufferItem::toolTip(int column) const
{
- auto *networkItem = qobject_cast<NetworkItem *>(parent());
+ auto* networkItem = qobject_cast<NetworkItem*>(parent());
if (networkItem)
return networkItem->toolTip(column);
else
return QString();
}
-
/*****************************************
-* QueryBufferItem
-*****************************************/
-QueryBufferItem::QueryBufferItem(const BufferInfo &bufferInfo, NetworkItem *parent)
- : BufferItem(bufferInfo, parent),
- _ircUser(nullptr)
+ * QueryBufferItem
+ *****************************************/
+QueryBufferItem::QueryBufferItem(const BufferInfo& bufferInfo, NetworkItem* parent)
+ : BufferItem(bufferInfo, parent)
+ , _ircUser(nullptr)
{
setFlags(flags() | Qt::ItemIsDropEnabled | Qt::ItemIsEditable);
- const Network *net = Client::network(bufferInfo.networkId());
+ const Network* net = Client::network(bufferInfo.networkId());
if (!net)
return;
- IrcUser *ircUser = net->ircUser(bufferInfo.bufferName());
+ IrcUser* ircUser = net->ircUser(bufferInfo.bufferName());
setIrcUser(ircUser);
}
-
QVariant QueryBufferItem::data(int column, int role) const
{
switch (role) {
case Qt::EditRole:
return BufferItem::data(column, Qt::DisplayRole);
case NetworkModel::IrcUserRole:
- return QVariant::fromValue<QObject *>(_ircUser);
+ return QVariant::fromValue<QObject*>(_ircUser);
case NetworkModel::UserAwayRole:
return (bool)_ircUser ? _ircUser->isAway() : false;
default:
}
}
-
-bool QueryBufferItem::setData(int column, const QVariant &value, int role)
+bool QueryBufferItem::setData(int column, const QVariant& value, int role)
{
if (column != 0)
return BufferItem::setData(column, value, role);
switch (role) {
- case Qt::EditRole:
- {
+ case Qt::EditRole: {
QString newName = value.toString();
// Sanity check - buffer names must not contain newlines!
else {
return false;
}
- }
- break;
+ } break;
default:
return BufferItem::setData(column, value, role);
}
}
-
-void QueryBufferItem::setBufferName(const QString &name)
+void QueryBufferItem::setBufferName(const QString& name)
{
BufferItem::setBufferName(name);
NetworkId netId = data(0, NetworkModel::NetworkIdRole).value<NetworkId>();
- const Network *net = Client::network(netId);
+ const Network* net = Client::network(netId);
if (net)
setIrcUser(net->ircUser(name));
}
-
QString QueryBufferItem::toolTip(int column) const
{
// pretty much code duplication of IrcUserItem::toolTip() but inheritance won't solve this...
Q_UNUSED(column);
QString strTooltip;
- QTextStream tooltip( &strTooltip, QIODevice::WriteOnly );
+ QTextStream tooltip(&strTooltip, QIODevice::WriteOnly);
tooltip << "<qt><style>.bold { font-weight: bold; } .italic { font-style: italic; }</style>";
// Keep track of whether or not information has been added
if (!_ircUser) {
// User seems to be offline, let the no information message be added below
tooltip << "</p>";
- } else {
+ }
+ else {
// Function to add a row to the tooltip table
auto addRow = [&](const QString& key, const QString& value, bool condition) {
if (condition) {
// User information is available
if (_ircUser->userModes() != "") {
- //TODO Translate user Modes and add them to the table below and in IrcUserItem::toolTip
+ // TODO Translate user Modes and add them to the table below and in IrcUserItem::toolTip
tooltip << " (" << _ircUser->userModes() << ")";
}
tooltip << "</p>";
}
addRow(NetworkItem::escapeHTML(tr("Away message"), true), awayMessageHTML, true);
}
- addRow(tr("Realname"),
- NetworkItem::escapeHTML(_ircUser->realName()),
- !_ircUser->realName().isEmpty());
+ addRow(tr("Realname"), NetworkItem::escapeHTML(_ircUser->realName()), !_ircUser->realName().isEmpty());
// suserHost may return "<nick> is available for help", which should be translated.
// See https://www.alien.net.au/irc/irc2numerics.html
- if(_ircUser->suserHost().endsWith("available for help")) {
- addRow(NetworkItem::escapeHTML(tr("Help status"), true),
- NetworkItem::escapeHTML(tr("Available for help")),
- true);
- } else {
+ if (_ircUser->suserHost().endsWith("available for help")) {
+ addRow(NetworkItem::escapeHTML(tr("Help status"), true), NetworkItem::escapeHTML(tr("Available for help")), true);
+ }
+ else {
addRow(NetworkItem::escapeHTML(tr("Service status"), true),
NetworkItem::escapeHTML(_ircUser->suserHost()),
!_ircUser->suserHost().isEmpty());
// Keep track of whether or not the account information's been added. Don't show it twice.
bool accountAdded = false;
- if(!_ircUser->account().isEmpty()) {
+ if (!_ircUser->account().isEmpty()) {
// IRCv3 account-notify is supported by the core and IRC server.
// Assume logged out (seems to be more common)
QString accountHTML = QString("<p class='italic'>%1</p>").arg(tr("Not logged in"));
if (_ircUser->account() != "*") {
accountHTML = NetworkItem::escapeHTML(_ircUser->account());
}
- addRow(NetworkItem::escapeHTML(tr("Account"), true),
- accountHTML,
- true);
+ addRow(NetworkItem::escapeHTML(tr("Account"), true), accountHTML, true);
// Mark the row as added
accountAdded = true;
}
// whoisServiceReply may return "<nick> is identified for this nick", which should be translated.
// See https://www.alien.net.au/irc/irc2numerics.html
- if(_ircUser->whoisServiceReply().endsWith("identified for this nick")) {
- addRow(NetworkItem::escapeHTML(tr("Account"), true),
- NetworkItem::escapeHTML(tr("Identified for this nick")),
- !accountAdded);
+ if (_ircUser->whoisServiceReply().endsWith("identified for this nick")) {
+ addRow(NetworkItem::escapeHTML(tr("Account"), true), NetworkItem::escapeHTML(tr("Identified for this nick")), !accountAdded);
// Don't add the account row again if information's already added via account-notify
// Not used further down...
// accountAdded = true;
- } else {
+ }
+ else {
addRow(NetworkItem::escapeHTML(tr("Service Reply"), true),
NetworkItem::escapeHTML(_ircUser->whoisServiceReply()),
!_ircUser->whoisServiceReply().isEmpty());
return strTooltip;
}
-
-void QueryBufferItem::setIrcUser(IrcUser *ircUser)
+void QueryBufferItem::setIrcUser(IrcUser* ircUser)
{
if (_ircUser == ircUser)
return;
emit dataChanged();
}
-
void QueryBufferItem::removeIrcUser()
{
if (_ircUser) {
}
}
-
/*****************************************
-* ChannelBufferItem
-*****************************************/
-ChannelBufferItem::ChannelBufferItem(const BufferInfo &bufferInfo, AbstractTreeItem *parent)
- : BufferItem(bufferInfo, parent),
- _ircChannel(nullptr)
+ * ChannelBufferItem
+ *****************************************/
+ChannelBufferItem::ChannelBufferItem(const BufferInfo& bufferInfo, AbstractTreeItem* parent)
+ : BufferItem(bufferInfo, parent)
+ , _ircChannel(nullptr)
{
setFlags(flags() | Qt::ItemIsDropEnabled);
}
-
QVariant ChannelBufferItem::data(int column, int role) const
{
switch (role) {
case NetworkModel::IrcChannelRole:
- return QVariant::fromValue<QObject *>(_ircChannel);
+ return QVariant::fromValue<QObject*>(_ircChannel);
default:
return BufferItem::data(column, role);
}
}
-
QString ChannelBufferItem::toolTip(int column) const
{
Q_UNUSED(column);
QString strTooltip;
- QTextStream tooltip( &strTooltip, QIODevice::WriteOnly );
+ QTextStream tooltip(&strTooltip, QIODevice::WriteOnly);
tooltip << "<qt><style>.bold { font-weight: bold; } .italic { font-style: italic; }</style>";
// Function to add a row to the tooltip table
addRow(tr("Users"), QString::number(nickCount()), true);
if (_ircChannel) {
- QString channelMode = _ircChannel->channelModeString(); // channelModeString is compiled on the fly -> thus cache the result
+ QString channelMode = _ircChannel->channelModeString(); // channelModeString is compiled on the fly -> thus cache the result
if (!channelMode.isEmpty())
addRow(tr("Mode"), channelMode, true);
}
}
tooltip << "</table>";
- } else {
+ }
+ else {
tooltip << "<p class='italic' align='center'>" << tr("Not active, double-click to join") << "</p>";
}
return strTooltip;
}
-
-void ChannelBufferItem::attachIrcChannel(IrcChannel *ircChannel)
+void ChannelBufferItem::attachIrcChannel(IrcChannel* ircChannel)
{
if (_ircChannel) {
qWarning() << Q_FUNC_INFO << "IrcChannel already set; cleanup failed!?";
emit dataChanged();
}
-QString ChannelBufferItem::nickChannelModes(const QString &nick) const
+QString ChannelBufferItem::nickChannelModes(const QString& nick) const
{
if (!_ircChannel) {
qDebug() << Q_FUNC_INFO << "IrcChannel not set, can't get user modes";
return _ircChannel->userModes(nick);
}
-
void ChannelBufferItem::ircChannelParted()
{
Q_CHECK_PTR(_ircChannel);
removeAllChilds();
}
-
void ChannelBufferItem::ircChannelDestroyed()
{
if (_ircChannel) {
}
}
-
-void ChannelBufferItem::join(const QList<IrcUser *> &ircUsers)
+void ChannelBufferItem::join(const QList<IrcUser*>& ircUsers)
{
addUsersToCategory(ircUsers);
emit dataChanged(2);
}
-
-UserCategoryItem *ChannelBufferItem::findCategoryItem(int categoryId)
+UserCategoryItem* ChannelBufferItem::findCategoryItem(int categoryId)
{
- UserCategoryItem *categoryItem = nullptr;
+ UserCategoryItem* categoryItem = nullptr;
for (int i = 0; i < childCount(); i++) {
- categoryItem = qobject_cast<UserCategoryItem *>(child(i));
+ categoryItem = qobject_cast<UserCategoryItem*>(child(i));
if (!categoryItem)
continue;
if (categoryItem->categoryId() == categoryId)
return nullptr;
}
-
-void ChannelBufferItem::addUserToCategory(IrcUser *ircUser)
+void ChannelBufferItem::addUserToCategory(IrcUser* ircUser)
{
- addUsersToCategory(QList<IrcUser *>() << ircUser);
+ addUsersToCategory(QList<IrcUser*>() << ircUser);
}
-
-void ChannelBufferItem::addUsersToCategory(const QList<IrcUser *> &ircUsers)
+void ChannelBufferItem::addUsersToCategory(const QList<IrcUser*>& ircUsers)
{
Q_ASSERT(_ircChannel);
- QHash<UserCategoryItem *, QList<IrcUser *> > categories;
+ QHash<UserCategoryItem*, QList<IrcUser*>> categories;
int categoryId = -1;
- UserCategoryItem *categoryItem = nullptr;
+ UserCategoryItem* categoryItem = nullptr;
- foreach(IrcUser *ircUser, ircUsers) {
+ foreach (IrcUser* ircUser, ircUsers) {
categoryId = UserCategoryItem::categoryFromModes(_ircChannel->userModes(ircUser));
categoryItem = findCategoryItem(categoryId);
if (!categoryItem) {
categoryItem = new UserCategoryItem(categoryId, this);
- categories[categoryItem] = QList<IrcUser *>();
+ categories[categoryItem] = QList<IrcUser*>();
newChild(categoryItem);
}
categories[categoryItem] << ircUser;
}
- QHash<UserCategoryItem *, QList<IrcUser *> >::const_iterator catIter = categories.constBegin();
+ QHash<UserCategoryItem*, QList<IrcUser*>>::const_iterator catIter = categories.constBegin();
while (catIter != categories.constEnd()) {
catIter.key()->addUsers(catIter.value());
++catIter;
}
}
-
-void ChannelBufferItem::part(IrcUser *ircUser)
+void ChannelBufferItem::part(IrcUser* ircUser)
{
if (!ircUser) {
qWarning() << bufferName() << "ChannelBufferItem::part(): unknown User" << ircUser;
emit dataChanged(2);
}
-
-void ChannelBufferItem::removeUserFromCategory(IrcUser *ircUser)
+void ChannelBufferItem::removeUserFromCategory(IrcUser* ircUser)
{
if (!_ircChannel) {
// If we parted the channel there might still be some ircUsers connected.
return;
}
- UserCategoryItem *categoryItem = nullptr;
+ UserCategoryItem* categoryItem = nullptr;
for (int i = 0; i < childCount(); i++) {
- categoryItem = qobject_cast<UserCategoryItem *>(child(i));
+ categoryItem = qobject_cast<UserCategoryItem*>(child(i));
if (categoryItem->removeUser(ircUser)) {
if (categoryItem->childCount() == 0)
removeChild(i);
}
}
-
-void ChannelBufferItem::userModeChanged(IrcUser *ircUser)
+void ChannelBufferItem::userModeChanged(IrcUser* ircUser)
{
Q_ASSERT(_ircChannel);
int categoryId = UserCategoryItem::categoryFromModes(_ircChannel->userModes(ircUser));
- UserCategoryItem *categoryItem = findCategoryItem(categoryId);
+ UserCategoryItem* categoryItem = findCategoryItem(categoryId);
if (categoryItem) {
if (categoryItem->findIrcUser(ircUser)) {
- return; // already in the right category;
+ return; // already in the right category;
}
}
else {
}
// find the item that needs reparenting
- IrcUserItem *ircUserItem = nullptr;
+ IrcUserItem* ircUserItem = nullptr;
for (int i = 0; i < childCount(); i++) {
- auto *oldCategoryItem = qobject_cast<UserCategoryItem *>(child(i));
+ auto* oldCategoryItem = qobject_cast<UserCategoryItem*>(child(i));
Q_ASSERT(oldCategoryItem);
- IrcUserItem *userItem = oldCategoryItem->findIrcUser(ircUser);
+ IrcUserItem* userItem = oldCategoryItem->findIrcUser(ircUser);
if (userItem) {
ircUserItem = userItem;
break;
ircUserItem->reParent(categoryItem);
}
-
/*****************************************
-* User Category Items (like @vh etc.)
-*****************************************/
+ * User Category Items (like @vh etc.)
+ *****************************************/
// we hardcode this even though we have PREFIX in network... but that wouldn't help with mapping modes to
// category strings anyway.
const QList<QChar> UserCategoryItem::categories = QList<QChar>() << 'q' << 'a' << 'o' << 'h' << 'v';
-UserCategoryItem::UserCategoryItem(int category, AbstractTreeItem *parent)
- : PropertyMapItem(parent),
- _category(category)
+UserCategoryItem::UserCategoryItem(int category, AbstractTreeItem* parent)
+ : PropertyMapItem(parent)
+ , _category(category)
{
setFlags(Qt::ItemIsEnabled);
setTreeItemFlags(AbstractTreeItem::DeleteOnLastChildRemoved);
setObjectName(parent->data(0, Qt::DisplayRole).toString() + "/" + QString::number(category));
}
-
QStringList UserCategoryItem::propertyOrder() const
{
static QStringList order{"categoryName"};
return order;
}
-
// caching this makes no sense, since we display the user number dynamically
QString UserCategoryItem::categoryName() const
{
}
}
-
-IrcUserItem *UserCategoryItem::findIrcUser(IrcUser *ircUser)
+IrcUserItem* UserCategoryItem::findIrcUser(IrcUser* ircUser)
{
- IrcUserItem *userItem = nullptr;
+ IrcUserItem* userItem = nullptr;
for (int i = 0; i < childCount(); i++) {
- userItem = qobject_cast<IrcUserItem *>(child(i));
+ userItem = qobject_cast<IrcUserItem*>(child(i));
if (!userItem)
continue;
if (userItem->ircUser() == ircUser)
return nullptr;
}
-
-void UserCategoryItem::addUsers(const QList<IrcUser *> &ircUsers)
+void UserCategoryItem::addUsers(const QList<IrcUser*>& ircUsers)
{
- QList<AbstractTreeItem *> userItems;
- foreach(IrcUser *ircUser, ircUsers)
- userItems << new IrcUserItem(ircUser, this);
+ QList<AbstractTreeItem*> userItems;
+ foreach (IrcUser* ircUser, ircUsers)
+ userItems << new IrcUserItem(ircUser, this);
newChilds(userItems);
emit dataChanged(0);
}
-
-bool UserCategoryItem::removeUser(IrcUser *ircUser)
+bool UserCategoryItem::removeUser(IrcUser* ircUser)
{
- IrcUserItem *userItem = findIrcUser(ircUser);
+ IrcUserItem* userItem = findIrcUser(ircUser);
auto success = (bool)userItem;
if (success) {
removeChild(userItem);
return success;
}
-
-int UserCategoryItem::categoryFromModes(const QString &modes)
+int UserCategoryItem::categoryFromModes(const QString& modes)
{
for (int i = 0; i < categories.count(); i++) {
if (modes.contains(categories[i]))
return categories.count();
}
-
QVariant UserCategoryItem::data(int column, int role) const
{
switch (role) {
}
}
-
/*****************************************
-* Irc User Items
-*****************************************/
-IrcUserItem::IrcUserItem(IrcUser *ircUser, AbstractTreeItem *parent)
- : PropertyMapItem(parent),
- _ircUser(ircUser)
+ * Irc User Items
+ *****************************************/
+IrcUserItem::IrcUserItem(IrcUser* ircUser, AbstractTreeItem* parent)
+ : PropertyMapItem(parent)
+ , _ircUser(ircUser)
{
setObjectName(ircUser->nick());
connect(ircUser, &IrcUser::quited, this, &IrcUserItem::ircUserQuited);
connect(ircUser, &IrcUser::awaySet, this, [this]() { emit dataChanged(); });
}
-
QStringList IrcUserItem::propertyOrder() const
{
static QStringList order{"nickName"};
return order;
}
-
QVariant IrcUserItem::data(int column, int role) const
{
switch (role) {
case NetworkModel::IrcChannelRole:
return parent()->data(column, role);
case NetworkModel::IrcUserRole:
- return QVariant::fromValue<QObject *>(_ircUser.data());
+ return QVariant::fromValue<QObject*>(_ircUser.data());
case NetworkModel::UserAwayRole:
return (bool)_ircUser ? _ircUser->isAway() : false;
default:
}
}
-
QString IrcUserItem::toolTip(int column) const
{
Q_UNUSED(column);
QString strTooltip;
- QTextStream tooltip( &strTooltip, QIODevice::WriteOnly );
+ QTextStream tooltip(&strTooltip, QIODevice::WriteOnly);
tooltip << "<qt><style>.bold { font-weight: bold; } .italic { font-style: italic; }</style>";
// Keep track of whether or not information has been added
// Use bufferName() for QueryBufferItem, nickName() for IrcUserItem
tooltip << "<p class='bold' align='center'>" << NetworkItem::escapeHTML(nickName(), true);
if (_ircUser->userModes() != "") {
- //TODO: Translate user Modes and add them to the table below and in QueryBufferItem::toolTip
+ // TODO: Translate user Modes and add them to the table below and in QueryBufferItem::toolTip
tooltip << " (" << _ircUser->userModes() << ")";
}
tooltip << "</p>";
auto addRow = [&](const QString& key, const QString& value, bool condition) {
- if (condition)
- {
+ if (condition) {
tooltip << "<tr><td class='bold' align='right'>" << key << "</td><td>" << value << "</td></tr>";
infoAdded = true;
}
};
tooltip << "<table cellspacing='5' cellpadding='0'>";
- addRow(tr("Modes"),
- NetworkItem::escapeHTML(channelModes()),
- !channelModes().isEmpty());
+ addRow(tr("Modes"), NetworkItem::escapeHTML(channelModes()), !channelModes().isEmpty());
if (_ircUser->isAway()) {
QString awayMessageHTML = QString("<p class='italic'>%1</p>").arg(tr("Unknown"));
}
addRow(NetworkItem::escapeHTML(tr("Away message"), true), awayMessageHTML, true);
}
- addRow(tr("Realname"),
- NetworkItem::escapeHTML(_ircUser->realName()),
- !_ircUser->realName().isEmpty());
+ addRow(tr("Realname"), NetworkItem::escapeHTML(_ircUser->realName()), !_ircUser->realName().isEmpty());
// suserHost may return "<nick> is available for help", which should be translated.
// See https://www.alien.net.au/irc/irc2numerics.html
- if(_ircUser->suserHost().endsWith("available for help")) {
- addRow(NetworkItem::escapeHTML(tr("Help status"), true),
- NetworkItem::escapeHTML(tr("Available for help")),
- true);
- } else {
+ if (_ircUser->suserHost().endsWith("available for help")) {
+ addRow(NetworkItem::escapeHTML(tr("Help status"), true), NetworkItem::escapeHTML(tr("Available for help")), true);
+ }
+ else {
addRow(NetworkItem::escapeHTML(tr("Service status"), true),
NetworkItem::escapeHTML(_ircUser->suserHost()),
!_ircUser->suserHost().isEmpty());
// Keep track of whether or not the account information's been added. Don't show it twice.
bool accountAdded = false;
- if(!_ircUser->account().isEmpty()) {
+ if (!_ircUser->account().isEmpty()) {
// IRCv3 account-notify is supported by the core and IRC server.
// Assume logged out (seems to be more common)
QString accountHTML = QString("<p class='italic'>%1</p>").arg(tr("Not logged in"));
if (_ircUser->account() != "*") {
accountHTML = NetworkItem::escapeHTML(_ircUser->account());
}
- addRow(NetworkItem::escapeHTML(tr("Account"), true),
- accountHTML,
- true);
+ addRow(NetworkItem::escapeHTML(tr("Account"), true), accountHTML, true);
// Mark the row as added
accountAdded = true;
}
// whoisServiceReply may return "<nick> is identified for this nick", which should be translated.
// See https://www.alien.net.au/irc/irc2numerics.html
- if(_ircUser->whoisServiceReply().endsWith("identified for this nick")) {
- addRow(NetworkItem::escapeHTML(tr("Account"), true),
- NetworkItem::escapeHTML(tr("Identified for this nick")),
- !accountAdded);
+ if (_ircUser->whoisServiceReply().endsWith("identified for this nick")) {
+ addRow(NetworkItem::escapeHTML(tr("Account"), true), NetworkItem::escapeHTML(tr("Identified for this nick")), !accountAdded);
// Don't add the account row again if information's already added via account-notify
// Not used further down...
// accountAdded = true;
- } else {
+ }
+ else {
addRow(NetworkItem::escapeHTML(tr("Service Reply"), true),
NetworkItem::escapeHTML(_ircUser->whoisServiceReply()),
!_ircUser->whoisServiceReply().isEmpty());
{
// IrcUserItems are parented to UserCategoryItem, which are parented to ChannelBufferItem.
// We want the channel buffer item in order to get the channel-specific user modes.
- auto *category = qobject_cast<UserCategoryItem *>(parent());
+ auto* category = qobject_cast<UserCategoryItem*>(parent());
if (!category)
return QString();
- auto *channel = qobject_cast<ChannelBufferItem *>(category->parent());
+ auto* channel = qobject_cast<ChannelBufferItem*>(category->parent());
if (!channel)
return QString();
return channel->nickChannelModes(nickName());
}
-
/*****************************************
* NetworkModel
*****************************************/
-NetworkModel::NetworkModel(QObject *parent)
+NetworkModel::NetworkModel(QObject* parent)
: TreeModel(NetworkModel::defaultHeader(), parent)
{
connect(this, &NetworkModel::rowsInserted, this, &NetworkModel::checkForNewBuffers);
messageRedirectionSettingsChanged();
}
-
QList<QVariant> NetworkModel::defaultHeader()
{
QList<QVariant> data;
return data;
}
-
-bool NetworkModel::isBufferIndex(const QModelIndex &index) const
+bool NetworkModel::isBufferIndex(const QModelIndex& index) const
{
return index.data(NetworkModel::ItemTypeRole) == NetworkModel::BufferItemType;
}
-
int NetworkModel::networkRow(NetworkId networkId) const
{
- NetworkItem *netItem = nullptr;
+ NetworkItem* netItem = nullptr;
for (int i = 0; i < rootItem->childCount(); i++) {
- netItem = qobject_cast<NetworkItem *>(rootItem->child(i));
+ netItem = qobject_cast<NetworkItem*>(rootItem->child(i));
if (!netItem)
continue;
if (netItem->networkId() == networkId)
return -1;
}
-
QModelIndex NetworkModel::networkIndex(NetworkId networkId)
{
int netRow = networkRow(networkId);
if (netRow == -1)
return {};
else
- return indexByItem(qobject_cast<NetworkItem *>(rootItem->child(netRow)));
+ return indexByItem(qobject_cast<NetworkItem*>(rootItem->child(netRow)));
}
-
-NetworkItem *NetworkModel::findNetworkItem(NetworkId networkId) const
+NetworkItem* NetworkModel::findNetworkItem(NetworkId networkId) const
{
int netRow = networkRow(networkId);
if (netRow == -1)
return nullptr;
else
- return qobject_cast<NetworkItem *>(rootItem->child(netRow));
+ return qobject_cast<NetworkItem*>(rootItem->child(netRow));
}
-
-NetworkItem *NetworkModel::networkItem(NetworkId networkId)
+NetworkItem* NetworkModel::networkItem(NetworkId networkId)
{
- NetworkItem *netItem = findNetworkItem(networkId);
+ NetworkItem* netItem = findNetworkItem(networkId);
if (netItem == nullptr) {
netItem = new NetworkItem(networkId, rootItem);
return netItem;
}
-
-void NetworkModel::networkRemoved(const NetworkId &networkId)
+void NetworkModel::networkRemoved(const NetworkId& networkId)
{
int netRow = networkRow(networkId);
if (netRow != -1) {
}
}
-
QModelIndex NetworkModel::bufferIndex(BufferId bufferId)
{
if (!_bufferItemCache.contains(bufferId))
return indexByItem(_bufferItemCache[bufferId]);
}
-
-BufferItem *NetworkModel::findBufferItem(BufferId bufferId) const
+BufferItem* NetworkModel::findBufferItem(BufferId bufferId) const
{
if (_bufferItemCache.contains(bufferId))
return _bufferItemCache[bufferId];
return nullptr;
}
-
-BufferItem *NetworkModel::bufferItem(const BufferInfo &bufferInfo)
+BufferItem* NetworkModel::bufferItem(const BufferInfo& bufferInfo)
{
if (_bufferItemCache.contains(bufferInfo.bufferId()))
return _bufferItemCache[bufferInfo.bufferId()];
- NetworkItem *netItem = networkItem(bufferInfo.networkId());
+ NetworkItem* netItem = networkItem(bufferInfo.networkId());
return netItem->bufferItem(bufferInfo);
}
-
QStringList NetworkModel::mimeTypes() const
{
// mimetypes we accept for drops
return types;
}
-
-bool NetworkModel::mimeContainsBufferList(const QMimeData *mimeData)
+bool NetworkModel::mimeContainsBufferList(const QMimeData* mimeData)
{
return mimeData->hasFormat("application/Quassel/BufferItemList");
}
-
-QList<QPair<NetworkId, BufferId> > NetworkModel::mimeDataToBufferList(const QMimeData *mimeData)
+QList<QPair<NetworkId, BufferId>> NetworkModel::mimeDataToBufferList(const QMimeData* mimeData)
{
- QList<QPair<NetworkId, BufferId> > bufferList;
+ QList<QPair<NetworkId, BufferId>> bufferList;
if (!mimeContainsBufferList(mimeData))
return bufferList;
QStringList rawBufferList = QString::fromLatin1(mimeData->data("application/Quassel/BufferItemList")).split(",");
NetworkId networkId;
BufferId bufferUid;
- foreach(QString rawBuffer, rawBufferList) {
+ foreach (QString rawBuffer, rawBufferList) {
if (!rawBuffer.contains(":"))
continue;
networkId = rawBuffer.section(":", 0, 0).toInt();
return bufferList;
}
-
-QMimeData *NetworkModel::mimeData(const QModelIndexList &indexes) const
+QMimeData* NetworkModel::mimeData(const QModelIndexList& indexes) const
{
- auto *mimeData = new QMimeData();
+ auto* mimeData = new QMimeData();
QStringList bufferlist;
QString netid, uid, bufferid;
- foreach(QModelIndex index, indexes) {
+ foreach (QModelIndex index, indexes) {
netid = QString::number(index.data(NetworkIdRole).value<NetworkId>().toInt());
uid = QString::number(index.data(BufferIdRole).value<BufferId>().toInt());
bufferid = QString("%1:%2").arg(netid).arg(uid);
return mimeData;
}
-
-void NetworkModel::attachNetwork(Network *net)
+void NetworkModel::attachNetwork(Network* net)
{
- NetworkItem *netItem = networkItem(net->networkId());
+ NetworkItem* netItem = networkItem(net->networkId());
netItem->attachNetwork(net);
}
-
void NetworkModel::bufferUpdated(BufferInfo bufferInfo)
{
- BufferItem *bufItem = bufferItem(bufferInfo);
+ BufferItem* bufItem = bufferItem(bufferInfo);
QModelIndex itemindex = indexByItem(bufItem);
emit dataChanged(itemindex, itemindex);
}
-
void NetworkModel::removeBuffer(BufferId bufferId)
{
- BufferItem *buffItem = findBufferItem(bufferId);
+ BufferItem* buffItem = findBufferItem(bufferId);
if (!buffItem)
return;
buffItem->parent()->removeChild(buffItem);
}
-
MsgId NetworkModel::lastSeenMsgId(BufferId bufferId) const
{
if (!_bufferItemCache.contains(bufferId))
return _bufferItemCache[bufferId]->lastSeenMsgId();
}
-
MsgId NetworkModel::markerLineMsgId(BufferId bufferId) const
{
if (!_bufferItemCache.contains(bufferId))
return _bufferItemCache[bufferId]->markerLineMsgId();
}
-
// FIXME we always seem to use this (expensive) non-const version
-MsgId NetworkModel::lastSeenMsgId(const BufferId &bufferId)
+MsgId NetworkModel::lastSeenMsgId(const BufferId& bufferId)
{
- BufferItem *bufferItem = findBufferItem(bufferId);
+ BufferItem* bufferItem = findBufferItem(bufferId);
if (!bufferItem) {
qDebug() << "NetworkModel::lastSeenMsgId(): buffer is unknown:" << bufferId;
Client::purgeKnownBufferIds();
return bufferItem->lastSeenMsgId();
}
-
-void NetworkModel::setLastSeenMsgId(const BufferId &bufferId, const MsgId &msgId)
+void NetworkModel::setLastSeenMsgId(const BufferId& bufferId, const MsgId& msgId)
{
- BufferItem *bufferItem = findBufferItem(bufferId);
+ BufferItem* bufferItem = findBufferItem(bufferId);
if (!bufferItem) {
qDebug() << "NetworkModel::setLastSeenMsgId(): buffer is unknown:" << bufferId;
Client::purgeKnownBufferIds();
emit lastSeenMsgSet(bufferId, msgId);
}
-
-void NetworkModel::setMarkerLineMsgId(const BufferId &bufferId, const MsgId &msgId)
+void NetworkModel::setMarkerLineMsgId(const BufferId& bufferId, const MsgId& msgId)
{
- BufferItem *bufferItem = findBufferItem(bufferId);
+ BufferItem* bufferItem = findBufferItem(bufferId);
if (!bufferItem) {
qDebug() << "NetworkModel::setMarkerLineMsgId(): buffer is unknown:" << bufferId;
Client::purgeKnownBufferIds();
emit markerLineSet(bufferId, msgId);
}
-
-void NetworkModel::updateBufferActivity(Message &msg)
+void NetworkModel::updateBufferActivity(Message& msg)
{
int redirectionTarget = 0;
switch (msg.type()) {
case Message::Plain:
case Message::Action:
if (bufferType(msg.bufferId()) == BufferInfo::ChannelBuffer) {
- const Network *net = Client::network(msg.bufferInfo().networkId());
- IrcUser *user = net ? net->ircUser(nickFromMask(msg.sender())) : nullptr;
+ const Network* net = Client::network(msg.bufferInfo().networkId());
+ IrcUser* user = net ? net->ircUser(nickFromMask(msg.sender())) : nullptr;
if (user)
user->setLastChannelActivity(msg.bufferId(), msg.timestamp());
}
updateBufferActivity(bufferItem(msg.bufferInfo()), msg);
if (redirectionTarget & BufferSettings::StatusBuffer) {
- const NetworkItem *netItem = findNetworkItem(msg.bufferInfo().networkId());
+ const NetworkItem* netItem = findNetworkItem(msg.bufferInfo().networkId());
if (netItem) {
updateBufferActivity(netItem->statusBufferItem(), msg);
}
}
}
-
-void NetworkModel::updateBufferActivity(BufferItem *bufferItem, const Message &msg)
+void NetworkModel::updateBufferActivity(BufferItem* bufferItem, const Message& msg)
{
if (!bufferItem)
return;
emit requestSetLastSeenMsg(bufferItem->bufferId(), msg.msgId());
}
-
-void NetworkModel::setBufferActivity(const BufferId &bufferId, BufferInfo::ActivityLevel level)
+void NetworkModel::setBufferActivity(const BufferId& bufferId, BufferInfo::ActivityLevel level)
{
- BufferItem *bufferItem = findBufferItem(bufferId);
+ BufferItem* bufferItem = findBufferItem(bufferId);
if (!bufferItem) {
qDebug() << "NetworkModel::setBufferActivity(): buffer is unknown:" << bufferId;
return;
bufferItem->setActivityLevel(level);
}
-
-void NetworkModel::clearBufferActivity(const BufferId &bufferId)
+void NetworkModel::clearBufferActivity(const BufferId& bufferId)
{
- BufferItem *bufferItem = findBufferItem(bufferId);
+ BufferItem* bufferItem = findBufferItem(bufferId);
if (!bufferItem) {
qDebug() << "NetworkModel::clearBufferActivity(): buffer is unknown:" << bufferId;
return;
bufferItem->clearActivityLevel();
}
-
-const Network *NetworkModel::networkByIndex(const QModelIndex &index) const
+const Network* NetworkModel::networkByIndex(const QModelIndex& index) const
{
QVariant netVariant = index.data(NetworkIdRole);
if (!netVariant.isValid())
return Client::network(networkId);
}
-
-void NetworkModel::checkForRemovedBuffers(const QModelIndex &parent, int start, int end)
+void NetworkModel::checkForRemovedBuffers(const QModelIndex& parent, int start, int end)
{
if (parent.data(ItemTypeRole) != NetworkItemType)
return;
}
}
-
-void NetworkModel::checkForNewBuffers(const QModelIndex &parent, int start, int end)
+void NetworkModel::checkForNewBuffers(const QModelIndex& parent, int start, int end)
{
if (parent.data(ItemTypeRole) != NetworkItemType)
return;
for (int row = start; row <= end; row++) {
QModelIndex child = parent.child(row, 0);
- _bufferItemCache[child.data(BufferIdRole).value < BufferId > ()] = static_cast<BufferItem *>(child.internalPointer());
+ _bufferItemCache[child.data(BufferIdRole).value<BufferId>()] = static_cast<BufferItem*>(child.internalPointer());
}
}
-
QString NetworkModel::bufferName(BufferId bufferId) const
{
if (!_bufferItemCache.contains(bufferId))
return _bufferItemCache[bufferId]->bufferName();
}
-
BufferInfo::Type NetworkModel::bufferType(BufferId bufferId) const
{
if (!_bufferItemCache.contains(bufferId))
return _bufferItemCache[bufferId]->bufferType();
}
-
BufferInfo NetworkModel::bufferInfo(BufferId bufferId) const
{
if (!_bufferItemCache.contains(bufferId))
return _bufferItemCache[bufferId]->bufferInfo();
}
-
NetworkId NetworkModel::networkId(BufferId bufferId) const
{
if (!_bufferItemCache.contains(bufferId))
return {};
- auto *netItem = qobject_cast<NetworkItem *>(_bufferItemCache[bufferId]->parent());
+ auto* netItem = qobject_cast<NetworkItem*>(_bufferItemCache[bufferId]->parent());
if (netItem)
return netItem->networkId();
else
return {};
}
-
QString NetworkModel::networkName(BufferId bufferId) const
{
if (!_bufferItemCache.contains(bufferId))
return QString();
- auto *netItem = qobject_cast<NetworkItem *>(_bufferItemCache[bufferId]->parent());
+ auto* netItem = qobject_cast<NetworkItem*>(_bufferItemCache[bufferId]->parent());
if (netItem)
return netItem->networkName();
else
return QString();
}
-
-BufferId NetworkModel::bufferId(NetworkId networkId, const QString &bufferName, Qt::CaseSensitivity cs) const
+BufferId NetworkModel::bufferId(NetworkId networkId, const QString& bufferName, Qt::CaseSensitivity cs) const
{
- const NetworkItem *netItem = findNetworkItem(networkId);
+ const NetworkItem* netItem = findNetworkItem(networkId);
if (!netItem)
return {};
for (int i = 0; i < netItem->childCount(); i++) {
- auto *bufferItem = qobject_cast<BufferItem *>(netItem->child(i));
+ auto* bufferItem = qobject_cast<BufferItem*>(netItem->child(i));
if (bufferItem && !bufferItem->bufferName().compare(bufferName, cs))
return bufferItem->bufferId();
}
return {};
}
-
-void NetworkModel::sortBufferIds(QList<BufferId> &bufferIds) const
+void NetworkModel::sortBufferIds(QList<BufferId>& bufferIds) const
{
- QList<BufferItem *> bufferItems;
- foreach(BufferId bufferId, bufferIds) {
+ QList<BufferItem*> bufferItems;
+ foreach (BufferId bufferId, bufferIds) {
if (_bufferItemCache.contains(bufferId))
bufferItems << _bufferItemCache[bufferId];
}
qSort(bufferItems.begin(), bufferItems.end(), bufferItemLessThan);
bufferIds.clear();
- foreach(BufferItem *bufferItem, bufferItems) {
+ foreach (BufferItem* bufferItem, bufferItems) {
bufferIds << bufferItem->bufferId();
}
}
-
QList<BufferId> NetworkModel::allBufferIdsSorted() const
{
QList<BufferId> bufferIds = allBufferIds();
return bufferIds;
}
-
-bool NetworkModel::bufferItemLessThan(const BufferItem *left, const BufferItem *right)
+bool NetworkModel::bufferItemLessThan(const BufferItem* left, const BufferItem* right)
{
int leftType = left->bufferType();
int rightType = right->bufferType();
return QString::compare(left->bufferName(), right->bufferName(), Qt::CaseInsensitive) < 0;
}
-
void NetworkModel::messageRedirectionSettingsChanged()
{
BufferSettings bufferSettings;
_errorMsgsTarget = bufferSettings.errorMsgsTarget();
}
-void NetworkModel::bufferActivityChanged(BufferId bufferId, const Message::Types activity) {
+void NetworkModel::bufferActivityChanged(BufferId bufferId, const Message::Types activity)
+{
auto _bufferItem = findBufferItem(bufferId);
if (!_bufferItem) {
qDebug() << "NetworkModel::bufferActivityChanged(): buffer is unknown:" << bufferId;
_bufferItem->setActivity(activityVisibleTypesIntersection, false);
}
-void NetworkModel::highlightCountChanged(BufferId bufferId, int count) {
+void NetworkModel::highlightCountChanged(BufferId bufferId, int count)
+{
auto _bufferItem = findBufferItem(bufferId);
if (!_bufferItem) {
qDebug() << "NetworkModel::highlightCountChanged(): buffer is unknown:" << bufferId;
Q_PROPERTY(QString currentServer READ currentServer)
Q_PROPERTY(int nickCount READ nickCount)
-public :
- NetworkItem(const NetworkId &netid, AbstractTreeItem *parent = nullptr);
+public:
+ NetworkItem(const NetworkId& netid, AbstractTreeItem* parent = nullptr);
QStringList propertyOrder() const override;
* If true, replace spaces with non-breaking spaces (i.e. ' '), otherwise only HTML escape.
* @endparblock
*/
- static QString escapeHTML(const QString &string, bool useNonbreakingSpaces = false);
+ static QString escapeHTML(const QString& string, bool useNonbreakingSpaces = false);
inline bool isActive() const { return (bool)_network ? _network->isConnected() : false; }
- inline const NetworkId &networkId() const { return _networkId; }
+ inline const NetworkId& networkId() const { return _networkId; }
inline QString networkName() const { return (bool)_network ? _network->networkName() : QString(); }
inline QString currentServer() const { return (bool)_network ? _network->currentServer() : QString(); }
inline int nickCount() const { return (bool)_network ? _network->ircUsers().count() : 0; }
QString toolTip(int column) const override;
- BufferItem *findBufferItem(BufferId bufferId);
- inline BufferItem *findBufferItem(const BufferInfo &bufferInfo) { return findBufferItem(bufferInfo.bufferId()); }
- BufferItem *bufferItem(const BufferInfo &bufferInfo);
- inline StatusBufferItem *statusBufferItem() const { return _statusBufferItem; }
+ BufferItem* findBufferItem(BufferId bufferId);
+ inline BufferItem* findBufferItem(const BufferInfo& bufferInfo) { return findBufferItem(bufferInfo.bufferId()); }
+ BufferItem* bufferItem(const BufferInfo& bufferInfo);
+ inline StatusBufferItem* statusBufferItem() const { return _statusBufferItem; }
public slots:
- void setNetworkName(const QString &networkName);
- void setCurrentServer(const QString &serverName);
+ void setNetworkName(const QString& networkName);
+ void setCurrentServer(const QString& serverName);
- void attachNetwork(Network *network);
- void attachIrcChannel(IrcChannel *channel);
- void attachIrcUser(IrcUser *ircUser);
+ void attachNetwork(Network* network);
+ void attachIrcChannel(IrcChannel* channel);
+ void attachIrcUser(IrcUser* ircUser);
signals:
void networkDataChanged(int column = -1);
private:
NetworkId _networkId;
- StatusBufferItem *_statusBufferItem;
+ StatusBufferItem* _statusBufferItem;
QPointer<Network> _network;
};
-
/*****************************************
* Fancy Buffer Items
*****************************************/
Q_PROPERTY(QString topic READ topic)
Q_PROPERTY(int nickCount READ nickCount)
-public :
- BufferItem(BufferInfo bufferInfo, AbstractTreeItem *parent = nullptr);
+public:
+ BufferItem(BufferInfo bufferInfo, AbstractTreeItem* parent = nullptr);
QStringList propertyOrder() const override;
- inline const BufferInfo &bufferInfo() const { return _bufferInfo; }
+ inline const BufferInfo& bufferInfo() const { return _bufferInfo; }
QVariant data(int column, int role) const override;
- bool setData(int column, const QVariant &value, int role) override;
+ bool setData(int column, const QVariant& value, int role) override;
inline BufferId bufferId() const { return _bufferInfo.bufferId(); }
inline BufferInfo::Type bufferType() const { return _bufferInfo.type(); }
- virtual void setBufferName(const QString &name);
+ virtual void setBufferName(const QString& name);
virtual inline QString bufferName() const { return _bufferInfo.bufferName(); }
virtual inline QString topic() const { return QString(); }
virtual inline int nickCount() const { return 0; }
- virtual inline bool isActive() const { return qobject_cast<NetworkItem *>(parent())->isActive(); }
+ virtual inline bool isActive() const { return qobject_cast<NetworkItem*>(parent())->isActive(); }
inline MsgId lastSeenMsgId() const { return _lastSeenMsgId; }
inline MsgId markerLineMsgId() const { return _markerLineMsgId; }
inline BufferInfo::ActivityLevel activityLevel() const { return _activity; }
void setActivityLevel(BufferInfo::ActivityLevel level);
void clearActivityLevel();
- void updateActivityLevel(const Message &msg);
+ void updateActivityLevel(const Message& msg);
void setActivity(Message::Types msg, bool highlight);
bool addActivity(Message::Types msg, bool highlight);
- inline const MsgId &firstUnreadMsgId() const { return _firstUnreadMsgId; }
+ inline const MsgId& firstUnreadMsgId() const { return _firstUnreadMsgId; }
bool isCurrentBuffer() const;
QString toolTip(int column) const override;
public slots:
- virtual inline void setTopic(const QString &) { emit dataChanged(1); }
+ virtual inline void setTopic(const QString&) { emit dataChanged(1); }
virtual inline void setEncrypted(bool) { emit dataChanged(); }
private:
MsgId _firstUnreadMsgId;
};
-
/*****************************************
-* StatusBufferItem
-*****************************************/
+ * StatusBufferItem
+ *****************************************/
class StatusBufferItem : public BufferItem
{
Q_OBJECT
public:
- StatusBufferItem(const BufferInfo &bufferInfo, NetworkItem *parent);
+ StatusBufferItem(const BufferInfo& bufferInfo, NetworkItem* parent);
QString toolTip(int column) const override;
inline QString bufferName() const override { return tr("Status Buffer"); }
};
-
/*****************************************
-* QueryBufferItem
-*****************************************/
+ * QueryBufferItem
+ *****************************************/
class QueryBufferItem : public BufferItem
{
Q_OBJECT
public:
- QueryBufferItem(const BufferInfo &bufferInfo, NetworkItem *parent);
+ QueryBufferItem(const BufferInfo& bufferInfo, NetworkItem* parent);
QVariant data(int column, int role) const override;
- bool setData(int column, const QVariant &value, int role) override;
+ bool setData(int column, const QVariant& value, int role) override;
inline bool isActive() const override { return (bool)_ircUser; }
QString toolTip(int column) const override;
- void setBufferName(const QString &name) override;
+ void setBufferName(const QString& name) override;
public slots:
- void setIrcUser(IrcUser *ircUser);
+ void setIrcUser(IrcUser* ircUser);
void removeIrcUser();
private:
- IrcUser *_ircUser;
+ IrcUser* _ircUser;
};
-
/*****************************************
-* ChannelBufferItem
-*****************************************/
+ * ChannelBufferItem
+ *****************************************/
class UserCategoryItem;
class ChannelBufferItem : public BufferItem
Q_OBJECT
public:
- ChannelBufferItem(const BufferInfo &bufferInfo, AbstractTreeItem *parent);
+ ChannelBufferItem(const BufferInfo& bufferInfo, AbstractTreeItem* parent);
QVariant data(int column, int role) const override;
inline bool isActive() const override { return (bool)_ircChannel; }
inline QString topic() const override { return (bool)_ircChannel ? _ircChannel->topic() : QString(); }
inline int nickCount() const override { return (bool)_ircChannel ? _ircChannel->ircUsers().count() : 0; }
- void attachIrcChannel(IrcChannel *ircChannel);
+ void attachIrcChannel(IrcChannel* ircChannel);
/**
* Gets the list of channel modes for a given nick.
* @param[in] nick IrcUser nickname to check
* @returns Channel modes as a string if any, otherwise empty string
*/
- QString nickChannelModes(const QString &nick) const;
+ QString nickChannelModes(const QString& nick) const;
public slots:
- void join(const QList<IrcUser *> &ircUsers);
- void part(IrcUser *ircUser);
+ void join(const QList<IrcUser*>& ircUsers);
+ void part(IrcUser* ircUser);
- UserCategoryItem *findCategoryItem(int categoryId);
- void addUserToCategory(IrcUser *ircUser);
- void addUsersToCategory(const QList<IrcUser *> &ircUser);
- void removeUserFromCategory(IrcUser *ircUser);
- void userModeChanged(IrcUser *ircUser);
+ UserCategoryItem* findCategoryItem(int categoryId);
+ void addUserToCategory(IrcUser* ircUser);
+ void addUsersToCategory(const QList<IrcUser*>& ircUser);
+ void removeUserFromCategory(IrcUser* ircUser);
+ void userModeChanged(IrcUser* ircUser);
private slots:
void ircChannelParted();
void ircChannelDestroyed();
private:
- IrcChannel *_ircChannel;
+ IrcChannel* _ircChannel;
};
-
/*****************************************
-* User Category Items (like @vh etc.)
-*****************************************/
+ * User Category Items (like @vh etc.)
+ *****************************************/
class IrcUserItem;
class CLIENT_EXPORT UserCategoryItem : public PropertyMapItem
Q_OBJECT
Q_PROPERTY(QString categoryName READ categoryName)
-public :
- UserCategoryItem(int category, AbstractTreeItem *parent);
+public:
+ UserCategoryItem(int category, AbstractTreeItem* parent);
QStringList propertyOrder() const override;
inline int categoryId() const { return _category; }
QVariant data(int column, int role) const override;
- IrcUserItem *findIrcUser(IrcUser *ircUser);
- void addUsers(const QList<IrcUser *> &ircUser);
- bool removeUser(IrcUser *ircUser);
+ IrcUserItem* findIrcUser(IrcUser* ircUser);
+ void addUsers(const QList<IrcUser*>& ircUser);
+ bool removeUser(IrcUser* ircUser);
- static int categoryFromModes(const QString &modes);
+ static int categoryFromModes(const QString& modes);
private:
int _category;
static const QList<QChar> categories;
};
-
/*****************************************
-* Irc User Items
-*****************************************/
+ * Irc User Items
+ *****************************************/
class IrcUserItem : public PropertyMapItem
{
Q_OBJECT
Q_PROPERTY(QString nickName READ nickName)
-public :
- IrcUserItem(IrcUser *ircUser, AbstractTreeItem *parent);
+public:
+ IrcUserItem(IrcUser* ircUser, AbstractTreeItem* parent);
QStringList propertyOrder() const override;
inline QString nickName() const { return _ircUser ? _ircUser->nick() : QString(); }
inline bool isActive() const { return _ircUser ? !_ircUser->isAway() : false; }
- inline IrcUser *ircUser() { return _ircUser; }
+ inline IrcUser* ircUser() { return _ircUser; }
QVariant data(int column, int role) const override;
QString toolTip(int column) const override;
QPointer<IrcUser> _ircUser;
};
-
/*****************************************
* NetworkModel
*****************************************/
Q_OBJECT
public:
- enum Role {
+ enum Role
+ {
BufferTypeRole = TreeModel::UserRole,
ItemActiveRole,
BufferActivityRole,
MarkerLineMsgIdRole,
};
- enum ItemType {
+ enum ItemType
+ {
NetworkItemType = 0x01,
BufferItemType = 0x02,
UserCategoryItemType = 0x04,
};
Q_DECLARE_FLAGS(ItemTypes, ItemType)
- NetworkModel(QObject *parent = nullptr);
+ NetworkModel(QObject* parent = nullptr);
static QList<QVariant> defaultHeader();
- static bool mimeContainsBufferList(const QMimeData *mimeData);
- static QList<QPair<NetworkId, BufferId> > mimeDataToBufferList(const QMimeData *mimeData);
+ static bool mimeContainsBufferList(const QMimeData* mimeData);
+ static QList<QPair<NetworkId, BufferId>> mimeDataToBufferList(const QMimeData* mimeData);
QStringList mimeTypes() const override;
- QMimeData *mimeData(const QModelIndexList &) const override;
+ QMimeData* mimeData(const QModelIndexList&) const override;
- void attachNetwork(Network *network);
+ void attachNetwork(Network* network);
- bool isBufferIndex(const QModelIndex &) const;
- //Buffer *getBufferByIndex(const QModelIndex &) const;
+ bool isBufferIndex(const QModelIndex&) const;
+ // Buffer *getBufferByIndex(const QModelIndex &) const;
QModelIndex networkIndex(NetworkId networkId);
QModelIndex bufferIndex(BufferId bufferId);
- const Network *networkByIndex(const QModelIndex &index) const;
+ const Network* networkByIndex(const QModelIndex& index) const;
- BufferInfo::ActivityLevel bufferActivity(const BufferInfo &buffer) const;
+ BufferInfo::ActivityLevel bufferActivity(const BufferInfo& buffer) const;
//! Finds a buffer with a given name in a given network
/** This performs a linear search through all BufferItems, hence it is expensive.
* @param bufferName The bufferName we look for
* @return The id of the buffer if found, an invalid one else
*/
- BufferId bufferId(NetworkId networkId, const QString &bufferName, Qt::CaseSensitivity cs = Qt::CaseInsensitive) const;
+ BufferId bufferId(NetworkId networkId, const QString& bufferName, Qt::CaseSensitivity cs = Qt::CaseInsensitive) const;
QString bufferName(BufferId bufferId) const;
BufferInfo::Type bufferType(BufferId bufferId) const;
inline QList<BufferId> allBufferIds() const { return _bufferItemCache.keys(); }
QList<BufferId> allBufferIdsSorted() const;
- void sortBufferIds(QList<BufferId> &bufferIds) const;
+ void sortBufferIds(QList<BufferId>& bufferIds) const;
public slots:
void bufferUpdated(BufferInfo bufferInfo);
void removeBuffer(BufferId bufferId);
- MsgId lastSeenMsgId(const BufferId &bufferId);
- void setLastSeenMsgId(const BufferId &bufferId, const MsgId &msgId);
- void setMarkerLineMsgId(const BufferId &bufferId, const MsgId &msgId);
- void setBufferActivity(const BufferId &bufferId, BufferInfo::ActivityLevel activity);
- void clearBufferActivity(const BufferId &bufferId);
- void updateBufferActivity(Message &msg);
- void networkRemoved(const NetworkId &networkId);
+ MsgId lastSeenMsgId(const BufferId& bufferId);
+ void setLastSeenMsgId(const BufferId& bufferId, const MsgId& msgId);
+ void setMarkerLineMsgId(const BufferId& bufferId, const MsgId& msgId);
+ void setBufferActivity(const BufferId& bufferId, BufferInfo::ActivityLevel activity);
+ void clearBufferActivity(const BufferId& bufferId);
+ void updateBufferActivity(Message& msg);
+ void networkRemoved(const NetworkId& networkId);
void bufferActivityChanged(BufferId, Message::Types);
void highlightCountChanged(BufferId, int);
void markerLineSet(BufferId buffer, MsgId msg);
private slots:
- void checkForRemovedBuffers(const QModelIndex &parent, int start, int end);
- void checkForNewBuffers(const QModelIndex &parent, int start, int end);
+ void checkForRemovedBuffers(const QModelIndex& parent, int start, int end);
+ void checkForNewBuffers(const QModelIndex& parent, int start, int end);
void messageRedirectionSettingsChanged();
private:
int networkRow(NetworkId networkId) const;
- NetworkItem *findNetworkItem(NetworkId networkId) const;
- NetworkItem *networkItem(NetworkId networkId);
- inline BufferItem *findBufferItem(const BufferInfo &bufferInfo) const { return findBufferItem(bufferInfo.bufferId()); }
- BufferItem *findBufferItem(BufferId bufferId) const;
- BufferItem *bufferItem(const BufferInfo &bufferInfo);
+ NetworkItem* findNetworkItem(NetworkId networkId) const;
+ NetworkItem* networkItem(NetworkId networkId);
+ inline BufferItem* findBufferItem(const BufferInfo& bufferInfo) const { return findBufferItem(bufferInfo.bufferId()); }
+ BufferItem* findBufferItem(BufferId bufferId) const;
+ BufferItem* bufferItem(const BufferInfo& bufferInfo);
- void updateBufferActivity(BufferItem *bufferItem, const Message &msg);
+ void updateBufferActivity(BufferItem* bufferItem, const Message& msg);
- static bool bufferItemLessThan(const BufferItem *left, const BufferItem *right);
+ static bool bufferItemLessThan(const BufferItem* left, const BufferItem* right);
- QHash<BufferId, BufferItem *> _bufferItemCache;
+ QHash<BufferId, BufferItem*> _bufferItemCache;
int _userNoticesTarget;
int _serverNoticesTarget;
int _errorMsgsTarget;
};
-
Q_DECLARE_OPERATORS_FOR_FLAGS(NetworkModel::ItemTypes)
#include <QAbstractItemModel>
#include <QAbstractProxyModel>
-
#include <QDebug>
-SelectionModelSynchronizer::SelectionModelSynchronizer(QAbstractItemModel *parent)
- : QObject(parent),
- _model(parent),
- _selectionModel(parent)
+SelectionModelSynchronizer::SelectionModelSynchronizer(QAbstractItemModel* parent)
+ : QObject(parent)
+ , _model(parent)
+ , _selectionModel(parent)
{
- connect(&_selectionModel, &QItemSelectionModel::currentChanged,
- this, &SelectionModelSynchronizer::currentChanged);
- connect(&_selectionModel, &QItemSelectionModel::selectionChanged,
- this, &SelectionModelSynchronizer::selectionChanged);
+ connect(&_selectionModel, &QItemSelectionModel::currentChanged, this, &SelectionModelSynchronizer::currentChanged);
+ connect(&_selectionModel, &QItemSelectionModel::selectionChanged, this, &SelectionModelSynchronizer::selectionChanged);
}
-
-bool SelectionModelSynchronizer::checkBaseModel(QItemSelectionModel *selectionModel)
+bool SelectionModelSynchronizer::checkBaseModel(QItemSelectionModel* selectionModel)
{
if (!selectionModel)
return false;
- const QAbstractItemModel *baseModel = selectionModel->model();
- const QAbstractProxyModel *proxyModel = nullptr;
- while ((proxyModel = qobject_cast<const QAbstractProxyModel *>(baseModel)) != nullptr) {
+ const QAbstractItemModel* baseModel = selectionModel->model();
+ const QAbstractProxyModel* proxyModel = nullptr;
+ while ((proxyModel = qobject_cast<const QAbstractProxyModel*>(baseModel)) != nullptr) {
baseModel = proxyModel->sourceModel();
if (baseModel == model())
break;
return baseModel == model();
}
-
-void SelectionModelSynchronizer::synchronizeSelectionModel(QItemSelectionModel *selectionModel)
+void SelectionModelSynchronizer::synchronizeSelectionModel(QItemSelectionModel* selectionModel)
{
if (!checkBaseModel(selectionModel)) {
qWarning() << "cannot Synchronize SelectionModel" << selectionModel << "which has a different baseModel()";
return;
}
- connect(selectionModel, &QItemSelectionModel::currentChanged,
- this, &SelectionModelSynchronizer::syncedCurrentChanged);
- connect(selectionModel, &QItemSelectionModel::selectionChanged,
- this, &SelectionModelSynchronizer::syncedSelectionChanged);
+ connect(selectionModel, &QItemSelectionModel::currentChanged, this, &SelectionModelSynchronizer::syncedCurrentChanged);
+ connect(selectionModel, &QItemSelectionModel::selectionChanged, this, &SelectionModelSynchronizer::syncedSelectionChanged);
connect(selectionModel, &QObject::destroyed, this, &SelectionModelSynchronizer::selectionModelDestroyed);
_selectionModels << selectionModel;
}
-
-void SelectionModelSynchronizer::removeSelectionModel(QItemSelectionModel *model)
+void SelectionModelSynchronizer::removeSelectionModel(QItemSelectionModel* model)
{
disconnect(model, nullptr, this, nullptr);
disconnect(this, nullptr, model, nullptr);
selectionModelDestroyed(model);
}
-
-void SelectionModelSynchronizer::selectionModelDestroyed(QObject *object)
+void SelectionModelSynchronizer::selectionModelDestroyed(QObject* object)
{
- auto *model = static_cast<QItemSelectionModel *>(object);
- QSet<QItemSelectionModel *>::iterator iter = _selectionModels.begin();
+ auto* model = static_cast<QItemSelectionModel*>(object);
+ QSet<QItemSelectionModel*>::iterator iter = _selectionModels.begin();
while (iter != _selectionModels.end()) {
if (*iter == model) {
iter = _selectionModels.erase(iter);
}
}
-
-void SelectionModelSynchronizer::syncedCurrentChanged(const QModelIndex ¤t, const QModelIndex &previous)
+void SelectionModelSynchronizer::syncedCurrentChanged(const QModelIndex& current, const QModelIndex& previous)
{
Q_UNUSED(previous);
if (!_changeCurrentEnabled)
return;
- auto *selectionModel = qobject_cast<QItemSelectionModel *>(sender());
+ auto* selectionModel = qobject_cast<QItemSelectionModel*>(sender());
Q_ASSERT(selectionModel);
QModelIndex newSourceCurrent = mapToSource(current, selectionModel);
if (newSourceCurrent.isValid() && newSourceCurrent != currentIndex())
setCurrentIndex(newSourceCurrent);
}
-
-void SelectionModelSynchronizer::syncedSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
+void SelectionModelSynchronizer::syncedSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected)
{
Q_UNUSED(selected);
Q_UNUSED(deselected);
if (!_changeSelectionEnabled)
return;
- auto *selectionModel = qobject_cast<QItemSelectionModel *>(sender());
+ auto* selectionModel = qobject_cast<QItemSelectionModel*>(sender());
Q_ASSERT(selectionModel);
QItemSelection mappedSelection = selectionModel->selection();
setCurrentSelection(mapSelectionToSource(mappedSelection, selectionModel));
}
-
-QModelIndex SelectionModelSynchronizer::mapFromSource(const QModelIndex &sourceIndex, const QItemSelectionModel *selectionModel)
+QModelIndex SelectionModelSynchronizer::mapFromSource(const QModelIndex& sourceIndex, const QItemSelectionModel* selectionModel)
{
Q_ASSERT(selectionModel);
QModelIndex mappedIndex = sourceIndex;
// make a list of all involved proxies, wie have to traverse backwards
- QList<const QAbstractProxyModel *> proxyModels;
- const QAbstractItemModel *baseModel = selectionModel->model();
- const QAbstractProxyModel *proxyModel = nullptr;
- while ((proxyModel = qobject_cast<const QAbstractProxyModel *>(baseModel)) != nullptr) {
+ QList<const QAbstractProxyModel*> proxyModels;
+ const QAbstractItemModel* baseModel = selectionModel->model();
+ const QAbstractProxyModel* proxyModel = nullptr;
+ while ((proxyModel = qobject_cast<const QAbstractProxyModel*>(baseModel)) != nullptr) {
if (baseModel == model())
break;
proxyModels << proxyModel;
return mappedIndex;
}
-
-QItemSelection SelectionModelSynchronizer::mapSelectionFromSource(const QItemSelection &sourceSelection, const QItemSelectionModel *selectionModel)
+QItemSelection SelectionModelSynchronizer::mapSelectionFromSource(const QItemSelection& sourceSelection,
+ const QItemSelectionModel* selectionModel)
{
Q_ASSERT(selectionModel);
QItemSelection mappedSelection = sourceSelection;
// make a list of all involved proxies, wie have to traverse backwards
- QList<const QAbstractProxyModel *> proxyModels;
- const QAbstractItemModel *baseModel = selectionModel->model();
- const QAbstractProxyModel *proxyModel = nullptr;
- while ((proxyModel = qobject_cast<const QAbstractProxyModel *>(baseModel)) != nullptr) {
+ QList<const QAbstractProxyModel*> proxyModels;
+ const QAbstractItemModel* baseModel = selectionModel->model();
+ const QAbstractProxyModel* proxyModel = nullptr;
+ while ((proxyModel = qobject_cast<const QAbstractProxyModel*>(baseModel)) != nullptr) {
if (baseModel == model())
break;
proxyModels << proxyModel;
return mappedSelection;
}
-
-QModelIndex SelectionModelSynchronizer::mapToSource(const QModelIndex &index, QItemSelectionModel *selectionModel)
+QModelIndex SelectionModelSynchronizer::mapToSource(const QModelIndex& index, QItemSelectionModel* selectionModel)
{
Q_ASSERT(selectionModel);
QModelIndex sourceIndex = index;
- const QAbstractItemModel *baseModel = selectionModel->model();
- const QAbstractProxyModel *proxyModel = nullptr;
- while ((proxyModel = qobject_cast<const QAbstractProxyModel *>(baseModel)) != nullptr) {
+ const QAbstractItemModel* baseModel = selectionModel->model();
+ const QAbstractProxyModel* proxyModel = nullptr;
+ while ((proxyModel = qobject_cast<const QAbstractProxyModel*>(baseModel)) != nullptr) {
sourceIndex = proxyModel->mapToSource(sourceIndex);
baseModel = proxyModel->sourceModel();
if (baseModel == model())
return sourceIndex;
}
-
-QItemSelection SelectionModelSynchronizer::mapSelectionToSource(const QItemSelection &selection, QItemSelectionModel *selectionModel)
+QItemSelection SelectionModelSynchronizer::mapSelectionToSource(const QItemSelection& selection, QItemSelectionModel* selectionModel)
{
Q_ASSERT(selectionModel);
QItemSelection sourceSelection = selection;
- const QAbstractItemModel *baseModel = selectionModel->model();
- const QAbstractProxyModel *proxyModel = nullptr;
- while ((proxyModel = qobject_cast<const QAbstractProxyModel *>(baseModel)) != nullptr) {
+ const QAbstractItemModel* baseModel = selectionModel->model();
+ const QAbstractProxyModel* proxyModel = nullptr;
+ while ((proxyModel = qobject_cast<const QAbstractProxyModel*>(baseModel)) != nullptr) {
sourceSelection = proxyModel->mapSelectionToSource(sourceSelection);
baseModel = proxyModel->sourceModel();
if (baseModel == model())
return sourceSelection;
}
-
-void SelectionModelSynchronizer::setCurrentIndex(const QModelIndex &index)
+void SelectionModelSynchronizer::setCurrentIndex(const QModelIndex& index)
{
_selectionModel.setCurrentIndex(index, QItemSelectionModel::Current);
}
-
-void SelectionModelSynchronizer::setCurrentSelection(const QItemSelection &selection)
+void SelectionModelSynchronizer::setCurrentSelection(const QItemSelection& selection)
{
_selectionModel.select(selection, QItemSelectionModel::ClearAndSelect);
}
-
-void SelectionModelSynchronizer::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
+void SelectionModelSynchronizer::currentChanged(const QModelIndex& current, const QModelIndex& previous)
{
Q_UNUSED(previous);
_changeCurrentEnabled = false;
- QSet<QItemSelectionModel *>::iterator iter = _selectionModels.begin();
+ QSet<QItemSelectionModel*>::iterator iter = _selectionModels.begin();
while (iter != _selectionModels.end()) {
(*iter)->setCurrentIndex(mapFromSource(current, (*iter)), QItemSelectionModel::Current);
++iter;
// Trigger a dataChanged() signal from the base model to update all proxy models (e.g. filters).
// Since signals are protected, we have to use invokeMethod for faking signal emission.
if (previous.isValid()) {
- QMetaObject::invokeMethod(model(), "dataChanged", Qt::DirectConnection,
- Q_ARG(QModelIndex, previous), Q_ARG(QModelIndex, previous));
+ QMetaObject::invokeMethod(model(), "dataChanged", Qt::DirectConnection, Q_ARG(QModelIndex, previous), Q_ARG(QModelIndex, previous));
}
}
-
-void SelectionModelSynchronizer::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
+void SelectionModelSynchronizer::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected)
{
Q_UNUSED(selected);
Q_UNUSED(deselected);
_changeSelectionEnabled = false;
- QSet<QItemSelectionModel *>::iterator iter = _selectionModels.begin();
+ QSet<QItemSelectionModel*>::iterator iter = _selectionModels.begin();
while (iter != _selectionModels.end()) {
(*iter)->select(mapSelectionFromSource(currentSelection(), (*iter)), QItemSelectionModel::ClearAndSelect);
++iter;
#include "client-export.h"
-#include <QObject>
#include <QItemSelectionModel>
+#include <QObject>
class QAbstractItemModel;
Q_OBJECT
public:
- SelectionModelSynchronizer(QAbstractItemModel *parent = nullptr);
+ SelectionModelSynchronizer(QAbstractItemModel* parent = nullptr);
- void synchronizeSelectionModel(QItemSelectionModel *selectionModel);
- void removeSelectionModel(QItemSelectionModel *selectionModel);
+ void synchronizeSelectionModel(QItemSelectionModel* selectionModel);
+ void removeSelectionModel(QItemSelectionModel* selectionModel);
- inline QAbstractItemModel *model() { return _model; }
- inline QItemSelectionModel *selectionModel() const { return const_cast<QItemSelectionModel *>(&_selectionModel); }
+ inline QAbstractItemModel* model() { return _model; }
+ inline QItemSelectionModel* selectionModel() const { return const_cast<QItemSelectionModel*>(&_selectionModel); }
inline QModelIndex currentIndex() const { return _selectionModel.currentIndex(); }
inline QItemSelection currentSelection() const { return _selectionModel.selection(); }
private slots:
- void syncedCurrentChanged(const QModelIndex ¤t, const QModelIndex &previous);
- void syncedSelectionChanged(const QItemSelection &selected, const QItemSelection &previous);
+ void syncedCurrentChanged(const QModelIndex& current, const QModelIndex& previous);
+ void syncedSelectionChanged(const QItemSelection& selected, const QItemSelection& previous);
- void setCurrentIndex(const QModelIndex &index);
- void setCurrentSelection(const QItemSelection &selection);
+ void setCurrentIndex(const QModelIndex& index);
+ void setCurrentSelection(const QItemSelection& selection);
- void currentChanged(const QModelIndex ¤t, const QModelIndex &previous);
- void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
+ void currentChanged(const QModelIndex& current, const QModelIndex& previous);
+ void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected);
- void selectionModelDestroyed(QObject *object);
+ void selectionModelDestroyed(QObject* object);
private:
- QAbstractItemModel *_model;
+ QAbstractItemModel* _model;
QItemSelectionModel _selectionModel;
bool _changeCurrentEnabled{true};
bool _changeSelectionEnabled{true};
- bool checkBaseModel(QItemSelectionModel *model);
- QModelIndex mapFromSource(const QModelIndex &sourceIndex, const QItemSelectionModel *selectionModel);
- QItemSelection mapSelectionFromSource(const QItemSelection &sourceSelection, const QItemSelectionModel *selectionModel);
- QModelIndex mapToSource(const QModelIndex &index, QItemSelectionModel *selectionModel);
- QItemSelection mapSelectionToSource(const QItemSelection &selection, QItemSelectionModel *selectionModel);
+ bool checkBaseModel(QItemSelectionModel* model);
+ QModelIndex mapFromSource(const QModelIndex& sourceIndex, const QItemSelectionModel* selectionModel);
+ QItemSelection mapSelectionFromSource(const QItemSelection& sourceSelection, const QItemSelectionModel* selectionModel);
+ QModelIndex mapToSource(const QModelIndex& index, QItemSelectionModel* selectionModel);
+ QItemSelection mapSelectionToSource(const QItemSelection& selection, QItemSelectionModel* selectionModel);
- QSet<QItemSelectionModel *> _selectionModels;
+ QSet<QItemSelectionModel*> _selectionModels;
};
#include "transfermanager.h"
namespace {
- constexpr int colCount{8};
+constexpr int colCount{8};
}
-
int TransferModel::rowCount(const QModelIndex& index) const
{
return index.isValid() ? 0 : _transferIds.size();
}
-
int TransferModel::columnCount(const QModelIndex& index) const
{
return index.isValid() ? 0 : colCount;
}
-
QVariant TransferModel::headerData(int section, Qt::Orientation orientation, int role) const
{
- static std::array<QString, colCount> headers = {{
- tr("Type"), tr("File"), tr("Status"), tr("Progress"), tr("Transferred"), tr("Speed"), tr("Peer"), tr("Peer Address")
- }};
+ static std::array<QString, colCount> headers = {
+ {tr("Type"), tr("File"), tr("Status"), tr("Progress"), tr("Transferred"), tr("Speed"), tr("Peer"), tr("Peer Address")}};
if (section < 0 || section >= columnCount() || orientation != Qt::Horizontal)
return {};
}
}
-
QVariant TransferModel::data(const QModelIndex& index, int role) const
{
if (!_manager)
switch (role) {
case Qt::DisplayRole:
switch (index.column()) {
- case 0: // Type
+ case 0: // Type
return t->direction() == Transfer::Direction::Send ? tr("Send") : tr("Receive");
- case 1: // File
+ case 1: // File
return t->fileName();
- case 2: // Status
+ case 2: // Status
return t->prettyStatus();
- case 3: // Progress
+ case 3: // Progress
return (t->transferred() / t->fileSize()) * 100;
- case 4: // Transferred
- return t->transferred(); // TODO: use pretty units and show total
- case 5: // Speed
- return "n/a"; // TODO: fixme
- case 6: // Peer
+ case 4: // Transferred
+ return t->transferred(); // TODO: use pretty units and show total
+ case 5: // Speed
+ return "n/a"; // TODO: fixme
+ case 6: // Peer
return t->nick();
- case 7: // Peer Address
+ case 7: // Peer Address
return QString("%1.%2").arg(t->address().toString(), t->port());
}
break;
return {};
}
-
-void TransferModel::setManager(const TransferManager *manager)
+void TransferModel::setManager(const TransferManager* manager)
{
if (_manager) {
disconnect(_manager, nullptr, this, nullptr);
if (_manager) {
connect(manager, &TransferManager::transferAdded, this, &TransferModel::onTransferAdded);
connect(manager, &TransferManager::transferRemoved, this, &TransferModel::onTransferRemoved);
- for (auto &&transferId : _manager->transferIds()) {
+ for (auto&& transferId : _manager->transferIds()) {
onTransferAdded(transferId);
}
}
}
-
-void TransferModel::onTransferAdded(const QUuid &transferId)
+void TransferModel::onTransferAdded(const QUuid& transferId)
{
auto transfer = _manager->transfer(transferId);
if (!transfer) {
endInsertRows();
}
-
-void TransferModel::onTransferRemoved(const QUuid &transferId)
+void TransferModel::onTransferRemoved(const QUuid& transferId)
{
// Check if the transfer object still exists, which means we still should disconnect
auto transfer = _manager->transfer(transferId);
}
}
-
void TransferModel::onTransferDataChanged()
{
- auto transfer = qobject_cast<Transfer *>(sender());
+ auto transfer = qobject_cast<Transfer*>(sender());
if (!transfer)
return;
#include <QAbstractTableModel>
#include <QString>
-#include <QVector>
#include <QUuid>
+#include <QVector>
#include "transfer.h"
using QAbstractTableModel::QAbstractTableModel;
// see base class docs
- int rowCount(const QModelIndex &index = {}) const override;
- int columnCount(const QModelIndex &index = {}) const override;
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
+ int rowCount(const QModelIndex& index = {}) const override;
+ int columnCount(const QModelIndex& index = {}) const override;
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
/**
* @param[in] transferId Transfer ID
* @returns A pointer to the transfer with the given ID, or nullptr for an unknown ID
*/
- Transfer *transfer(const QUuid &transferId) const;
+ Transfer* transfer(const QUuid& transferId) const;
/**
* Sets the TransferManager associated with this model.
*
* @param[in] manager Pointer to the TransferManager instance, or nullptr for clearing the model
*/
- void setManager(const TransferManager *manager);
+ void setManager(const TransferManager* manager);
private slots:
/**
*
* @param[in] transferId The transfer's ID
*/
- void onTransferAdded(const QUuid &transferId);
+ void onTransferAdded(const QUuid& transferId);
/**
* Slot to be called when a transfer is removed.
*
* @param[in] transferId The transfer's ID
*/
- void onTransferRemoved(const QUuid &transferId);
+ void onTransferRemoved(const QUuid& transferId);
/**
* Slot to be called when a transfer's data changes.
void onTransferDataChanged();
private:
- const TransferManager *_manager{nullptr}; ///< Pointer to the active TransferManager instance, if any
- QVector<QUuid> _transferIds; ///< List of transfer IDs
+ const TransferManager* _manager{nullptr}; ///< Pointer to the active TransferManager instance, if any
+ QVector<QUuid> _transferIds; ///< List of transfer IDs
};
#include "treemodel.h"
+#include <utility>
+
#include <QCoreApplication>
#include <QDebug>
-#include <utility>
#include "quassel.h"
class RemoveChildLaterEvent : public QEvent
{
public:
- RemoveChildLaterEvent(AbstractTreeItem *child) : QEvent(QEvent::User), _child(child) {};
- inline AbstractTreeItem *child() { return _child; }
+ RemoveChildLaterEvent(AbstractTreeItem* child)
+ : QEvent(QEvent::User)
+ , _child(child){};
+ inline AbstractTreeItem* child() { return _child; }
+
private:
- AbstractTreeItem *_child;
+ AbstractTreeItem* _child;
};
-
/*****************************************
* Abstract Items of a TreeModel
*****************************************/
-AbstractTreeItem::AbstractTreeItem(AbstractTreeItem *parent)
- : QObject(parent),
- _flags(Qt::ItemIsSelectable | Qt::ItemIsEnabled),
- _treeItemFlags(nullptr)
-{
-}
+AbstractTreeItem::AbstractTreeItem(AbstractTreeItem* parent)
+ : QObject(parent)
+ , _flags(Qt::ItemIsSelectable | Qt::ItemIsEnabled)
+ , _treeItemFlags(nullptr)
+{}
-
-bool AbstractTreeItem::newChild(AbstractTreeItem *item)
+bool AbstractTreeItem::newChild(AbstractTreeItem* item)
{
int newRow = childCount();
emit beginAppendChilds(newRow, newRow);
return true;
}
-
-bool AbstractTreeItem::newChilds(const QList<AbstractTreeItem *> &items)
+bool AbstractTreeItem::newChilds(const QList<AbstractTreeItem*>& items)
{
if (items.isEmpty())
return false;
return true;
}
-
bool AbstractTreeItem::removeChild(int row)
{
if (row < 0 || childCount() <= row)
child(row)->removeAllChilds();
emit beginRemoveChilds(row, row);
- AbstractTreeItem *treeitem = _childItems.takeAt(row);
+ AbstractTreeItem* treeitem = _childItems.takeAt(row);
delete treeitem;
emit endRemoveChilds();
return true;
}
-
void AbstractTreeItem::removeAllChilds()
{
const int numChilds = childCount();
if (numChilds == 0)
return;
- AbstractTreeItem *child;
+ AbstractTreeItem* child;
- QList<AbstractTreeItem *>::iterator childIter;
+ QList<AbstractTreeItem*>::iterator childIter;
childIter = _childItems.begin();
while (childIter != _childItems.end()) {
child = *childIter;
- child->setTreeItemFlags(nullptr); // disable self deletion, as this would only fuck up consitency and the child gets deleted anyways
+ child->setTreeItemFlags(nullptr); // disable self deletion, as this would only fuck up consitency and the child gets deleted anyways
child->removeAllChilds();
++childIter;
}
checkForDeletion();
}
-
-void AbstractTreeItem::removeChildLater(AbstractTreeItem *child)
+void AbstractTreeItem::removeChildLater(AbstractTreeItem* child)
{
Q_ASSERT(child);
QCoreApplication::postEvent(this, new RemoveChildLaterEvent(child));
}
-
-void AbstractTreeItem::customEvent(QEvent *event)
+void AbstractTreeItem::customEvent(QEvent* event)
{
if (event->type() != QEvent::User)
return;
event->accept();
- auto *removeEvent = static_cast<RemoveChildLaterEvent *>(event);
+ auto* removeEvent = static_cast<RemoveChildLaterEvent*>(event);
int childRow = _childItems.indexOf(removeEvent->child());
if (childRow == -1)
return;
removeChild(childRow);
}
-
-bool AbstractTreeItem::reParent(AbstractTreeItem *newParent)
+bool AbstractTreeItem::reParent(AbstractTreeItem* newParent)
{
// currently we support only re parenting if the child that's about to be
// adopted does not have any children itself.
if (childCount() != 0) {
- qDebug() << "AbstractTreeItem::reParent(): cannot reparent" << this << "with children.";
+ qDebug() << "AbstractTreeItem::reParent(): cannot reparent" << this << "with children.";
return false;
}
parent()->_childItems.removeAt(oldRow);
emit parent()->endRemoveChilds();
- AbstractTreeItem *oldParent = parent();
+ AbstractTreeItem* oldParent = parent();
setParent(newParent);
bool success = newParent->newChild(this);
if (!success)
- qWarning() << "AbstractTreeItem::reParent(): failed to attach to new parent after removing from old parent! this:" << this << "new parent:" << newParent;
+ qWarning() << "AbstractTreeItem::reParent(): failed to attach to new parent after removing from old parent! this:" << this
+ << "new parent:" << newParent;
if (oldParent)
oldParent->checkForDeletion();
return success;
}
-
-AbstractTreeItem *AbstractTreeItem::child(int row) const
+AbstractTreeItem* AbstractTreeItem::child(int row) const
{
if (childCount() <= row)
return nullptr;
return _childItems[row];
}
-
int AbstractTreeItem::childCount(int column) const
{
if (column > 0)
return _childItems.count();
}
-
int AbstractTreeItem::row() const
{
if (!parent()) {
return -1;
}
- int row_ = parent()->_childItems.indexOf(const_cast<AbstractTreeItem *>(this));
+ int row_ = parent()->_childItems.indexOf(const_cast<AbstractTreeItem*>(this));
if (row_ == -1)
qWarning() << "AbstractTreeItem::row():" << this << "is not in the child list of" << QObject::parent();
return row_;
}
-
void AbstractTreeItem::dumpChildList()
{
qDebug() << "==== Childlist for Item:" << this << "====";
if (childCount() > 0) {
- AbstractTreeItem *child;
- QList<AbstractTreeItem *>::const_iterator childIter = _childItems.constBegin();
+ AbstractTreeItem* child;
+ QList<AbstractTreeItem*>::const_iterator childIter = _childItems.constBegin();
while (childIter != _childItems.constEnd()) {
child = *childIter;
qDebug() << "Row:" << child->row() << child << child->data(0, Qt::DisplayRole);
qDebug() << "==== End Of Childlist ====";
}
-
/*****************************************
* SimpleTreeItem
*****************************************/
-SimpleTreeItem::SimpleTreeItem(QList<QVariant> data, AbstractTreeItem *parent)
- : AbstractTreeItem(parent),
- _itemData(std::move(data))
-{
-}
-
+SimpleTreeItem::SimpleTreeItem(QList<QVariant> data, AbstractTreeItem* parent)
+ : AbstractTreeItem(parent)
+ , _itemData(std::move(data))
+{}
QVariant SimpleTreeItem::data(int column, int role) const
{
return _itemData[column];
}
-
-bool SimpleTreeItem::setData(int column, const QVariant &value, int role)
+bool SimpleTreeItem::setData(int column, const QVariant& value, int role)
{
if (column > columnCount() || role != Qt::DisplayRole)
return false;
return true;
}
-
int SimpleTreeItem::columnCount() const
{
return _itemData.count();
}
-
/*****************************************
* PropertyMapItem
*****************************************/
-PropertyMapItem::PropertyMapItem(AbstractTreeItem *parent)
+PropertyMapItem::PropertyMapItem(AbstractTreeItem* parent)
: AbstractTreeItem(parent)
-{
-}
-
+{}
QVariant PropertyMapItem::data(int column, int role) const
{
case Qt::ToolTipRole:
return toolTip(column);
case Qt::DisplayRole:
- case TreeModel::SortRole: // fallthrough, since SortRole should default to DisplayRole
+ case TreeModel::SortRole: // fallthrough, since SortRole should default to DisplayRole
return property(propertyOrder()[column].toLatin1());
default:
return QVariant();
}
}
-
-bool PropertyMapItem::setData(int column, const QVariant &value, int role)
+bool PropertyMapItem::setData(int column, const QVariant& value, int role)
{
if (column >= columnCount() || role != Qt::DisplayRole)
return false;
return true;
}
-
int PropertyMapItem::columnCount() const
{
return propertyOrder().count();
}
-
/*****************************************
* TreeModel
*****************************************/
-TreeModel::TreeModel(const QList<QVariant> &data, QObject *parent)
- : QAbstractItemModel(parent),
- _childStatus(QModelIndex(), 0, 0, 0),
- _aboutToRemoveOrInsert(false)
+TreeModel::TreeModel(const QList<QVariant>& data, QObject* parent)
+ : QAbstractItemModel(parent)
+ , _childStatus(QModelIndex(), 0, 0, 0)
+ , _aboutToRemoveOrInsert(false)
{
rootItem = new SimpleTreeItem(data, nullptr);
connectItem(rootItem);
if (Quassel::isOptionSet("debugmodel")) {
- connect(this, &QAbstractItemModel::rowsAboutToBeInserted,
- this, &TreeModel::debug_rowsAboutToBeInserted);
- connect(this, &QAbstractItemModel::rowsAboutToBeRemoved,
- this, &TreeModel::debug_rowsAboutToBeRemoved);
- connect(this, &QAbstractItemModel::rowsInserted,
- this, &TreeModel::debug_rowsInserted);
- connect(this, &QAbstractItemModel::rowsRemoved,
- this, &TreeModel::debug_rowsRemoved);
- connect(this, &QAbstractItemModel::dataChanged,
- this, &TreeModel::debug_dataChanged);
+ connect(this, &QAbstractItemModel::rowsAboutToBeInserted, this, &TreeModel::debug_rowsAboutToBeInserted);
+ connect(this, &QAbstractItemModel::rowsAboutToBeRemoved, this, &TreeModel::debug_rowsAboutToBeRemoved);
+ connect(this, &QAbstractItemModel::rowsInserted, this, &TreeModel::debug_rowsInserted);
+ connect(this, &QAbstractItemModel::rowsRemoved, this, &TreeModel::debug_rowsRemoved);
+ connect(this, &QAbstractItemModel::dataChanged, this, &TreeModel::debug_dataChanged);
}
}
-
TreeModel::~TreeModel()
{
delete rootItem;
}
-
-AbstractTreeItem *TreeModel::root() const
+AbstractTreeItem* TreeModel::root() const
{
return rootItem;
}
-
-QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const
+QModelIndex TreeModel::index(int row, int column, const QModelIndex& parent) const
{
if (row < 0 || row >= rowCount(parent) || column < 0 || column >= columnCount(parent))
return {};
- AbstractTreeItem *parentItem;
+ AbstractTreeItem* parentItem;
if (!parent.isValid())
parentItem = rootItem;
else
- parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
+ parentItem = static_cast<AbstractTreeItem*>(parent.internalPointer());
- AbstractTreeItem *childItem = parentItem->child(row);
+ AbstractTreeItem* childItem = parentItem->child(row);
if (childItem)
return createIndex(row, column, childItem);
return {};
}
-
-QModelIndex TreeModel::indexByItem(AbstractTreeItem *item) const
+QModelIndex TreeModel::indexByItem(AbstractTreeItem* item) const
{
if (item == nullptr) {
qWarning() << "TreeModel::indexByItem(AbstractTreeItem *item) received NULL-Pointer";
return createIndex(item->row(), 0, item);
}
-
-QModelIndex TreeModel::parent(const QModelIndex &index) const
+QModelIndex TreeModel::parent(const QModelIndex& index) const
{
if (!index.isValid()) {
// ModelTest does this
return {};
}
- auto *childItem = static_cast<AbstractTreeItem *>(index.internalPointer());
- AbstractTreeItem *parentItem = childItem->parent();
+ auto* childItem = static_cast<AbstractTreeItem*>(index.internalPointer());
+ AbstractTreeItem* parentItem = childItem->parent();
Q_ASSERT(parentItem);
if (parentItem == rootItem)
return createIndex(parentItem->row(), 0, parentItem);
}
-
-int TreeModel::rowCount(const QModelIndex &parent) const
+int TreeModel::rowCount(const QModelIndex& parent) const
{
- AbstractTreeItem *parentItem;
+ AbstractTreeItem* parentItem;
if (!parent.isValid())
parentItem = rootItem;
else
- parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
+ parentItem = static_cast<AbstractTreeItem*>(parent.internalPointer());
return parentItem->childCount(parent.column());
}
-
-int TreeModel::columnCount(const QModelIndex &parent) const
+int TreeModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent)
return rootItem->columnCount();
// actually this gives us more freedom cause we don't have to ensure that a rows parent
// has equal or more columns than that row
-// AbstractTreeItem *parentItem;
-// if(!parent.isValid())
-// parentItem = rootItem;
-// else
-// parentItem = static_cast<AbstractTreeItem*>(parent.internalPointer());
-// return parentItem->columnCount();
+ // AbstractTreeItem *parentItem;
+ // if(!parent.isValid())
+ // parentItem = rootItem;
+ // else
+ // parentItem = static_cast<AbstractTreeItem*>(parent.internalPointer());
+ // return parentItem->columnCount();
}
-
-QVariant TreeModel::data(const QModelIndex &index, int role) const
+QVariant TreeModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
- auto *item = static_cast<AbstractTreeItem *>(index.internalPointer());
+ auto* item = static_cast<AbstractTreeItem*>(index.internalPointer());
return item->data(index.column(), role);
}
-
-bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
+bool TreeModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!index.isValid())
return false;
- auto *item = static_cast<AbstractTreeItem *>(index.internalPointer());
+ auto* item = static_cast<AbstractTreeItem*>(index.internalPointer());
return item->setData(index.column(), value, role);
}
-
-Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const
+Qt::ItemFlags TreeModel::flags(const QModelIndex& index) const
{
if (!index.isValid()) {
return rootItem->flags() & Qt::ItemIsDropEnabled;
}
else {
- auto *item = static_cast<AbstractTreeItem *>(index.internalPointer());
+ auto* item = static_cast<AbstractTreeItem*>(index.internalPointer());
return item->flags();
}
}
-
QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return QVariant();
}
-
void TreeModel::itemDataChanged(int column)
{
- auto *item = qobject_cast<AbstractTreeItem *>(sender());
+ auto* item = qobject_cast<AbstractTreeItem*>(sender());
QModelIndex leftIndex, rightIndex;
if (item == rootItem)
emit dataChanged(leftIndex, rightIndex);
}
-
-void TreeModel::connectItem(AbstractTreeItem *item)
+void TreeModel::connectItem(AbstractTreeItem* item)
{
- connect(item, &AbstractTreeItem::dataChanged,
- this, &TreeModel::itemDataChanged);
+ connect(item, &AbstractTreeItem::dataChanged, this, &TreeModel::itemDataChanged);
- connect(item, &AbstractTreeItem::beginAppendChilds,
- this, &TreeModel::beginAppendChilds);
- connect(item, &AbstractTreeItem::endAppendChilds,
- this, &TreeModel::endAppendChilds);
+ connect(item, &AbstractTreeItem::beginAppendChilds, this, &TreeModel::beginAppendChilds);
+ connect(item, &AbstractTreeItem::endAppendChilds, this, &TreeModel::endAppendChilds);
- connect(item, &AbstractTreeItem::beginRemoveChilds,
- this, &TreeModel::beginRemoveChilds);
- connect(item, &AbstractTreeItem::endRemoveChilds,
- this, &TreeModel::endRemoveChilds);
+ connect(item, &AbstractTreeItem::beginRemoveChilds, this, &TreeModel::beginRemoveChilds);
+ connect(item, &AbstractTreeItem::endRemoveChilds, this, &TreeModel::endRemoveChilds);
}
-
void TreeModel::beginAppendChilds(int firstRow, int lastRow)
{
- auto *parentItem = qobject_cast<AbstractTreeItem *>(sender());
+ auto* parentItem = qobject_cast<AbstractTreeItem*>(sender());
if (!parentItem) {
qWarning() << "TreeModel::beginAppendChilds(): cannot append Children to unknown parent";
return;
beginInsertRows(parent, firstRow, lastRow);
}
-
void TreeModel::endAppendChilds()
{
- auto *parentItem = qobject_cast<AbstractTreeItem *>(sender());
+ auto* parentItem = qobject_cast<AbstractTreeItem*>(sender());
if (!parentItem) {
qWarning() << "TreeModel::endAppendChilds(): cannot append Children to unknown parent";
return;
endInsertRows();
}
-
void TreeModel::beginRemoveChilds(int firstRow, int lastRow)
{
- auto *parentItem = qobject_cast<AbstractTreeItem *>(sender());
+ auto* parentItem = qobject_cast<AbstractTreeItem*>(sender());
if (!parentItem) {
qWarning() << "TreeModel::beginRemoveChilds(): cannot append Children to unknown parent";
return;
beginRemoveRows(parent, firstRow, lastRow);
}
-
void TreeModel::endRemoveChilds()
{
- auto *parentItem = qobject_cast<AbstractTreeItem *>(sender());
+ auto* parentItem = qobject_cast<AbstractTreeItem*>(sender());
if (!parentItem) {
qWarning() << "TreeModel::endRemoveChilds(): cannot remove Children from unknown parent";
return;
endRemoveRows();
}
-
void TreeModel::clear()
{
rootItem->removeAllChilds();
}
-
-void TreeModel::debug_rowsAboutToBeInserted(const QModelIndex &parent, int start, int end)
+void TreeModel::debug_rowsAboutToBeInserted(const QModelIndex& parent, int start, int end)
{
- qDebug() << "debug_rowsAboutToBeInserted" << parent << parent.internalPointer() << parent.data().toString() << rowCount(parent) << start << end;
+ qDebug() << "debug_rowsAboutToBeInserted" << parent << parent.internalPointer() << parent.data().toString() << rowCount(parent) << start
+ << end;
}
-
-void TreeModel::debug_rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
+void TreeModel::debug_rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
- AbstractTreeItem *parentItem;
- parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
+ AbstractTreeItem* parentItem;
+ parentItem = static_cast<AbstractTreeItem*>(parent.internalPointer());
if (!parentItem)
parentItem = rootItem;
qDebug() << "debug_rowsAboutToBeRemoved" << parent << parentItem << parent.data().toString() << rowCount(parent) << start << end;
}
}
-
-void TreeModel::debug_rowsInserted(const QModelIndex &parent, int start, int end)
+void TreeModel::debug_rowsInserted(const QModelIndex& parent, int start, int end)
{
- AbstractTreeItem *parentItem;
- parentItem = static_cast<AbstractTreeItem *>(parent.internalPointer());
+ AbstractTreeItem* parentItem;
+ parentItem = static_cast<AbstractTreeItem*>(parent.internalPointer());
if (!parentItem)
parentItem = rootItem;
qDebug() << "debug_rowsInserted:" << parent << parentItem << parent.data().toString() << rowCount(parent) << start << end;
}
}
-
-void TreeModel::debug_rowsRemoved(const QModelIndex &parent, int start, int end)
+void TreeModel::debug_rowsRemoved(const QModelIndex& parent, int start, int end)
{
qDebug() << "debug_rowsRemoved" << parent << parent.internalPointer() << parent.data().toString() << rowCount(parent) << start << end;
}
-
-void TreeModel::debug_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
+void TreeModel::debug_dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
qDebug() << "debug_dataChanged" << topLeft << bottomRight;
QStringList displayData;
#include "client-export.h"
+#include <QAbstractItemModel>
+#include <QLinkedList> // needed for debug
#include <QList>
#include <QStringList>
#include <QVariant>
-#include <QAbstractItemModel>
-
-#include <QLinkedList> // needed for debug
/*****************************************
* general item used in the Tree Model
Q_OBJECT
public:
- enum TreeItemFlag {
+ enum TreeItemFlag
+ {
NoTreeItemFlag = 0x00,
DeleteOnLastChildRemoved = 0x01
};
Q_DECLARE_FLAGS(TreeItemFlags, TreeItemFlag)
- AbstractTreeItem(AbstractTreeItem *parent = nullptr);
+ AbstractTreeItem(AbstractTreeItem* parent = nullptr);
- bool newChild(AbstractTreeItem *child);
- bool newChilds(const QList<AbstractTreeItem *> &items);
+ bool newChild(AbstractTreeItem* child);
+ bool newChilds(const QList<AbstractTreeItem*>& items);
bool removeChild(int row);
- inline bool removeChild(AbstractTreeItem *child) { return removeChild(child->row()); }
+ inline bool removeChild(AbstractTreeItem* child) { return removeChild(child->row()); }
void removeAllChilds();
- bool reParent(AbstractTreeItem *newParent);
+ bool reParent(AbstractTreeItem* newParent);
- AbstractTreeItem *child(int row) const;
+ AbstractTreeItem* child(int row) const;
int childCount(int column = 0) const;
virtual int columnCount() const = 0;
virtual QVariant data(int column, int role) const = 0;
- virtual bool setData(int column, const QVariant &value, int role) = 0;
+ virtual bool setData(int column, const QVariant& value, int role) = 0;
virtual inline Qt::ItemFlags flags() const { return _flags; }
virtual inline void setFlags(Qt::ItemFlags flags) { _flags = flags; }
inline AbstractTreeItem::TreeItemFlags treeItemFlags() const { return _treeItemFlags; }
inline void setTreeItemFlags(AbstractTreeItem::TreeItemFlags flags) { _treeItemFlags = flags; }
int row() const;
- inline AbstractTreeItem *parent() const { return qobject_cast<AbstractTreeItem *>(QObject::parent()); }
+ inline AbstractTreeItem* parent() const { return qobject_cast<AbstractTreeItem*>(QObject::parent()); }
void dumpChildList();
void endRemoveChilds();
protected:
- void customEvent(QEvent *event) override;
+ void customEvent(QEvent* event) override;
private:
- QList<AbstractTreeItem *> _childItems;
+ QList<AbstractTreeItem*> _childItems;
Qt::ItemFlags _flags;
TreeItemFlags _treeItemFlags;
- void removeChildLater(AbstractTreeItem *child);
+ void removeChildLater(AbstractTreeItem* child);
inline void checkForDeletion()
{
- if (treeItemFlags() & DeleteOnLastChildRemoved && childCount() == 0) parent()->removeChildLater(this);
+ if (treeItemFlags() & DeleteOnLastChildRemoved && childCount() == 0)
+ parent()->removeChildLater(this);
}
};
-
/*****************************************
* SimpleTreeItem
*****************************************/
Q_OBJECT
public:
- SimpleTreeItem(QList<QVariant> data, AbstractTreeItem *parent = nullptr);
+ SimpleTreeItem(QList<QVariant> data, AbstractTreeItem* parent = nullptr);
QVariant data(int column, int role) const override;
- bool setData(int column, const QVariant &value, int role) override;
+ bool setData(int column, const QVariant& value, int role) override;
int columnCount() const override;
QList<QVariant> _itemData;
};
-
/*****************************************
* PropertyMapItem
*****************************************/
Q_OBJECT
public:
- PropertyMapItem(AbstractTreeItem *parent = nullptr);
+ PropertyMapItem(AbstractTreeItem* parent = nullptr);
virtual QStringList propertyOrder() const = 0;
QVariant data(int column, int role) const override;
- bool setData(int column, const QVariant &value, int role) override;
+ bool setData(int column, const QVariant& value, int role) override;
virtual QString toolTip(int column) const { Q_UNUSED(column) return QString(); }
int columnCount() const override;
};
-
/*****************************************
* TreeModel
*****************************************/
Q_OBJECT
public:
- enum myRoles {
+ enum myRoles
+ {
SortRole = Qt::UserRole,
UserRole
};
- TreeModel(const QList<QVariant> &, QObject *parent = nullptr);
+ TreeModel(const QList<QVariant>&, QObject* parent = nullptr);
~TreeModel() override;
- AbstractTreeItem *root() const;
+ AbstractTreeItem* root() const;
- QVariant data(const QModelIndex &index, int role) const override;
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
+ QVariant data(const QModelIndex& index, int role) const override;
+ bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override;
- Qt::ItemFlags flags(const QModelIndex &index) 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 indexByItem(AbstractTreeItem *item) const;
+ QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override;
+ QModelIndex indexByItem(AbstractTreeItem* item) const;
- QModelIndex parent(const QModelIndex &index) const override;
+ QModelIndex parent(const QModelIndex& index) const override;
- int rowCount(const QModelIndex &parent = QModelIndex()) const override;
- int columnCount(const QModelIndex &parent = QModelIndex()) const override;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const override;
+ int columnCount(const QModelIndex& parent = QModelIndex()) const override;
virtual void clear();
void endRemoveChilds();
protected:
- AbstractTreeItem *rootItem;
+ AbstractTreeItem* rootItem;
private:
- void connectItem(AbstractTreeItem *item);
+ void connectItem(AbstractTreeItem* item);
- struct ChildStatus {
+ struct ChildStatus
+ {
QModelIndex parent;
int childCount;
int start;
int end;
- inline ChildStatus(QModelIndex parent_, int cc_, int s_, int e_) : parent(parent_), childCount(cc_), start(s_), end(e_) {};
+ inline ChildStatus(QModelIndex parent_, int cc_, int s_, int e_)
+ : parent(parent_)
+ , childCount(cc_)
+ , start(s_)
+ , end(e_){};
};
ChildStatus _childStatus;
int _aboutToRemoveOrInsert;
private slots:
- void debug_rowsAboutToBeInserted(const QModelIndex &parent, int start, int end);
- void debug_rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
- void debug_rowsInserted(const QModelIndex &parent, int start, int end);
- void debug_rowsRemoved(const QModelIndex &parent, int start, int end);
- void debug_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
+ void debug_rowsAboutToBeInserted(const QModelIndex& parent, int start, int end);
+ void debug_rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end);
+ void debug_rowsInserted(const QModelIndex& parent, int start, int end);
+ void debug_rowsRemoved(const QModelIndex& parent, int start, int end);
+ void debug_dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight);
};
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "aliasmanager.h"
+
#include <QDebug>
#include <QStringList>
-#include "aliasmanager.h"
#include "network.h"
-AliasManager &AliasManager::operator=(const AliasManager &other)
+AliasManager& AliasManager::operator=(const AliasManager& other)
{
if (this == &other)
return *this;
return *this;
}
-
-int AliasManager::indexOf(const QString &name) const
+int AliasManager::indexOf(const QString& name) const
{
for (int i = 0; i < _aliases.count(); i++) {
if (_aliases[i].name == name)
return -1;
}
-
QVariantMap AliasManager::initAliases() const
{
QVariantMap aliases;
return aliases;
}
-
-void AliasManager::initSetAliases(const QVariantMap &aliases)
+void AliasManager::initSetAliases(const QVariantMap& aliases)
{
QStringList names = aliases["names"].toStringList();
QStringList expansions = aliases["expansions"].toStringList();
if (names.count() != expansions.count()) {
- qWarning() << "AliasesManager::initSetAliases: received" << names.count() << "alias names but only" << expansions.count() << "expansions!";
+ qWarning() << "AliasesManager::initSetAliases: received" << names.count() << "alias names but only" << expansions.count()
+ << "expansions!";
return;
}
}
}
-
-void AliasManager::addAlias(const QString &name, const QString &expansion)
+void AliasManager::addAlias(const QString& name, const QString& expansion)
{
if (contains(name)) {
return;
SYNC(ARG(name), ARG(expansion))
}
-
AliasManager::AliasList AliasManager::defaults()
{
AliasList aliases;
- aliases << Alias("j", "/join $0")
- << Alias("ns", "/msg nickserv $0")
- << Alias("nickserv", "/msg nickserv $0")
- << Alias("cs", "/msg chanserv $0")
- << Alias("chanserv", "/msg chanserv $0")
- << Alias("hs", "/msg hostserv $0")
- << Alias("hostserv", "/msg hostserv $0")
- << Alias("wii", "/whois $0 $0")
- << Alias("back", "/quote away");
+ aliases << Alias("j", "/join $0") << Alias("ns", "/msg nickserv $0") << Alias("nickserv", "/msg nickserv $0")
+ << Alias("cs", "/msg chanserv $0") << Alias("chanserv", "/msg chanserv $0") << Alias("hs", "/msg hostserv $0")
+ << Alias("hostserv", "/msg hostserv $0") << Alias("wii", "/whois $0 $0") << Alias("back", "/quote away");
#ifdef Q_OS_LINUX
// let's add aliases for scripts that only run on linux
- aliases << Alias("inxi", "/exec inxi $0")
- << Alias("sysinfo", "/exec inxi -d");
+ aliases << Alias("inxi", "/exec inxi $0") << Alias("sysinfo", "/exec inxi -d");
#endif
return aliases;
}
-
-AliasManager::CommandList AliasManager::processInput(const BufferInfo &info, const QString &msg)
+AliasManager::CommandList AliasManager::processInput(const BufferInfo& info, const QString& msg)
{
CommandList result;
processInput(info, msg, result);
return result;
}
-
-void AliasManager::processInput(const BufferInfo &info, const QString &msg_, CommandList &list)
+void AliasManager::processInput(const BufferInfo& info, const QString& msg_, CommandList& list)
{
QString msg = msg_;
msg.remove(0, 1); // "//asdf" is transformed to "/asdf"
else if (msg.startsWith("/ "))
msg.remove(0, 2); // "/ /asdf" is transformed to "/asdf"
- msg.prepend("/SAY "); // make sure we only send proper commands to the core
+ msg.prepend("/SAY "); // make sure we only send proper commands to the core
}
else {
// check for aliases
list.append(qMakePair(info, msg));
}
-
-void AliasManager::expand(const QString &alias, const BufferInfo &bufferInfo, const QString &msg, CommandList &list)
+void AliasManager::expand(const QString& alias, const BufferInfo& bufferInfo, const QString& msg, CommandList& list)
{
- const Network *net = network(bufferInfo.networkId());
+ const Network* net = network(bufferInfo.networkId());
if (!net) {
// FIXME send error as soon as we have a method for that!
return;
for (int j = params.count(); j > 0; j--) {
// Find the referenced IRC user...
- IrcUser *ircUser = net->ircUser(params[j - 1]);
+ IrcUser* ircUser = net->ircUser(params[j - 1]);
// ...and replace components, using short-circuit evaluation as ircUser might be null
// Account, or "*" if blank/nonexistent/logged out
- command = command.replace(
- QString("$%1:account").arg(j),
- (ircUser && !ircUser->account().isEmpty()) ? ircUser->account()
- : QString("*"));
+ command = command.replace(QString("$%1:account").arg(j),
+ (ircUser && !ircUser->account().isEmpty()) ? ircUser->account() : QString("*"));
// Hostname, or "*" if blank/nonexistent
- command = command.replace(
- QString("$%1:hostname").arg(j),
- (ircUser && !ircUser->host().isEmpty()) ? ircUser->host() : QString("*"));
+ command = command.replace(QString("$%1:hostname").arg(j),
+ (ircUser && !ircUser->host().isEmpty()) ? ircUser->host() : QString("*"));
// Identd
// Ident if verified, or "*" if blank/unknown/unverified (prefixed with "~")
// server does not verify idents, it usually won't add "~".
//
// Identd must be replaced before ident to avoid being treated as "$i:ident" + "d"
- command = command.replace(
- QString("$%1:identd").arg(j),
- (ircUser && !ircUser->user().isEmpty()
- && !ircUser->user().startsWith("~"))
- ? ircUser->user() : QString("*"));
+ command = command.replace(QString("$%1:identd").arg(j),
+ (ircUser && !ircUser->user().isEmpty() && !ircUser->user().startsWith("~")) ? ircUser->user()
+ : QString("*"));
// Ident, or "*" if blank/nonexistent
- command = command.replace(
- QString("$%1:ident").arg(j),
- (ircUser && !ircUser->user().isEmpty()) ? ircUser->user() : QString("*"));
+ command = command.replace(QString("$%1:ident").arg(j), (ircUser && !ircUser->user().isEmpty()) ? ircUser->user() : QString("*"));
// Nickname
// Must be replaced last to avoid interferring with more specific aliases
command = command.replace(QString("$%1").arg(j), params[j - 1]);
}
command = command.replace("$0", msg);
- command = command.replace("$channelname", bufferInfo.bufferName()); // legacy
+ command = command.replace("$channelname", bufferInfo.bufferName()); // legacy
command = command.replace("$channel", bufferInfo.bufferName());
- command = command.replace("$currentnick", net->myNick()); // legacy
+ command = command.replace("$currentnick", net->myNick()); // legacy
command = command.replace("$nick", net->myNick());
expandedCommands << command;
}
#include "common-export.h"
-#include <QVariantMap>
#include <utility>
+#include <QVariantMap>
+
#include "bufferinfo.h"
#include "syncableobject.h"
SYNCABLE_OBJECT
public:
- inline AliasManager(QObject *parent = nullptr) : SyncableObject(parent) { setAllowClientUpdates(true); }
- AliasManager &operator=(const AliasManager &other);
-
- struct Alias {
+ inline AliasManager(QObject* parent = nullptr)
+ : SyncableObject(parent)
+ {
+ setAllowClientUpdates(true);
+ }
+ AliasManager& operator=(const AliasManager& other);
+
+ struct Alias
+ {
QString name;
QString expansion;
- Alias(QString name_, QString expansion_) : name(std::move(name_)), expansion(std::move(expansion_)) {}
+ Alias(QString name_, QString expansion_)
+ : name(std::move(name_))
+ , expansion(std::move(expansion_))
+ {}
};
using AliasList = QList<Alias>;
- int indexOf(const QString &name) const;
- inline bool contains(const QString &name) const { return indexOf(name) != -1; }
+ int indexOf(const QString& name) const;
+ inline bool contains(const QString& name) const { return indexOf(name) != -1; }
inline bool isEmpty() const { return _aliases.isEmpty(); }
inline int count() const { return _aliases.count(); }
inline void removeAt(int index) { _aliases.removeAt(index); }
- inline Alias &operator[](int i) { return _aliases[i]; }
- inline const Alias &operator[](int i) const { return _aliases.at(i); }
- inline const AliasList &aliases() const { return _aliases; }
+ inline Alias& operator[](int i) { return _aliases[i]; }
+ inline const Alias& operator[](int i) const { return _aliases.at(i); }
+ inline const AliasList& aliases() const { return _aliases; }
static AliasList defaults();
using CommandList = QList<QPair<BufferInfo, QString>>;
- CommandList processInput(const BufferInfo &info, const QString &message);
+ CommandList processInput(const BufferInfo& info, const QString& message);
public slots:
virtual QVariantMap initAliases() const;
- virtual void initSetAliases(const QVariantMap &aliases);
+ virtual void initSetAliases(const QVariantMap& aliases);
- virtual void addAlias(const QString &name, const QString &expansion);
+ virtual void addAlias(const QString& name, const QString& expansion);
protected:
- void setAliases(const QList<Alias> &aliases) { _aliases = aliases; }
- virtual const Network *network(NetworkId) const = 0; // core and client require different access
+ void setAliases(const QList<Alias>& aliases) { _aliases = aliases; }
+ virtual const Network* network(NetworkId) const = 0; // core and client require different access
private:
- void processInput(const BufferInfo &info, const QString &message, CommandList &previousCommands);
- void expand(const QString &alias, const BufferInfo &bufferInfo, const QString &msg, CommandList &previousCommands);
+ void processInput(const BufferInfo& info, const QString& message, CommandList& previousCommands);
+ void expand(const QString& alias, const BufferInfo& bufferInfo, const QString& msg, CommandList& previousCommands);
AliasList _aliases;
};
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "authhandler.h"
+
#include <QHostAddress>
-#include "authhandler.h"
#include "util.h"
-AuthHandler::AuthHandler(QObject *parent)
+AuthHandler::AuthHandler(QObject* parent)
: QObject(parent)
-{
-
-}
-
+{}
-QTcpSocket *AuthHandler::socket() const
+QTcpSocket* AuthHandler::socket() const
{
return _socket;
}
-
-void AuthHandler::setSocket(QTcpSocket *socket)
+void AuthHandler::setSocket(QTcpSocket* socket)
{
_socket = socket;
connect(socket, selectOverload<QAbstractSocket::SocketError>(&QTcpSocket::error), this, &AuthHandler::onSocketError);
connect(socket, &QAbstractSocket::disconnected, this, &AuthHandler::onSocketDisconnected);
}
-
bool AuthHandler::isLocal() const
{
if (socket()) {
return false;
}
-
// Some errors (e.g. connection refused) don't trigger a disconnected() from the socket, so send this explicitly
// (but make sure it's only sent once!)
void AuthHandler::onSocketError(QAbstractSocket::SocketError error)
}
}
-
void AuthHandler::onSocketDisconnected()
{
if (!_disconnectedSent) {
}
}
-
void AuthHandler::invalidMessage()
{
qWarning() << Q_FUNC_INFO << "No handler for message!";
}
-
void AuthHandler::close()
{
if (_socket && _socket->isOpen())
Q_OBJECT
public:
- AuthHandler(QObject *parent = nullptr);
+ AuthHandler(QObject* parent = nullptr);
- QTcpSocket *socket() const;
+ QTcpSocket* socket() const;
bool isLocal() const;
- virtual void handle(const Protocol::RegisterClient &) { invalidMessage(); }
- virtual void handle(const Protocol::ClientDenied &) { invalidMessage(); }
- virtual void handle(const Protocol::ClientRegistered &) { invalidMessage(); }
- virtual void handle(const Protocol::SetupData &) { invalidMessage(); }
- virtual void handle(const Protocol::SetupFailed &) { invalidMessage(); }
- virtual void handle(const Protocol::SetupDone &) { invalidMessage(); }
- virtual void handle(const Protocol::Login &) { invalidMessage(); }
- virtual void handle(const Protocol::LoginFailed &) { invalidMessage(); }
- virtual void handle(const Protocol::LoginSuccess &) { invalidMessage(); }
- virtual void handle(const Protocol::SessionState &) { invalidMessage(); }
+ virtual void handle(const Protocol::RegisterClient&) { invalidMessage(); }
+ virtual void handle(const Protocol::ClientDenied&) { invalidMessage(); }
+ virtual void handle(const Protocol::ClientRegistered&) { invalidMessage(); }
+ virtual void handle(const Protocol::SetupData&) { invalidMessage(); }
+ virtual void handle(const Protocol::SetupFailed&) { invalidMessage(); }
+ virtual void handle(const Protocol::SetupDone&) { invalidMessage(); }
+ virtual void handle(const Protocol::Login&) { invalidMessage(); }
+ virtual void handle(const Protocol::LoginFailed&) { invalidMessage(); }
+ virtual void handle(const Protocol::LoginSuccess&) { invalidMessage(); }
+ virtual void handle(const Protocol::SessionState&) { invalidMessage(); }
// fallback for unknown types, will trigger an error
template<class T>
- void handle(const T &) { invalidMessage(); }
+ void handle(const T&)
+ {
+ invalidMessage();
+ }
public slots:
void close();
signals:
void disconnected();
- void socketError(QAbstractSocket::SocketError error, const QString &errorString);
+ void socketError(QAbstractSocket::SocketError error, const QString& errorString);
protected:
- void setSocket(QTcpSocket *socket);
+ void setSocket(QTcpSocket* socket);
protected slots:
virtual void onSocketError(QAbstractSocket::SocketError error);
private:
void invalidMessage();
- QTcpSocket *_socket{nullptr}; // FIXME: should be a QSharedPointer? -> premature disconnect before the peer has taken over
+ QTcpSocket* _socket{nullptr}; // FIXME: should be a QSharedPointer? -> premature disconnect before the peer has taken over
bool _disconnectedSent{false};
};
SYNCABLE_OBJECT
public:
- BacklogManager(QObject *parent = nullptr) : SyncableObject(parent) {}
+ BacklogManager(QObject* parent = nullptr)
+ : SyncableObject(parent)
+ {}
public slots:
virtual QVariantList requestBacklog(BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0);
- virtual QVariantList requestBacklogFiltered(BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0, int type = -1, int flags = -1);
- inline virtual void receiveBacklog(BufferId, MsgId, MsgId, int, int, QVariantList) {};
- inline virtual void receiveBacklogFiltered(BufferId, MsgId, MsgId, int, int, int, int, QVariantList) {};
+ virtual QVariantList requestBacklogFiltered(
+ BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0, int type = -1, int flags = -1);
+ inline virtual void receiveBacklog(BufferId, MsgId, MsgId, int, int, QVariantList){};
+ inline virtual void receiveBacklogFiltered(BufferId, MsgId, MsgId, int, int, int, int, QVariantList){};
virtual QVariantList requestBacklogAll(MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0);
- virtual QVariantList requestBacklogAllFiltered(MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0, int type = -1, int flags = -1);
- inline virtual void receiveBacklogAll(MsgId, MsgId, int, int, QVariantList) {};
- inline virtual void receiveBacklogAllFiltered(MsgId, MsgId, int, int, int, int, QVariantList) {};
+ virtual QVariantList requestBacklogAllFiltered(
+ MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0, int type = -1, int flags = -1);
+ inline virtual void receiveBacklogAll(MsgId, MsgId, int, int, QVariantList){};
+ inline virtual void receiveBacklogAllFiltered(MsgId, MsgId, int, int, int, int, QVariantList){};
signals:
void backlogRequested(BufferId, MsgId, MsgId, int, int);
#include "basichandler.h"
-#include <QDebug>
-#include <QMetaMethod>
#include <utility>
-BasicHandler::BasicHandler(QObject *parent)
- : QObject(parent),
- _methodPrefix("handle")
-{
-}
-
+#include <QDebug>
+#include <QMetaMethod>
-BasicHandler::BasicHandler(QString methodPrefix, QObject *parent)
- : QObject(parent),
- _methodPrefix(std::move(methodPrefix))
-{
-}
+BasicHandler::BasicHandler(QObject* parent)
+ : QObject(parent)
+ , _methodPrefix("handle")
+{}
+BasicHandler::BasicHandler(QString methodPrefix, QObject* parent)
+ : QObject(parent)
+ , _methodPrefix(std::move(methodPrefix))
+{}
QStringList BasicHandler::providesHandlers()
{
return handlerHash().keys();
}
-
-const QHash<QString, int> &BasicHandler::handlerHash()
+const QHash<QString, int>& BasicHandler::handlerHash()
{
if (!_initDone) {
for (int i = metaObject()->methodOffset(); i < metaObject()->methodCount(); i++) {
if (!methodSignature.startsWith(_methodPrefix))
continue;
- methodSignature = methodSignature.section('(', 0, 0); // chop the attribute list
- methodSignature = methodSignature.mid(_methodPrefix.length()); // strip "handle" or whatever the prefix is
+ methodSignature = methodSignature.section('(', 0, 0); // chop the attribute list
+ methodSignature = methodSignature.mid(_methodPrefix.length()); // strip "handle" or whatever the prefix is
_handlerHash[methodSignature] = i;
}
_initDone = true;
return _handlerHash;
}
-
-void BasicHandler::handle(const QString &member, QGenericArgument val0,
- QGenericArgument val1, QGenericArgument val2,
- QGenericArgument val3, QGenericArgument val4,
- QGenericArgument val5, QGenericArgument val6,
- QGenericArgument val7, QGenericArgument val8)
+void BasicHandler::handle(const QString& member,
+ QGenericArgument val0,
+ QGenericArgument val1,
+ QGenericArgument val2,
+ QGenericArgument val3,
+ QGenericArgument val4,
+ QGenericArgument val5,
+ QGenericArgument val6,
+ QGenericArgument val7,
+ QGenericArgument val8)
{
// Now we try to find a handler for this message. BTW, I do love the Trolltech guys ;-)
// and now we even have a fast lookup! Thanks thiago!
return;
}
else {
- void *param[] = { nullptr, Q_ARG(QString, member).data(), val0.data(), val1.data(), val2.data(), val3.data(), val4.data(),
- val5.data(), val6.data(), val7.data(), val8.data(), val8.data() };
+ void* param[] = {nullptr,
+ Q_ARG(QString, member).data(),
+ val0.data(),
+ val1.data(),
+ val2.data(),
+ val3.data(),
+ val4.data(),
+ val5.data(),
+ val6.data(),
+ val7.data(),
+ val8.data(),
+ val8.data()};
qt_metacall(QMetaObject::InvokeMetaMethod, _defaultHandler, param);
return;
}
}
- void *param[] = { nullptr, val0.data(), val1.data(), val2.data(), val3.data(), val4.data(),
- val5.data(), val6.data(), val7.data(), val8.data(), val8.data(), nullptr };
+ void* param[] = {nullptr,
+ val0.data(),
+ val1.data(),
+ val2.data(),
+ val3.data(),
+ val4.data(),
+ val5.data(),
+ val6.data(),
+ val7.data(),
+ val8.data(),
+ val8.data(),
+ nullptr};
qt_metacall(QMetaObject::InvokeMetaMethod, handlerHash()[handler], param);
}
#include "common-export.h"
+#include <QGenericArgument>
+#include <QHash>
#include <QObject>
#include <QString>
#include <QStringList>
-#include <QHash>
-#include <QGenericArgument>
class COMMON_EXPORT BasicHandler : public QObject
{
Q_OBJECT
public:
- BasicHandler(QObject *parent = nullptr);
- BasicHandler(QString methodPrefix, QObject *parent = nullptr);
+ BasicHandler(QObject* parent = nullptr);
+ BasicHandler(QString methodPrefix, QObject* parent = nullptr);
QStringList providesHandlers();
protected:
- virtual void handle(const QString &member, QGenericArgument val0 = QGenericArgument(nullptr),
- QGenericArgument val1 = QGenericArgument(), QGenericArgument val2 = QGenericArgument(),
- QGenericArgument val3 = QGenericArgument(), QGenericArgument val4 = QGenericArgument(),
- QGenericArgument val5 = QGenericArgument(), QGenericArgument val6 = QGenericArgument(),
- QGenericArgument val7 = QGenericArgument(), QGenericArgument val8 = QGenericArgument());
+ virtual void handle(const QString& member,
+ QGenericArgument val0 = QGenericArgument(nullptr),
+ QGenericArgument val1 = QGenericArgument(),
+ QGenericArgument val2 = QGenericArgument(),
+ QGenericArgument val3 = QGenericArgument(),
+ QGenericArgument val4 = QGenericArgument(),
+ QGenericArgument val5 = QGenericArgument(),
+ QGenericArgument val6 = QGenericArgument(),
+ QGenericArgument val7 = QGenericArgument(),
+ QGenericArgument val8 = QGenericArgument());
private:
- const QHash<QString, int> &handlerHash();
+ const QHash<QString, int>& handlerHash();
QHash<QString, int> _handlerHash;
int _defaultHandler{-1};
bool _initDone{false};
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include <QString>
-#include <QDataStream>
-#include <QDebug>
-#include <QByteArray>
+#include "bufferinfo.h"
+
#include <utility>
-#include "bufferinfo.h"
+#include <QByteArray>
+#include <QDataStream>
+#include <QDebug>
+#include <QString>
#include "util.h"
BufferInfo::BufferInfo()
- : _bufferId(0),
- _netid(0),
- _bufferName(QString())
-{
-}
-
-
-BufferInfo::BufferInfo(BufferId id, NetworkId networkid, Type type, uint gid, QString buf)
- : _bufferId(id),
- _netid(networkid),
- _type(type),
- _groupId(gid),
- _bufferName(std::move(buf))
-{
-}
-
+ : _bufferId(0)
+ , _netid(0)
+ , _bufferName(QString())
+{}
+
+BufferInfo::BufferInfo(BufferId id, NetworkId networkid, Type type, uint gid, QString buf)
+ : _bufferId(id)
+ , _netid(networkid)
+ , _type(type)
+ , _groupId(gid)
+ , _bufferName(std::move(buf))
+{}
BufferInfo BufferInfo::fakeStatusBuffer(NetworkId networkId)
{
return BufferInfo(0, networkId, StatusBuffer);
}
-
QString BufferInfo::bufferName() const
{
if (isChannelName(_bufferName))
return nickFromMask(_bufferName); // FIXME get rid of global functions and use the Network stuff instead!
}
-
bool BufferInfo::acceptsRegularMessages() const
{
- if(_type == StatusBuffer || _type == InvalidBuffer)
+ if (_type == StatusBuffer || _type == InvalidBuffer)
return false;
return true;
}
-
-QDebug operator<<(QDebug dbg, const BufferInfo &b)
+QDebug operator<<(QDebug dbg, const BufferInfo& b)
{
- dbg.nospace() << "(bufId: " << b.bufferId() << ", netId: " << b.networkId() << ", groupId: " << b.groupId() << ", buf: " << b.bufferName() << ")";
+ dbg.nospace() << "(bufId: " << b.bufferId() << ", netId: " << b.networkId() << ", groupId: " << b.groupId()
+ << ", buf: " << b.bufferName() << ")";
return dbg.space();
}
-
-QDataStream &operator<<(QDataStream &out, const BufferInfo &bufferInfo)
+QDataStream& operator<<(QDataStream& out, const BufferInfo& bufferInfo)
{
out << bufferInfo._bufferId << bufferInfo._netid << (qint16)bufferInfo._type << bufferInfo._groupId << bufferInfo._bufferName.toUtf8();
return out;
}
-
-QDataStream &operator>>(QDataStream &in, BufferInfo &bufferInfo)
+QDataStream& operator>>(QDataStream& in, BufferInfo& bufferInfo)
{
QByteArray buffername;
qint16 bufferType;
return in;
}
-
-uint qHash(const BufferInfo &bufferid)
+uint qHash(const BufferInfo& bufferid)
{
return qHash(bufferid._bufferId);
}
class COMMON_EXPORT BufferInfo
{
public:
- enum Type {
+ enum Type
+ {
InvalidBuffer = 0x00,
StatusBuffer = 0x01,
ChannelBuffer = 0x02,
GroupBuffer = 0x08
};
- enum Activity {
+ enum Activity
+ {
NoActivity = 0x00,
OtherActivity = 0x01,
NewMessage = 0x02,
static BufferInfo fakeStatusBuffer(NetworkId networkId);
inline bool isValid() const { return _bufferId != 0; }
- inline const BufferId &bufferId() const { return _bufferId; }
+ inline const BufferId& bufferId() const { return _bufferId; }
inline void setBufferId(BufferId id) { _bufferId = id; }
- inline const NetworkId &networkId() const { return _netid; }
- inline const Type &type() const { return _type; }
- inline const uint &groupId() const { return _groupId; }
+ inline const NetworkId& networkId() const { return _netid; }
+ inline const Type& type() const { return _type; }
+ inline const uint& groupId() const { return _groupId; }
void setGroupId(uint gid) { _groupId = gid; }
QString bufferName() const;
bool acceptsRegularMessages() const;
- inline bool operator==(const BufferInfo &other) const { return _bufferId == other._bufferId; }
+ inline bool operator==(const BufferInfo& other) const { return _bufferId == other._bufferId; }
private:
BufferId _bufferId;
uint _groupId{0};
QString _bufferName;
- friend uint qHash(const BufferInfo &);
- friend QDataStream &operator<<(QDataStream &out, const BufferInfo &bufferInfo);
- friend QDataStream &operator>>(QDataStream &in, BufferInfo &bufferInfo);
+ friend uint qHash(const BufferInfo&);
+ friend QDataStream& operator<<(QDataStream& out, const BufferInfo& bufferInfo);
+ friend QDataStream& operator>>(QDataStream& in, BufferInfo& bufferInfo);
};
-
-QDataStream &operator<<(QDataStream &out, const BufferInfo &bufferInfo);
-QDataStream &operator>>(QDataStream &in, BufferInfo &bufferInfo);
-QDebug operator<<(QDebug dbg, const BufferInfo &b);
+QDataStream& operator<<(QDataStream& out, const BufferInfo& bufferInfo);
+QDataStream& operator>>(QDataStream& in, BufferInfo& bufferInfo);
+QDebug operator<<(QDebug dbg, const BufferInfo& b);
Q_DECLARE_METATYPE(BufferInfo)
Q_DECLARE_OPERATORS_FOR_FLAGS(BufferInfo::ActivityLevel)
-uint qHash(const BufferInfo &);
+uint qHash(const BufferInfo&);
#include <utility>
-BufferSyncer::BufferSyncer(QObject *parent)
+BufferSyncer::BufferSyncer(QObject* parent)
: SyncableObject(parent)
-{
-}
-
-
-BufferSyncer::BufferSyncer(
- QHash<BufferId, MsgId> lastSeenMsg,
- QHash<BufferId, MsgId> markerLines,
- QHash<BufferId, Message::Types> activities,
- QHash<BufferId, int> highlightCounts,
- QObject *parent
-) : SyncableObject(parent),
- _lastSeenMsg(std::move(lastSeenMsg)),
- _markerLines(std::move(markerLines)),
- _bufferActivities(std::move(activities)),
- _highlightCounts(std::move(highlightCounts))
-{
-}
+{}
+BufferSyncer::BufferSyncer(QHash<BufferId, MsgId> lastSeenMsg,
+ QHash<BufferId, MsgId> markerLines,
+ QHash<BufferId, Message::Types> activities,
+ QHash<BufferId, int> highlightCounts,
+ QObject* parent)
+ : SyncableObject(parent)
+ , _lastSeenMsg(std::move(lastSeenMsg))
+ , _markerLines(std::move(markerLines))
+ , _bufferActivities(std::move(activities))
+ , _highlightCounts(std::move(highlightCounts))
+{}
MsgId BufferSyncer::lastSeenMsg(BufferId buffer) const
{
return _lastSeenMsg.value(buffer, MsgId());
}
-
-bool BufferSyncer::setLastSeenMsg(BufferId buffer, const MsgId &msgId)
+bool BufferSyncer::setLastSeenMsg(BufferId buffer, const MsgId& msgId)
{
if (!msgId.isValid())
return false;
return false;
}
-
MsgId BufferSyncer::markerLine(BufferId buffer) const
{
return _markerLines.value(buffer, MsgId());
}
-
-bool BufferSyncer::setMarkerLine(BufferId buffer, const MsgId &msgId)
+bool BufferSyncer::setMarkerLine(BufferId buffer, const MsgId& msgId)
{
if (!msgId.isValid())
return false;
return true;
}
-
QVariantList BufferSyncer::initLastSeenMsg() const
{
QVariantList list;
QHash<BufferId, MsgId>::const_iterator iter = _lastSeenMsg.constBegin();
while (iter != _lastSeenMsg.constEnd()) {
- list << QVariant::fromValue<BufferId>(iter.key())
- << QVariant::fromValue<MsgId>(iter.value());
+ list << QVariant::fromValue<BufferId>(iter.key()) << QVariant::fromValue<MsgId>(iter.value());
++iter;
}
return list;
}
-
-void BufferSyncer::initSetLastSeenMsg(const QVariantList &list)
+void BufferSyncer::initSetLastSeenMsg(const QVariantList& list)
{
_lastSeenMsg.clear();
Q_ASSERT(list.count() % 2 == 0);
for (int i = 0; i < list.count(); i += 2) {
- setLastSeenMsg(list.at(i).value<BufferId>(), list.at(i+1).value<MsgId>());
+ setLastSeenMsg(list.at(i).value<BufferId>(), list.at(i + 1).value<MsgId>());
}
}
-
QVariantList BufferSyncer::initMarkerLines() const
{
QVariantList list;
QHash<BufferId, MsgId>::const_iterator iter = _markerLines.constBegin();
while (iter != _markerLines.constEnd()) {
- list << QVariant::fromValue<BufferId>(iter.key())
- << QVariant::fromValue<MsgId>(iter.value());
+ list << QVariant::fromValue<BufferId>(iter.key()) << QVariant::fromValue<MsgId>(iter.value());
++iter;
}
return list;
}
-
-void BufferSyncer::initSetMarkerLines(const QVariantList &list)
+void BufferSyncer::initSetMarkerLines(const QVariantList& list)
{
_markerLines.clear();
Q_ASSERT(list.count() % 2 == 0);
for (int i = 0; i < list.count(); i += 2) {
- setMarkerLine(list.at(i).value<BufferId>(), list.at(i+1).value<MsgId>());
+ setMarkerLine(list.at(i).value<BufferId>(), list.at(i + 1).value<MsgId>());
}
}
-
QVariantList BufferSyncer::initActivities() const
{
QVariantList list;
auto iter = _bufferActivities.constBegin();
while (iter != _bufferActivities.constEnd()) {
- list << QVariant::fromValue<BufferId>(iter.key())
- << QVariant::fromValue<int>((int) iter.value());
+ list << QVariant::fromValue<BufferId>(iter.key()) << QVariant::fromValue<int>((int)iter.value());
++iter;
}
return list;
}
-
-void BufferSyncer::initSetActivities(const QVariantList &list)
+void BufferSyncer::initSetActivities(const QVariantList& list)
{
_bufferActivities.clear();
Q_ASSERT(list.count() % 2 == 0);
for (int i = 0; i < list.count(); i += 2) {
- setBufferActivity(list.at(i).value<BufferId>(), list.at(i+1).value<int>());
+ setBufferActivity(list.at(i).value<BufferId>(), list.at(i + 1).value<int>());
}
}
-
Message::Types BufferSyncer::activity(BufferId buffer) const
{
return _bufferActivities.value(buffer, Message::Types());
}
-
void BufferSyncer::removeBuffer(BufferId buffer)
{
if (_lastSeenMsg.contains(buffer))
emit bufferRemoved(buffer);
}
-
void BufferSyncer::mergeBuffersPermanently(BufferId buffer1, BufferId buffer2)
{
if (_lastSeenMsg.contains(buffer2))
emit buffersPermanentlyMerged(buffer1, buffer2);
}
-int BufferSyncer::highlightCount(BufferId buffer) const {
+int BufferSyncer::highlightCount(BufferId buffer) const
+{
return _highlightCounts.value(buffer, 0);
}
-QVariantList BufferSyncer::initHighlightCounts() const {
+QVariantList BufferSyncer::initHighlightCounts() const
+{
QVariantList list;
auto iter = _highlightCounts.constBegin();
while (iter != _highlightCounts.constEnd()) {
- list << QVariant::fromValue<BufferId>(iter.key())
- << QVariant::fromValue<int>((int) iter.value());
+ list << QVariant::fromValue<BufferId>(iter.key()) << QVariant::fromValue<int>((int)iter.value());
++iter;
}
return list;
}
-void BufferSyncer::initSetHighlightCounts(const QVariantList &list) {
+void BufferSyncer::initSetHighlightCounts(const QVariantList& list)
+{
_highlightCounts.clear();
Q_ASSERT(list.count() % 2 == 0);
for (int i = 0; i < list.count(); i += 2) {
- setHighlightCount(list.at(i).value<BufferId>(), list.at(i+1).value<int>());
+ setHighlightCount(list.at(i).value<BufferId>(), list.at(i + 1).value<int>());
}
}
#include "common-export.h"
+#include "message.h"
#include "syncableobject.h"
#include "types.h"
-#include "message.h"
class COMMON_EXPORT BufferSyncer : public SyncableObject
{
SYNCABLE_OBJECT
public:
- explicit BufferSyncer(QObject *parent);
- explicit BufferSyncer(QHash<BufferId, MsgId> lastSeenMsg, QHash<BufferId, MsgId> markerLines, QHash<BufferId, Message::Types> activities, QHash<BufferId, int> highlightCounts, QObject *parent);
+ explicit BufferSyncer(QObject* parent);
+ explicit BufferSyncer(QHash<BufferId, MsgId> lastSeenMsg,
+ QHash<BufferId, MsgId> markerLines,
+ QHash<BufferId, Message::Types> activities,
+ QHash<BufferId, int> highlightCounts,
+ QObject* parent);
MsgId lastSeenMsg(BufferId buffer) const;
MsgId markerLine(BufferId buffer) const;
Message::Types activity(BufferId buffer) const;
int highlightCount(BufferId buffer) const;
- void markActivitiesChanged() {
+ void markActivitiesChanged()
+ {
for (auto buffer : _bufferActivities.keys()) {
emit bufferActivityChanged(buffer, activity(buffer));
}
}
- void markHighlightCountsChanged() {
+ void markHighlightCountsChanged()
+ {
for (auto buffer : _highlightCounts.keys()) {
emit highlightCountChanged(buffer, highlightCount(buffer));
}
public slots:
QVariantList initLastSeenMsg() const;
- void initSetLastSeenMsg(const QVariantList &);
+ void initSetLastSeenMsg(const QVariantList&);
QVariantList initMarkerLines() const;
- void initSetMarkerLines(const QVariantList &);
+ void initSetMarkerLines(const QVariantList&);
QVariantList initActivities() const;
- void initSetActivities(const QVariantList &);
+ void initSetActivities(const QVariantList&);
QVariantList initHighlightCounts() const;
- void initSetHighlightCounts(const QVariantList &);
+ void initSetHighlightCounts(const QVariantList&);
- virtual inline void requestSetLastSeenMsg(BufferId buffer, const MsgId &msgId) { REQUEST(ARG(buffer), ARG(msgId)) }
- virtual inline void requestSetMarkerLine(BufferId buffer, const MsgId &msgId) { REQUEST(ARG(buffer), ARG(msgId)) setMarkerLine(buffer, msgId); }
+ virtual inline void requestSetLastSeenMsg(BufferId buffer, const MsgId& msgId) { REQUEST(ARG(buffer), ARG(msgId)) }
+ virtual inline void requestSetMarkerLine(BufferId buffer, const MsgId& msgId)
+ {
+ REQUEST(ARG(buffer), ARG(msgId)) setMarkerLine(buffer, msgId);
+ }
- virtual inline void setBufferActivity(BufferId buffer, int activity) {
+ virtual inline void setBufferActivity(BufferId buffer, int activity)
+ {
auto flags = Message::Types(activity);
SYNC(ARG(buffer), ARG(activity));
_bufferActivities[buffer] = flags;
emit bufferActivityChanged(buffer, flags);
}
- virtual inline void setHighlightCount(BufferId buffer, int count) {
+ virtual inline void setHighlightCount(BufferId buffer, int count)
+ {
SYNC(ARG(buffer), ARG(count));
_highlightCounts[buffer] = count;
emit highlightCountChanged(buffer, count);
virtual void removeBuffer(BufferId buffer);
virtual inline void requestRenameBuffer(BufferId buffer, QString newName) { REQUEST(ARG(buffer), ARG(newName)) }
- virtual inline void renameBuffer(BufferId buffer, QString newName) { SYNC(ARG(buffer), ARG(newName)) emit bufferRenamed(buffer, newName); }
+ virtual inline void renameBuffer(BufferId buffer, QString newName)
+ {
+ SYNC(ARG(buffer), ARG(newName)) emit bufferRenamed(buffer, newName);
+ }
virtual inline void requestMergeBuffersPermanently(BufferId buffer1, BufferId buffer2) { emit REQUEST(ARG(buffer1), ARG(buffer2)) }
virtual void mergeBuffersPermanently(BufferId buffer1, BufferId buffer2);
virtual inline void markBufferAsRead(BufferId buffer) { SYNC(ARG(buffer)) emit bufferMarkedAsRead(buffer); }
signals:
- void lastSeenMsgSet(BufferId buffer, const MsgId &msgId);
- void markerLineSet(BufferId buffer, const MsgId &msgId);
+ void lastSeenMsgSet(BufferId buffer, const MsgId& msgId);
+ void markerLineSet(BufferId buffer, const MsgId& msgId);
void bufferRemoved(BufferId buffer);
void bufferRenamed(BufferId buffer, QString newName);
void buffersPermanentlyMerged(BufferId buffer1, BufferId buffer2);
void highlightCountChanged(BufferId, int);
protected slots:
- bool setLastSeenMsg(BufferId buffer, const MsgId &msgId);
- bool setMarkerLine(BufferId buffer, const MsgId &msgId);
+ bool setLastSeenMsg(BufferId buffer, const MsgId& msgId);
+ bool setMarkerLine(BufferId buffer, const MsgId& msgId);
protected:
inline QList<BufferId> lastSeenBufferIds() const { return _lastSeenMsg.keys(); }
#include "bufferviewconfig.h"
-BufferViewConfig::BufferViewConfig(int bufferViewId, QObject *parent)
- : SyncableObject(parent),
- _bufferViewId(bufferViewId)
+BufferViewConfig::BufferViewConfig(int bufferViewId, QObject* parent)
+ : SyncableObject(parent)
+ , _bufferViewId(bufferViewId)
{
setObjectName(QString::number(bufferViewId));
}
-
-BufferViewConfig::BufferViewConfig(int bufferViewId, const QVariantMap &properties, QObject *parent)
- : SyncableObject(parent),
- _bufferViewId(bufferViewId)
+BufferViewConfig::BufferViewConfig(int bufferViewId, const QVariantMap& properties, QObject* parent)
+ : SyncableObject(parent)
+ , _bufferViewId(bufferViewId)
{
fromVariantMap(properties);
setObjectName(QString::number(bufferViewId));
}
-
-void BufferViewConfig::setBufferViewName(const QString &bufferViewName)
+void BufferViewConfig::setBufferViewName(const QString& bufferViewName)
{
if (_bufferViewName == bufferViewName)
return;
emit bufferViewNameSet(bufferViewName);
}
-
-void BufferViewConfig::setNetworkId(const NetworkId &networkId)
+void BufferViewConfig::setNetworkId(const NetworkId& networkId)
{
if (_networkId == networkId)
return;
emit configChanged();
}
-
void BufferViewConfig::setAddNewBuffersAutomatically(bool addNewBuffersAutomatically)
{
if (_addNewBuffersAutomatically == addNewBuffersAutomatically)
emit configChanged();
}
-
void BufferViewConfig::setSortAlphabetically(bool sortAlphabetically)
{
if (_sortAlphabetically == sortAlphabetically)
emit configChanged();
}
-
void BufferViewConfig::setDisableDecoration(bool disableDecoration)
{
if (_disableDecoration == disableDecoration)
SYNC(ARG(disableDecoration))
}
-
void BufferViewConfig::setAllowedBufferTypes(int bufferTypes)
{
if (_allowedBufferTypes == bufferTypes)
emit configChanged();
}
-
void BufferViewConfig::setMinimumActivity(int activity)
{
if (_minimumActivity == activity)
emit configChanged();
}
-
void BufferViewConfig::setHideInactiveBuffers(bool hideInactiveBuffers)
{
if (_hideInactiveBuffers == hideInactiveBuffers)
emit configChanged();
}
-void BufferViewConfig::setShowSearch(bool showSearch) {
+void BufferViewConfig::setShowSearch(bool showSearch)
+{
if (_showSearch == showSearch) {
return;
}
emit configChanged();
}
-
QVariantList BufferViewConfig::initBufferList() const
{
QVariantList buffers;
- foreach(BufferId bufferId, _buffers) {
+ foreach (BufferId bufferId, _buffers) {
buffers << qVariantFromValue(bufferId);
}
return buffers;
}
-
-void BufferViewConfig::initSetBufferList(const QVariantList &buffers)
+void BufferViewConfig::initSetBufferList(const QVariantList& buffers)
{
_buffers.clear();
- foreach(QVariant buffer, buffers) {
+ foreach (QVariant buffer, buffers) {
_buffers << buffer.value<BufferId>();
}
- emit configChanged(); // used to track changes in the settingspage
+ emit configChanged(); // used to track changes in the settingspage
}
-
-void BufferViewConfig::initSetBufferList(const QList<BufferId> &buffers)
+void BufferViewConfig::initSetBufferList(const QList<BufferId>& buffers)
{
_buffers.clear();
- foreach(BufferId bufferId, buffers) {
+ foreach (BufferId bufferId, buffers) {
_buffers << bufferId;
}
- emit configChanged(); // used to track changes in the settingspage
+ emit configChanged(); // used to track changes in the settingspage
}
-
QVariantList BufferViewConfig::initRemovedBuffers() const
{
QVariantList removedBuffers;
- foreach(BufferId bufferId, _removedBuffers) {
+ foreach (BufferId bufferId, _removedBuffers) {
removedBuffers << qVariantFromValue(bufferId);
}
return removedBuffers;
}
-
-void BufferViewConfig::initSetRemovedBuffers(const QVariantList &buffers)
+void BufferViewConfig::initSetRemovedBuffers(const QVariantList& buffers)
{
_removedBuffers.clear();
- foreach(QVariant buffer, buffers) {
+ foreach (QVariant buffer, buffers) {
_removedBuffers << buffer.value<BufferId>();
}
}
-
QVariantList BufferViewConfig::initTemporarilyRemovedBuffers() const
{
QVariantList temporarilyRemovedBuffers;
- foreach(BufferId bufferId, _temporarilyRemovedBuffers) {
+ foreach (BufferId bufferId, _temporarilyRemovedBuffers) {
temporarilyRemovedBuffers << qVariantFromValue(bufferId);
}
return temporarilyRemovedBuffers;
}
-
-void BufferViewConfig::initSetTemporarilyRemovedBuffers(const QVariantList &buffers)
+void BufferViewConfig::initSetTemporarilyRemovedBuffers(const QVariantList& buffers)
{
_temporarilyRemovedBuffers.clear();
- foreach(QVariant buffer, buffers) {
+ foreach (QVariant buffer, buffers) {
_temporarilyRemovedBuffers << buffer.value<BufferId>();
}
}
-
-void BufferViewConfig::addBuffer(const BufferId &bufferId, int pos)
+void BufferViewConfig::addBuffer(const BufferId& bufferId, int pos)
{
if (_buffers.contains(bufferId))
return;
emit configChanged();
}
-
-void BufferViewConfig::moveBuffer(const BufferId &bufferId, int pos)
+void BufferViewConfig::moveBuffer(const BufferId& bufferId, int pos)
{
if (!_buffers.contains(bufferId))
return;
emit configChanged();
}
-
-void BufferViewConfig::removeBuffer(const BufferId &bufferId)
+void BufferViewConfig::removeBuffer(const BufferId& bufferId)
{
if (_buffers.contains(bufferId))
_buffers.removeAt(_buffers.indexOf(bufferId));
emit configChanged();
}
-
-void BufferViewConfig::removeBufferPermanently(const BufferId &bufferId)
+void BufferViewConfig::removeBufferPermanently(const BufferId& bufferId)
{
if (_buffers.contains(bufferId))
_buffers.removeAt(_buffers.indexOf(bufferId));
#include "common-export.h"
-#include "syncableobject.h"
-
#include "bufferinfo.h"
+#include "syncableobject.h"
#include "types.h"
class COMMON_EXPORT BufferViewConfig : public SyncableObject
Q_PROPERTY(int minimumActivity READ minimumActivity WRITE setMinimumActivity)
Q_PROPERTY(bool showSearch READ showSearch WRITE setShowSearch)
-public :
- BufferViewConfig(int bufferViewId, QObject *parent = nullptr);
- BufferViewConfig(int bufferViewId, const QVariantMap &properties, QObject *parent = nullptr);
+public:
+ BufferViewConfig(int bufferViewId, QObject* parent = nullptr);
+ BufferViewConfig(int bufferViewId, const QVariantMap& properties, QObject* parent = nullptr);
public slots:
inline int bufferViewId() const { return _bufferViewId; }
- inline const QString &bufferViewName() const { return _bufferViewName; }
- void setBufferViewName(const QString &bufferViewName);
+ inline const QString& bufferViewName() const { return _bufferViewName; }
+ void setBufferViewName(const QString& bufferViewName);
- inline const NetworkId &networkId() const { return _networkId; }
- void setNetworkId(const NetworkId &networkId);
+ inline const NetworkId& networkId() const { return _networkId; }
+ void setNetworkId(const NetworkId& networkId);
inline bool addNewBuffersAutomatically() const { return _addNewBuffersAutomatically; }
void setAddNewBuffersAutomatically(bool addNewBuffersAutomatically);
inline bool showSearch() const { return _showSearch; }
void setShowSearch(bool showSearch);
- virtual inline void requestSetBufferViewName(const QString &bufferViewName) { REQUEST(ARG(bufferViewName)) }
+ virtual inline void requestSetBufferViewName(const QString& bufferViewName) { REQUEST(ARG(bufferViewName)) }
- const QList<BufferId> &bufferList() const { return _buffers; }
- const QSet<BufferId> &removedBuffers() const { return _removedBuffers; }
- const QSet<BufferId> &temporarilyRemovedBuffers() const { return _temporarilyRemovedBuffers; }
+ const QList<BufferId>& bufferList() const { return _buffers; }
+ const QSet<BufferId>& removedBuffers() const { return _removedBuffers; }
+ const QSet<BufferId>& temporarilyRemovedBuffers() const { return _temporarilyRemovedBuffers; }
QVariantList initBufferList() const;
- void initSetBufferList(const QVariantList &buffers);
- void initSetBufferList(const QList<BufferId> &buffers);
+ void initSetBufferList(const QVariantList& buffers);
+ void initSetBufferList(const QList<BufferId>& buffers);
QVariantList initRemovedBuffers() const;
- void initSetRemovedBuffers(const QVariantList &buffers);
+ void initSetRemovedBuffers(const QVariantList& buffers);
QVariantList initTemporarilyRemovedBuffers() const;
- void initSetTemporarilyRemovedBuffers(const QVariantList &buffers);
-
- void addBuffer(const BufferId &bufferId, int pos);
- virtual inline void requestAddBuffer(const BufferId &bufferId, int pos) { REQUEST(ARG(bufferId), ARG(pos)) }
- void moveBuffer(const BufferId &bufferId, int pos);
- virtual inline void requestMoveBuffer(const BufferId &bufferId, int pos) { REQUEST(ARG(bufferId), ARG(pos)) }
- void removeBuffer(const BufferId &bufferId);
- virtual inline void requestRemoveBuffer(const BufferId &bufferId) { REQUEST(ARG(bufferId)) }
- void removeBufferPermanently(const BufferId &bufferId);
- virtual inline void requestRemoveBufferPermanently(const BufferId &bufferId) { REQUEST(ARG(bufferId)) }
-
-signals:
- void bufferViewNameSet(const QString &bufferViewName); // invalidate
+ void initSetTemporarilyRemovedBuffers(const QVariantList& buffers);
+
+ void addBuffer(const BufferId& bufferId, int pos);
+ virtual inline void requestAddBuffer(const BufferId& bufferId, int pos) { REQUEST(ARG(bufferId), ARG(pos)) }
+ void moveBuffer(const BufferId& bufferId, int pos);
+ virtual inline void requestMoveBuffer(const BufferId& bufferId, int pos) { REQUEST(ARG(bufferId), ARG(pos)) }
+ void removeBuffer(const BufferId& bufferId);
+ virtual inline void requestRemoveBuffer(const BufferId& bufferId) { REQUEST(ARG(bufferId)) }
+ void removeBufferPermanently(const BufferId& bufferId);
+ virtual inline void requestRemoveBufferPermanently(const BufferId& bufferId){REQUEST(ARG(bufferId))}
+
+ signals : void bufferViewNameSet(const QString& bufferViewName); // invalidate
void configChanged();
- void networkIdSet(const NetworkId &networkId);
-// void addNewBuffersAutomaticallySet(bool addNewBuffersAutomatically); // invalidate
-// void sortAlphabeticallySet(bool sortAlphabetically); // invalidate
-// // void disableDecorationSet(bool disableDecoration); // invalidate
-// void allowedBufferTypesSet(int allowedBufferTypes); // invalidate
-// void minimumActivitySet(int activity); // invalidate
-// void hideInactiveBuffersSet(bool hideInactiveBuffers); // invalidate
- void bufferListSet(); // invalidate
-
- void bufferAdded(const BufferId &bufferId, int pos);
-// void addBufferRequested(const BufferId &bufferId, int pos);
- void bufferMoved(const BufferId &bufferId, int pos);
-// void moveBufferRequested(const BufferId &bufferId, int pos);
- void bufferRemoved(const BufferId &bufferId);
- void bufferPermanentlyRemoved(const BufferId &bufferId);
-// void removeBufferRequested(const BufferId &bufferId);
-// void removeBufferPermanentlyRequested(const BufferId &bufferId);
-
-// void setBufferViewNameRequested(const QString &bufferViewName);
+ void networkIdSet(const NetworkId& networkId);
+ // void addNewBuffersAutomaticallySet(bool addNewBuffersAutomatically); // invalidate
+ // void sortAlphabeticallySet(bool sortAlphabetically); // invalidate
+ // // void disableDecorationSet(bool disableDecoration); // invalidate
+ // void allowedBufferTypesSet(int allowedBufferTypes); // invalidate
+ // void minimumActivitySet(int activity); // invalidate
+ // void hideInactiveBuffersSet(bool hideInactiveBuffers); // invalidate
+ void bufferListSet(); // invalidate
+
+ void bufferAdded(const BufferId& bufferId, int pos);
+ // void addBufferRequested(const BufferId &bufferId, int pos);
+ void bufferMoved(const BufferId& bufferId, int pos);
+ // void moveBufferRequested(const BufferId &bufferId, int pos);
+ void bufferRemoved(const BufferId& bufferId);
+ void bufferPermanentlyRemoved(const BufferId& bufferId);
+ // void removeBufferRequested(const BufferId &bufferId);
+ // void removeBufferPermanentlyRequested(const BufferId &bufferId);
+
+ // void setBufferViewNameRequested(const QString &bufferViewName);
private:
- int _bufferViewId = 0; ///< ID of the associated BufferView
- QString _bufferViewName = {}; ///< Display name of the associated BufferView
- NetworkId _networkId = {}; ///< Network ID this buffer belongs to
-
- bool _addNewBuffersAutomatically = true; ///< Automatically add new buffers when created
- bool _sortAlphabetically = true; ///< Sort buffers alphabetically
- bool _hideInactiveBuffers = false; ///< Hide buffers without activity
- bool _hideInactiveNetworks = false; ///< Hide networks without activity
- bool _disableDecoration = false; ///< Disable buffer decoration (not fully implemented)
+ int _bufferViewId = 0; ///< ID of the associated BufferView
+ QString _bufferViewName = {}; ///< Display name of the associated BufferView
+ NetworkId _networkId = {}; ///< Network ID this buffer belongs to
+
+ bool _addNewBuffersAutomatically = true; ///< Automatically add new buffers when created
+ bool _sortAlphabetically = true; ///< Sort buffers alphabetically
+ bool _hideInactiveBuffers = false; ///< Hide buffers without activity
+ bool _hideInactiveNetworks = false; ///< Hide networks without activity
+ bool _disableDecoration = false; ///< Disable buffer decoration (not fully implemented)
/// Buffer types allowed within this view
- int _allowedBufferTypes = (BufferInfo::StatusBuffer | BufferInfo::ChannelBuffer
- | BufferInfo::QueryBuffer | BufferInfo::GroupBuffer);
- int _minimumActivity = 0; ///< Minimum activity for a buffer to show
- bool _showSearch = false; ///< Persistently show the buffer search UI
+ int _allowedBufferTypes = (BufferInfo::StatusBuffer | BufferInfo::ChannelBuffer | BufferInfo::QueryBuffer | BufferInfo::GroupBuffer);
+ int _minimumActivity = 0; ///< Minimum activity for a buffer to show
+ bool _showSearch = false; ///< Persistently show the buffer search UI
QList<BufferId> _buffers;
QSet<BufferId> _removedBuffers;
#include "bufferviewconfig.h"
#include "signalproxy.h"
-BufferViewManager::BufferViewManager(SignalProxy *proxy, QObject *parent)
- : SyncableObject(parent),
- _proxy(proxy)
+BufferViewManager::BufferViewManager(SignalProxy* proxy, QObject* parent)
+ : SyncableObject(parent)
+ , _proxy(proxy)
{
_proxy->synchronize(this);
}
-
-BufferViewConfig *BufferViewManager::bufferViewConfig(int bufferViewId) const
+BufferViewConfig* BufferViewManager::bufferViewConfig(int bufferViewId) const
{
if (_bufferViewConfigs.contains(bufferViewId))
return _bufferViewConfigs[bufferViewId];
return nullptr;
}
-
-BufferViewConfig *BufferViewManager::bufferViewConfigFactory(int bufferViewConfigId)
+BufferViewConfig* BufferViewManager::bufferViewConfigFactory(int bufferViewConfigId)
{
return new BufferViewConfig(bufferViewConfigId, this);
}
-
void BufferViewManager::addBufferViewConfig(int bufferViewConfigId)
{
if (_bufferViewConfigs.contains(bufferViewConfigId)) {
addBufferViewConfig(bufferViewConfigFactory(bufferViewConfigId));
}
-
-void BufferViewManager::addBufferViewConfig(BufferViewConfig *config)
+void BufferViewManager::addBufferViewConfig(BufferViewConfig* config)
{
if (_bufferViewConfigs.contains(config->bufferViewId())) {
delete config;
emit bufferViewConfigAdded(bufferViewId);
}
-
void BufferViewManager::deleteBufferViewConfig(int bufferViewConfigId)
{
if (!_bufferViewConfigs.contains(bufferViewConfigId))
emit bufferViewConfigDeleted(bufferViewConfigId);
}
-
QVariantList BufferViewManager::initBufferViewIds() const
{
QVariantList bufferViewIds;
return bufferViewIds;
}
-
void BufferViewManager::initSetBufferViewIds(const QVariantList bufferViewIds)
{
- for (auto &&id : bufferViewIds) {
+ for (auto&& id : bufferViewIds) {
addBufferViewConfig(id.value<int>());
}
}
#include "common-export.h"
-#include "syncableobject.h"
-
-#include <QList>
#include <QHash>
+#include <QList>
+
+#include "syncableobject.h"
class BufferViewConfig;
class SignalProxy;
SYNCABLE_OBJECT
public:
- BufferViewManager(SignalProxy *proxy, QObject *parent = nullptr);
+ BufferViewManager(SignalProxy* proxy, QObject* parent = nullptr);
- inline QList<BufferViewConfig *> bufferViewConfigs() const { return _bufferViewConfigs.values(); }
- BufferViewConfig *bufferViewConfig(int bufferViewId) const;
+ inline QList<BufferViewConfig*> bufferViewConfigs() const { return _bufferViewConfigs.values(); }
+ BufferViewConfig* bufferViewConfig(int bufferViewId) const;
public slots:
QVariantList initBufferViewIds() const;
void addBufferViewConfig(int bufferViewConfigId);
void deleteBufferViewConfig(int bufferViewConfigId);
- virtual inline void requestCreateBufferView(const QVariantMap &properties) { REQUEST(ARG(properties)) }
- virtual inline void requestCreateBufferViews(const QVariantList &properties) { REQUEST(ARG(properties)) }
+ virtual inline void requestCreateBufferView(const QVariantMap& properties) { REQUEST(ARG(properties)) }
+ virtual inline void requestCreateBufferViews(const QVariantList& properties) { REQUEST(ARG(properties)) }
virtual inline void requestDeleteBufferView(int bufferViewId) { REQUEST(ARG(bufferViewId)) }
- virtual inline void requestDeleteBufferViews(const QVariantList &bufferViews) { REQUEST(ARG(bufferViews)) }
+ virtual inline void requestDeleteBufferViews(const QVariantList& bufferViews) { REQUEST(ARG(bufferViews)) }
-signals:
- void bufferViewConfigAdded(int bufferViewConfigId);
+ signals : void bufferViewConfigAdded(int bufferViewConfigId);
void bufferViewConfigDeleted(int bufferViewConfigId);
-// void createBufferViewRequested(const QVariantMap &properties);
-// void createBufferViewsRequested(const QVariantList &properties);
-// void deleteBufferViewRequested(int bufferViewId);
-// void deleteBufferViewsRequested(const QVariantList &bufferViews);
+ // void createBufferViewRequested(const QVariantMap &properties);
+ // void createBufferViewsRequested(const QVariantList &properties);
+ // void deleteBufferViewRequested(int bufferViewId);
+ // void deleteBufferViewsRequested(const QVariantList &bufferViews);
protected:
- using BufferViewConfigHash = QHash<int, BufferViewConfig *>;
- inline const BufferViewConfigHash &bufferViewConfigHash() { return _bufferViewConfigs; }
- virtual BufferViewConfig *bufferViewConfigFactory(int bufferViewConfigId);
+ using BufferViewConfigHash = QHash<int, BufferViewConfig*>;
+ inline const BufferViewConfigHash& bufferViewConfigHash() { return _bufferViewConfigs; }
+ virtual BufferViewConfig* bufferViewConfigFactory(int bufferViewConfigId);
- void addBufferViewConfig(BufferViewConfig *config);
+ void addBufferViewConfig(BufferViewConfig* config);
private:
BufferViewConfigHash _bufferViewConfigs;
- SignalProxy *_proxy;
+ SignalProxy* _proxy;
};
#include <QTcpSocket>
#include <QTimer>
-const int maxBufferSize = 64 * 1024 * 1024; // protect us from zip bombs
-const int ioBufferSize = 64 * 1024; // chunk size for inflate/deflate; should not be too large as we preallocate that space!
-
-Compressor::Compressor(QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent)
- : QObject(parent),
- _socket(socket),
- _level(level),
- _inflater(nullptr),
- _deflater(nullptr)
+const int maxBufferSize = 64 * 1024 * 1024; // protect us from zip bombs
+const int ioBufferSize = 64 * 1024; // chunk size for inflate/deflate; should not be too large as we preallocate that space!
+
+Compressor::Compressor(QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent)
+ : QObject(parent)
+ , _socket(socket)
+ , _level(level)
+ , _inflater(nullptr)
+ , _deflater(nullptr)
{
connect(socket, &QIODevice::readyRead, this, &Compressor::readData);
QTimer::singleShot(0, this, &Compressor::readData);
}
-
Compressor::~Compressor()
{
// release resources allocated by zlib
}
}
-
bool Compressor::initStreams()
{
int zlevel;
- switch(compressionLevel()) {
- case BestCompression:
- zlevel = 9;
- break;
- case BestSpeed:
- zlevel = 1;
- break;
- default:
- zlevel = Z_DEFAULT_COMPRESSION;
+ switch (compressionLevel()) {
+ case BestCompression:
+ zlevel = 9;
+ break;
+ case BestSpeed:
+ zlevel = 1;
+ break;
+ default:
+ zlevel = Z_DEFAULT_COMPRESSION;
}
_inflater = new z_stream;
return false;
}
- _inputBuffer.reserve(ioBufferSize); // pre-allocate space
- _outputBuffer.resize(ioBufferSize); // not a typo; we never change the size of this buffer anyway (we *do* for _inputBuffer!)
+ _inputBuffer.reserve(ioBufferSize); // pre-allocate space
+ _outputBuffer.resize(ioBufferSize); // not a typo; we never change the size of this buffer anyway (we *do* for _inputBuffer!)
qDebug() << "Enabling compression...";
return true;
}
-
-
qint64 Compressor::bytesAvailable() const
{
return _readBuffer.size();
}
-
-qint64 Compressor::read(char *data, qint64 maxSize)
+qint64 Compressor::read(char* data, qint64 maxSize)
{
if (maxSize <= 0)
maxSize = _readBuffer.size();
return n;
}
-
// The usual usage pattern is to write a blocksize first, followed by the actual data.
// By setting NoFlush, one can indicate that the write buffer should not immediately be
// written, which should make things a bit more efficient.
-qint64 Compressor::write(const char *data, qint64 count, WriteBufferHint flush)
+qint64 Compressor::write(const char* data, qint64 count, WriteBufferHint flush)
{
int pos = _writeBuffer.size();
_writeBuffer.resize(pos + count);
return count;
}
-
void Compressor::readData()
{
// don't try to read more data if we're already closing
- if (_socket->state() != QAbstractSocket::ConnectedState)
+ if (_socket->state() != QAbstractSocket::ConnectedState)
return;
if (!_socket->bytesAvailable() || _readBuffer.size() >= maxBufferSize)
_readBuffer.resize(_readBuffer.size() + ioBufferSize);
_inputBuffer.append(_socket->read(ioBufferSize - _inputBuffer.size()));
- _inflater->next_in = reinterpret_cast<unsigned char *>(_inputBuffer.data());
+ _inflater->next_in = reinterpret_cast<unsigned char*>(_inputBuffer.data());
_inflater->avail_in = _inputBuffer.size();
- _inflater->next_out = reinterpret_cast<unsigned char *>(_readBuffer.data() + _readBuffer.size() - ioBufferSize);
+ _inflater->next_out = reinterpret_cast<unsigned char*>(_readBuffer.data() + _readBuffer.size() - ioBufferSize);
_inflater->avail_out = ioBufferSize;
- const unsigned char *orig_out = _inflater->next_out; // so we see if we have actually produced any output
+ const unsigned char* orig_out = _inflater->next_out; // so we see if we have actually produced any output
- int status = inflate(_inflater, Z_SYNC_FLUSH); // get as much data as possible
+ int status = inflate(_inflater, Z_SYNC_FLUSH); // get as much data as possible
// adjust input and output buffers
- _readBuffer.resize(_inflater->next_out - reinterpret_cast<unsigned char *>(_readBuffer.data()));
+ _readBuffer.resize(_inflater->next_out - reinterpret_cast<unsigned char*>(_readBuffer.data()));
if (_inflater->avail_in > 0)
memmove(_inputBuffer.data(), _inflater->next_in, _inflater->avail_in);
_inputBuffer.resize(_inflater->avail_in);
if (_inflater->next_out != orig_out)
emit readyRead();
- switch(status) {
- case Z_NEED_DICT:
- case Z_DATA_ERROR:
- case Z_MEM_ERROR:
- case Z_STREAM_ERROR:
- qWarning() << "Error while decompressing stream:" << status;
- emit error(StreamError);
- return;
- case Z_BUF_ERROR:
- // means that we need more input to continue, so this is not an actual error
- return;
- case Z_STREAM_END:
- qWarning() << "Reached end of zlib stream!"; // this should really never happen
- return;
- default:
- // just try to get more out of the stream
- break;
+ switch (status) {
+ case Z_NEED_DICT:
+ case Z_DATA_ERROR:
+ case Z_MEM_ERROR:
+ case Z_STREAM_ERROR:
+ qWarning() << "Error while decompressing stream:" << status;
+ emit error(StreamError);
+ return;
+ case Z_BUF_ERROR:
+ // means that we need more input to continue, so this is not an actual error
+ return;
+ case Z_STREAM_END:
+ qWarning() << "Reached end of zlib stream!"; // this should really never happen
+ return;
+ default:
+ // just try to get more out of the stream
+ break;
}
}
- //qDebug() << "inflate in:" << _inflater->total_in << "out:" << _inflater->total_out << "ratio:" << (double)_inflater->total_in/_inflater->total_out;
+ // qDebug() << "inflate in:" << _inflater->total_in << "out:" << _inflater->total_out << "ratio:" << (double)_inflater->total_in/_inflater->total_out;
}
-
void Compressor::writeData()
{
if (compressionLevel() == NoCompression) {
return;
}
- _deflater->next_in = reinterpret_cast<unsigned char *>(_writeBuffer.data());
+ _deflater->next_in = reinterpret_cast<unsigned char*>(_writeBuffer.data());
_deflater->avail_in = _writeBuffer.size();
int status;
do {
- _deflater->next_out = reinterpret_cast<unsigned char *>(_outputBuffer.data());
+ _deflater->next_out = reinterpret_cast<unsigned char*>(_outputBuffer.data());
_deflater->avail_out = ioBufferSize;
status = deflate(_deflater, Z_PARTIAL_FLUSH);
if (status != Z_OK && status != Z_BUF_ERROR) {
}
if (_deflater->avail_out == static_cast<unsigned int>(ioBufferSize))
- continue; // nothing to write here
+ continue; // nothing to write here
if (!_socket->write(_outputBuffer.constData(), ioBufferSize - _deflater->avail_out)) {
qWarning() << "Error while writing to socket:" << _socket->errorString();
emit error(DeviceError);
return;
}
- } while (_deflater->avail_out == 0); // the output buffer being full is the only reason we should have to loop here!
+ } while (_deflater->avail_out == 0); // the output buffer being full is the only reason we should have to loop here!
if (_deflater->avail_in > 0) {
qWarning() << "Oops, something weird happened: data still remaining in write buffer!";
_writeBuffer.resize(0);
- //qDebug() << "deflate in:" << _deflater->total_in << "out:" << _deflater->total_out << "ratio:" << (double)_deflater->total_out/_deflater->total_in;
+ // qDebug() << "deflate in:" << _deflater->total_in << "out:" << _deflater->total_out << "ratio:" << (double)_deflater->total_out/_deflater->total_in;
}
-
void Compressor::flush()
{
if (compressionLevel() == NoCompression && _socket->state() == QAbstractSocket::ConnectedState)
#pragma once
-#include <zlib.h>
-
#include <QObject>
+#include <zlib.h>
+
class QTcpSocket;
class Compressor : public QObject
Q_OBJECT
public:
- enum CompressionLevel {
+ enum CompressionLevel
+ {
NoCompression,
DefaultCompression,
BestCompression,
BestSpeed
};
- enum Error {
+ enum Error
+ {
NoError,
StreamError,
DeviceError
};
- enum WriteBufferHint {
+ enum WriteBufferHint
+ {
NoFlush,
Flush
};
- Compressor(QTcpSocket *socket, CompressionLevel level, QObject *parent = nullptr);
+ Compressor(QTcpSocket* socket, CompressionLevel level, QObject* parent = nullptr);
~Compressor() override;
CompressionLevel compressionLevel() const { return _level; }
qint64 bytesAvailable() const;
- qint64 read(char *data, qint64 maxSize);
- qint64 write(const char *data, qint64 count, WriteBufferHint flush = Flush);
+ qint64 read(char* data, qint64 maxSize);
+ qint64 write(const char* data, qint64 count, WriteBufferHint flush = Flush);
void flush();
void writeData();
private:
- QTcpSocket *_socket;
+ QTcpSocket* _socket;
CompressionLevel _level;
QByteArray _readBuffer;
#include "coreinfo.h"
-CoreInfo::CoreInfo(QObject *parent) : SyncableObject(parent) {}
+CoreInfo::CoreInfo(QObject* parent)
+ : SyncableObject(parent)
+{}
QVariantMap CoreInfo::coreData() const
{
return _coreData;
}
-void CoreInfo::setCoreData(const QVariantMap &coreData)
+void CoreInfo::setCoreData(const QVariantMap& coreData)
{
_coreData = coreData;
SYNC(ARG(coreData));
Q_PROPERTY(QVariantMap coreData READ coreData WRITE setCoreData)
public:
- explicit CoreInfo(QObject *parent = nullptr);
- inline QVariant &at(const QString &key) { return _coreData[key]; }
+ explicit CoreInfo(QObject* parent = nullptr);
+ inline QVariant& at(const QString& key) { return _coreData[key]; }
void setConnectedClientData(int, QVariantList);
public slots:
QVariantMap coreData() const;
- void setCoreData(const QVariantMap &);
+ void setCoreData(const QVariantMap&);
private:
QVariantMap _coreData;
#include "ctcpevent.h"
-Event *CtcpEvent::create(EventManager::EventType type, QVariantMap &map, Network *network)
+Event* CtcpEvent::create(EventManager::EventType type, QVariantMap& map, Network* network)
{
if (type == EventManager::CtcpEvent || type == EventManager::CtcpEventFlush)
return new CtcpEvent(type, map, network);
return nullptr;
}
-
-CtcpEvent::CtcpEvent(EventManager::EventType type, QVariantMap &map, Network *network)
+CtcpEvent::CtcpEvent(EventManager::EventType type, QVariantMap& map, Network* network)
: IrcEvent(type, map, network)
{
_ctcpType = static_cast<CtcpType>(map.take("ctcpType").toInt());
_uuid = map.take("uuid").toString();
}
-
-void CtcpEvent::toVariantMap(QVariantMap &map) const
+void CtcpEvent::toVariantMap(QVariantMap& map) const
{
IrcEvent::toVariantMap(map);
map["ctcpType"] = ctcpType();
#include "common-export.h"
-#include "ircevent.h"
+#include <utility>
#include <QUuid>
-#include <utility>
+
+#include "ircevent.h"
class COMMON_EXPORT CtcpEvent : public IrcEvent
{
public:
- enum CtcpType {
+ enum CtcpType
+ {
Query,
Reply
};
- explicit CtcpEvent(EventManager::EventType type, Network *network, const QString &prefix, QString target,
- CtcpType ctcpType, QString ctcpCmd, QString param,
- const QDateTime ×tamp = QDateTime(), const QUuid &uuid = QUuid())
- : IrcEvent(type, network, prefix),
- _ctcpType(ctcpType),
- _ctcpCmd(std::move(ctcpCmd)),
- _target(std::move(target)),
- _param(std::move(param)),
- _uuid(uuid)
+ explicit CtcpEvent(EventManager::EventType type,
+ Network* network,
+ const QString& prefix,
+ QString target,
+ CtcpType ctcpType,
+ QString ctcpCmd,
+ QString param,
+ const QDateTime& timestamp = QDateTime(),
+ const QUuid& uuid = QUuid())
+ : IrcEvent(type, network, prefix)
+ , _ctcpType(ctcpType)
+ , _ctcpCmd(std::move(ctcpCmd))
+ , _target(std::move(target))
+ , _param(std::move(param))
+ , _uuid(uuid)
{
setTimestamp(timestamp);
}
-
inline CtcpType ctcpType() const { return _ctcpType; }
inline void setCtcpType(CtcpType type) { _ctcpType = type; }
inline QString ctcpCmd() const { return _ctcpCmd; }
- inline void setCtcpCmd(const QString &ctcpCmd) { _ctcpCmd = ctcpCmd; }
+ inline void setCtcpCmd(const QString& ctcpCmd) { _ctcpCmd = ctcpCmd; }
inline QString target() const { return _target; }
- inline void setTarget(const QString &target) { _target = target; }
+ inline void setTarget(const QString& target) { _target = target; }
inline QString param() const { return _param; }
- inline void setParam(const QString ¶m) { _param = param; }
+ inline void setParam(const QString& param) { _param = param; }
inline QString reply() const { return _reply; }
- inline void setReply(const QString &reply) { _reply = reply; }
+ inline void setReply(const QString& reply) { _reply = reply; }
inline QUuid uuid() const { return _uuid; }
- inline void setUuid(const QUuid &uuid) { _uuid = uuid; }
+ inline void setUuid(const QUuid& uuid) { _uuid = uuid; }
- static Event *create(EventManager::EventType type, QVariantMap &map, Network *network);
+ static Event* create(EventManager::EventType type, QVariantMap& map, Network* network);
protected:
- explicit CtcpEvent(EventManager::EventType type, QVariantMap &map, Network *network);
- void toVariantMap(QVariantMap &map) const override;
+ explicit CtcpEvent(EventManager::EventType type, QVariantMap& map, Network* network);
+ void toVariantMap(QVariantMap& map) const override;
inline QString className() const override { return "CtcpEvent"; }
- inline void debugInfo(QDebug &dbg) const override
+ inline void debugInfo(QDebug& dbg) const override
{
NetworkEvent::debugInfo(dbg);
- dbg << ", prefix = " << qPrintable(prefix())
- << ", target = " << qPrintable(target())
- << ", ctcptype = " << (ctcpType() == Query ? "query" : "reply")
- << ", cmd = " << qPrintable(ctcpCmd())
- << ", param = " << qPrintable(param())
- << ", reply = " << qPrintable(reply());
+ dbg << ", prefix = " << qPrintable(prefix()) << ", target = " << qPrintable(target())
+ << ", ctcptype = " << (ctcpType() == Query ? "query" : "reply") << ", cmd = " << qPrintable(ctcpCmd())
+ << ", param = " << qPrintable(param()) << ", reply = " << qPrintable(reply());
}
-
private:
CtcpType _ctcpType;
QString _ctcpCmd;
#include "types.h"
-DccConfig::DccConfig(QObject *parent)
+DccConfig::DccConfig(QObject* parent)
: SyncableObject(parent)
{
static auto regTypes = []() -> bool {
setAllowClientUpdates(true);
}
-
-DccConfig &DccConfig::operator=(const DccConfig &other)
+DccConfig& DccConfig::operator=(const DccConfig& other)
{
if (this == &other)
return *this;
return *this;
}
-
-bool DccConfig::operator==(const DccConfig &other)
+bool DccConfig::operator==(const DccConfig& other)
{
// NOTE: We don't compare the SyncableObject attributes (isInitialized, clientUpdatesAllowed())
static auto propCount = staticMetaObject.propertyCount();
return false;
}
else if (property(propName) != other.property(propName))
- return false;
+ return false;
}
return true;
}
-
bool DccConfig::isDccEnabled() const
{
return _dccEnabled;
}
-
void DccConfig::setDccEnabled(bool enabled)
{
_dccEnabled = enabled;
}
-
QHostAddress DccConfig::outgoingIp() const
{
return _outgoingIp;
}
-
-void DccConfig::setOutgoingIp(const QHostAddress &outgoingIp)
+void DccConfig::setOutgoingIp(const QHostAddress& outgoingIp)
{
_outgoingIp = outgoingIp;
}
-
DccConfig::IpDetectionMode DccConfig::ipDetectionMode() const
{
return _ipDetectionMode;
}
-
void DccConfig::setIpDetectionMode(DccConfig::IpDetectionMode detectionMode)
{
_ipDetectionMode = detectionMode;
}
-
DccConfig::PortSelectionMode DccConfig::portSelectionMode() const
{
return _portSelectionMode;
}
-
void DccConfig::setPortSelectionMode(DccConfig::PortSelectionMode portSelectionMode)
{
_portSelectionMode = portSelectionMode;
}
-
quint16 DccConfig::minPort() const
{
return _minPort;
}
-
void DccConfig::setMinPort(quint16 port)
{
_minPort = port;
}
-
quint16 DccConfig::maxPort() const
{
return _maxPort;
}
-
void DccConfig::setMaxPort(quint16 port)
{
_maxPort = port;
}
-
int DccConfig::chunkSize() const
{
return _chunkSize;
}
-
void DccConfig::setChunkSize(int chunkSize)
{
_chunkSize = chunkSize;
}
-
int DccConfig::sendTimeout() const
{
return _sendTimeout;
}
-
void DccConfig::setSendTimeout(int timeout)
{
_sendTimeout = timeout;
}
-
bool DccConfig::usePassiveDcc() const
{
return _usePassiveDcc;
}
-
void DccConfig::setUsePassiveDcc(bool use)
{
_usePassiveDcc = use;
}
-
bool DccConfig::useFastSend() const
{
return _useFastSend;
}
-
void DccConfig::setUseFastSend(bool use)
{
_useFastSend = use;
/**
* Mode for detecting the outgoing IP
*/
- enum class IpDetectionMode : quint8 {
+ enum class IpDetectionMode : quint8
+ {
Automatic, ///< Automatic detection (network socket or USERHOST)
Manual, ///< Manually specified IP
};
/**
* Mode for selecting the port range for DCC
*/
- enum class PortSelectionMode : quint8 {
- Automatic, ///< Automatic port selection
- Manual, ///< Manually specified port range
+ enum class PortSelectionMode : quint8
+ {
+ Automatic, ///< Automatic port selection
+ Manual, ///< Manually specified port range
};
Q_ENUMS(PortSelectionMode)
*
* @param[in] parent QObject parent
*/
- DccConfig(QObject *parent = nullptr);
+ DccConfig(QObject* parent = nullptr);
/**
* Assignment operator.
* @param[in] other Right-hand side instance
* @returns The updated instance
*/
- DccConfig &operator=(const DccConfig &other);
+ DccConfig& operator=(const DccConfig& other);
/**
* Equality operator.
* @param[in] other Right-hand side instance
* @returns Whether the two instances have equal properties
*/
- bool operator==(const DccConfig &other);
+ bool operator==(const DccConfig& other);
/// @name Getters
/// @{
/// @name Setters
/// @{
void setDccEnabled(bool enabled);
- void setOutgoingIp(const QHostAddress &outgoingIp);
+ void setOutgoingIp(const QHostAddress& outgoingIp);
void setIpDetectionMode(DccConfig::IpDetectionMode ipDetectionMode);
void setPortSelectionMode(DccConfig::PortSelectionMode portSelectionMode);
void setMinPort(quint16 port);
private:
// The given values are used as default for both initialization and settings
- bool _dccEnabled {false};
- QHostAddress _outgoingIp {QHostAddress::LocalHost};
- IpDetectionMode _ipDetectionMode {IpDetectionMode::Automatic};
- PortSelectionMode _portSelectionMode {PortSelectionMode::Automatic};
- quint16 _minPort {1024};
- quint16 _maxPort {32767};
- int _chunkSize {16};
- int _sendTimeout {180};
- bool _usePassiveDcc {false};
- bool _useFastSend {false};
+ bool _dccEnabled{false};
+ QHostAddress _outgoingIp{QHostAddress::LocalHost};
+ IpDetectionMode _ipDetectionMode{IpDetectionMode::Automatic};
+ PortSelectionMode _portSelectionMode{PortSelectionMode::Automatic};
+ quint16 _minPort{1024};
+ quint16 _maxPort{32767};
+ int _chunkSize{16};
+ int _sendTimeout{180};
+ bool _usePassiveDcc{false};
+ bool _useFastSend{false};
};
* QObject should always be deleted by calling deleteLater() on them, so the event loop can
* perform necessary cleanups.
*/
-struct DeferredDeleter {
+struct DeferredDeleter
+{
/// Deletes the given QObject
- void operator()(QObject *object) const {
+ void operator()(QObject* object) const
+ {
if (object)
object->deleteLater();
}
};
-} // detail
+} // namespace detail
/**
* Unique pointer for QObjects with deferred deletion
template<typename T>
using DeferredUniquePtr = std::unique_ptr<T, detail::DeferredDeleter>;
-
/**
* Helper function for creating a DeferredUniquePtr
*
* @param[in] args Constructor arguments
* @returns A DeferredUniquePtr holding a new instance of T
*/
-template<typename T, typename ...Args>
+template<typename T, typename... Args>
DeferredUniquePtr<T> makeDeferredUnique(Args... args)
{
static_assert(std::is_base_of<QObject, T>::value, "Type must inherit from QObject");
return DeferredUniquePtr<T>(new T(std::forward<Args>(args)...));
}
-
/**
* Shared pointer for QObjects with deferred deletion
*
template<typename T>
using DeferredSharedPtr = std::shared_ptr<T>;
-
/**
* Helper function for creating a DeferredSharedPtr
*
* @param[in] args Constructor arguments
* @returns A DeferredSharedPtr holding a new instance of T
*/
-template<typename T, typename ...Args>
+template<typename T, typename... Args>
DeferredSharedPtr<T> makeDeferredShared(Args... args)
{
static_assert(std::is_base_of<QObject, T>::value, "Type must inherit from QObject");
#include "ctcpevent.h"
#include "ircevent.h"
-#include "networkevent.h"
#include "messageevent.h"
+#include "networkevent.h"
#include "peer.h"
#include "signalproxy.h"
Event::Event(EventManager::EventType type)
: _type(type)
-{
-}
-
+{}
-Event::Event(EventManager::EventType type, QVariantMap &map)
+Event::Event(EventManager::EventType type, QVariantMap& map)
: _type(type)
{
if (!map.contains("flags") || !map.contains("timestamp")) {
Q_ASSERT(SignalProxy::current());
Q_ASSERT(SignalProxy::current()->sourcePeer());
- setFlags(static_cast<EventManager::EventFlags>(map.take("flags").toInt())); // TODO sanity check?
+ setFlags(static_cast<EventManager::EventFlags>(map.take("flags").toInt())); // TODO sanity check?
if (SignalProxy::current()->sourcePeer()->hasFeature(Quassel::Feature::LongTime)) {
// timestamp is a qint64, signed rather than unsigned
setTimestamp(QDateTime::fromMSecsSinceEpoch(map.take("timestamp").toLongLong()));
- } else {
+ }
+ else {
setTimestamp(QDateTime::fromTime_t(map.take("timestamp").toUInt()));
}
}
-
-void Event::toVariantMap(QVariantMap &map) const
+void Event::toVariantMap(QVariantMap& map) const
{
Q_ASSERT(SignalProxy::current());
Q_ASSERT(SignalProxy::current()->targetPeer());
if (SignalProxy::current()->targetPeer()->hasFeature(Quassel::Feature::LongTime)) {
// toMSecs returns a qint64, signed rather than unsigned
map["timestamp"] = timestamp().toMSecsSinceEpoch();
- } else {
+ }
+ else {
map["timestamp"] = timestamp().toTime_t();
}
}
-
QVariantMap Event::toVariantMap() const
{
QVariantMap map;
return map;
}
-
-Event *Event::fromVariantMap(QVariantMap &map, Network *network)
+Event* Event::fromVariantMap(QVariantMap& map, Network* network)
{
int inttype = map.take("type").toInt();
// sanity check if we have a valid enum value
auto group = static_cast<EventManager::EventType>(type & EventManager::EventGroupMask);
- Event *e = nullptr;
+ Event* e = nullptr;
// we use static create() functions to keep group-specific special cases in the files they belong
// e.g. IrcEventRawMessage
return e;
}
-
-QDebug operator<<(QDebug dbg, Event *e)
+QDebug operator<<(QDebug dbg, Event* e)
{
dbg.nospace() << qPrintable(e->className()) << "("
- << "type = 0x" << qPrintable(QString::number(e->type(), 16));
+ << "type = 0x" << qPrintable(QString::number(e->type(), 16));
e->debugInfo(dbg);
//<< ", data = " << e->data(); // we don't use data anywhere yet
- dbg.nospace() << ", flags = 0x" << qPrintable(QString::number(e->flags(), 16))
- << ")";
+ dbg.nospace() << ", flags = 0x" << qPrintable(QString::number(e->flags(), 16)) << ")";
return dbg.space();
}
inline void stop() { setFlag(EventManager::Stopped); }
inline bool isStopped() { return _flags.testFlag(EventManager::Stopped); }
- inline void setTimestamp(const QDateTime &time) { _timestamp = time; }
+ inline void setTimestamp(const QDateTime& time) { _timestamp = time; }
inline QDateTime timestamp() const { return _timestamp; }
- //inline void setData(const QVariant &data) { _data = data; }
- //inline QVariant data() const { return _data; }
+ // inline void setData(const QVariant &data) { _data = data; }
+ // inline QVariant data() const { return _data; }
// call EventManager::createEvent(map) instead!
- static Event *fromVariantMap(QVariantMap &map, Network *network);
+ static Event* fromVariantMap(QVariantMap& map, Network* network);
QVariantMap toVariantMap() const;
protected:
virtual inline QString className() const { return "Event"; }
- virtual inline void debugInfo(QDebug &dbg) const { Q_UNUSED(dbg); }
+ virtual inline void debugInfo(QDebug& dbg) const { Q_UNUSED(dbg); }
- explicit Event(EventManager::EventType type, QVariantMap &map);
+ explicit Event(EventManager::EventType type, QVariantMap& map);
// must only use primitive types: string, int, double, list, hash
// we want to convert this to JSON in the future!
- virtual void toVariantMap(QVariantMap &map) const;
+ virtual void toVariantMap(QVariantMap& map) const;
inline void setValid(bool valid) { _valid = valid; }
QDateTime _timestamp;
bool _valid{true};
- friend COMMON_EXPORT QDebug operator<<(QDebug dbg, Event *e);
+ friend COMMON_EXPORT QDebug operator<<(QDebug dbg, Event* e);
};
-COMMON_EXPORT QDebug operator<<(QDebug dbg, Event *e);
+COMMON_EXPORT QDebug operator<<(QDebug dbg, Event* e);
#include "eventmanager.h"
#include <QCoreApplication>
-#include <QEvent>
#include <QDebug>
+#include <QEvent>
#include "event.h"
#include "ircevent.h"
class QueuedQuasselEvent : public QEvent
{
public:
- QueuedQuasselEvent(Event *event)
- : QEvent(QEvent::User), event(event) {}
- Event *event;
+ QueuedQuasselEvent(Event* event)
+ : QEvent(QEvent::User)
+ , event(event)
+ {}
+ Event* event;
};
-
// ============================================================
// EventManager
// ============================================================
-EventManager::EventManager(QObject *parent)
+EventManager::EventManager(QObject* parent)
: QObject(parent)
-{
-}
-
+{}
QMetaEnum EventManager::eventEnum()
{
return _enum;
}
-
-EventManager::EventType EventManager::eventTypeByName(const QString &name)
+EventManager::EventType EventManager::eventTypeByName(const QString& name)
{
int val = eventEnum().keyToValue(name.toLatin1());
return (val == -1) ? Invalid : static_cast<EventType>(val);
}
-
-EventManager::EventType EventManager::eventGroupByName(const QString &name)
+EventManager::EventType EventManager::eventGroupByName(const QString& name)
{
EventType type = eventTypeByName(name);
return type == Invalid ? Invalid : static_cast<EventType>(type & EventGroupMask);
}
-
QString EventManager::enumName(EventType type)
{
return eventEnum().valueToKey(type);
}
-
QString EventManager::enumName(int type)
{
return eventEnum().valueToKey(type);
}
-
-Event *EventManager::createEvent(const QVariantMap &map)
+Event* EventManager::createEvent(const QVariantMap& map)
{
QVariantMap m = map;
- Network *net = networkById(m.take("network").toInt());
+ Network* net = networkById(m.take("network").toInt());
return Event::fromVariantMap(m, net);
}
-
/* NOTE:
Registering and calling handlers works fine even if they specify a subclass of Event as their parameter.
However, this most probably is a result from a reinterpret_cast somewhere deep inside Qt, so there is *no*
with the actual class. Possibly (optionally) using rtti...
*/
-int EventManager::findEventType(const QString &methodSignature_, const QString &methodPrefix) const
+int EventManager::findEventType(const QString& methodSignature_, const QString& methodPrefix) const
{
if (!methodSignature_.startsWith(methodPrefix))
return -1;
QString methodSignature = methodSignature_;
- methodSignature = methodSignature.section('(', 0, 0); // chop the attribute list
- methodSignature = methodSignature.mid(methodPrefix.length()); // strip prefix
+ methodSignature = methodSignature.section('(', 0, 0); // chop the attribute list
+ methodSignature = methodSignature.mid(methodPrefix.length()); // strip prefix
int eventType = -1;
// special handling for numeric IrcEvents: IrcEvent042 gets mapped to IrcEventNumeric + 42
- if (methodSignature.length() == 8+3 && methodSignature.startsWith("IrcEvent")) {
+ if (methodSignature.length() == 8 + 3 && methodSignature.startsWith("IrcEvent")) {
int num = methodSignature.right(3).toUInt();
if (num > 0) {
QString numericSig = methodSignature.left(methodSignature.length() - 3) + "Numeric";
return eventType;
}
-
-void EventManager::registerObject(QObject *object, Priority priority, const QString &methodPrefix, const QString &filterPrefix)
+void EventManager::registerObject(QObject* object, Priority priority, const QString& methodPrefix, const QString& filterPrefix)
{
for (int i = object->metaObject()->methodOffset(); i < object->metaObject()->methodCount(); i++) {
QString methodSignature = object->metaObject()->method(i).methodSignature();
if (eventType > 0) {
Handler handler(object, i, priority);
registeredHandlers()[eventType].append(handler);
- //qDebug() << "Registered event handler for" << methodSignature << "in" << object;
+ // qDebug() << "Registered event handler for" << methodSignature << "in" << object;
}
eventType = findEventType(methodSignature, filterPrefix);
if (eventType > 0) {
Handler handler(object, i, priority);
registeredFilters()[eventType].append(handler);
- //qDebug() << "Registered event filterer for" << methodSignature << "in" << object;
+ // qDebug() << "Registered event filterer for" << methodSignature << "in" << object;
}
}
}
-
-void EventManager::registerEventFilter(EventType event, QObject *object, const char *slot)
+void EventManager::registerEventFilter(EventType event, QObject* object, const char* slot)
{
registerEventHandler(QList<EventType>() << event, object, slot, NormalPriority, true);
}
-
-void EventManager::registerEventFilter(QList<EventType> events, QObject *object, const char *slot)
+void EventManager::registerEventFilter(QList<EventType> events, QObject* object, const char* slot)
{
registerEventHandler(events, object, slot, NormalPriority, true);
}
-
-void EventManager::registerEventHandler(EventType event, QObject *object, const char *slot, Priority priority, bool isFilter)
+void EventManager::registerEventHandler(EventType event, QObject* object, const char* slot, Priority priority, bool isFilter)
{
registerEventHandler(QList<EventType>() << event, object, slot, priority, isFilter);
}
-
-void EventManager::registerEventHandler(QList<EventType> events, QObject *object, const char *slot, Priority priority, bool isFilter)
+void EventManager::registerEventHandler(QList<EventType> events, QObject* object, const char* slot, Priority priority, bool isFilter)
{
int methodIndex = object->metaObject()->indexOfMethod(slot);
if (methodIndex < 0) {
return;
}
Handler handler(object, methodIndex, priority);
- foreach(EventType event, events) {
+ foreach (EventType event, events) {
if (isFilter) {
registeredFilters()[event].append(handler);
qDebug() << "Registered event filter for" << event << "in" << object;
}
}
-
-void EventManager::postEvent(Event *event)
+void EventManager::postEvent(Event* event)
{
if (sender() && sender()->thread() != this->thread()) {
- auto *queuedEvent = new QueuedQuasselEvent(event);
+ auto* queuedEvent = new QueuedQuasselEvent(event);
QCoreApplication::postEvent(this, queuedEvent);
}
else {
}
}
-
-void EventManager::customEvent(QEvent *event)
+void EventManager::customEvent(QEvent* event)
{
if (event->type() == QEvent::User) {
- auto *queuedEvent = static_cast<QueuedQuasselEvent *>(event);
+ auto* queuedEvent = static_cast<QueuedQuasselEvent*>(event);
processEvent(queuedEvent->event);
event->accept();
}
}
-
-void EventManager::processEvent(Event *event)
+void EventManager::processEvent(Event* event)
{
Q_ASSERT(_eventQueue.isEmpty());
dispatchEvent(event);
}
}
-
-void EventManager::dispatchEvent(Event *event)
+void EventManager::dispatchEvent(Event* event)
{
- //qDebug() << "Dispatching" << event;
+ // qDebug() << "Dispatching" << event;
// we try handlers from specialized to generic by masking the enum
// build a list sorted by priorities that contains all eligible handlers
QList<Handler> handlers;
- QHash<QObject *, Handler> filters;
- QSet<QObject *> ignored;
+ QHash<QObject*, Handler> filters;
+ QSet<QObject*> ignored;
uint type = event->type();
bool checkDupes = false;
// special handling for numeric IrcEvents
if ((type & ~IrcEventNumericMask) == IrcEventNumeric) {
- auto *numEvent = static_cast< ::IrcEventNumeric *>(event);
+ auto* numEvent = static_cast<::IrcEventNumeric*>(event);
if (!numEvent)
qWarning() << "Invalid event type for IrcEventNumeric!";
else {
// now dispatch the event
QList<Handler>::const_iterator it;
for (it = handlers.begin(); it != handlers.end() && !event->isStopped(); ++it) {
- QObject *obj = it->object;
+ QObject* obj = it->object;
- if (ignored.contains(obj)) // object has filtered the event
+ if (ignored.contains(obj)) // object has filtered the event
continue;
- if (filters.contains(obj)) { // we have a filter, so let's check if we want to deliver the event
+ if (filters.contains(obj)) { // we have a filter, so let's check if we want to deliver the event
Handler filter = filters.value(obj);
bool result = false;
- void *param[] = { Q_RETURN_ARG(bool, result).data(), Q_ARG(Event *, event).data() };
+ void* param[] = {Q_RETURN_ARG(bool, result).data(), Q_ARG(Event*, event).data()};
obj->qt_metacall(QMetaObject::InvokeMetaMethod, filter.methodIndex, param);
if (!result) {
ignored.insert(obj);
- continue; // mmmh, event filter told us to not accept
+ continue; // mmmh, event filter told us to not accept
}
}
// finally, deliverance!
- void *param[] = { nullptr, Q_ARG(Event *, event).data() };
+ void* param[] = {nullptr, Q_ARG(Event*, event).data()};
obj->qt_metacall(QMetaObject::InvokeMetaMethod, it->methodIndex, param);
}
delete event;
}
-
-void EventManager::insertHandlers(const QList<Handler> &newHandlers, QList<Handler> &existing, bool checkDupes)
+void EventManager::insertHandlers(const QList<Handler>& newHandlers, QList<Handler>& existing, bool checkDupes)
{
- foreach(const Handler &handler, newHandlers) {
+ foreach (const Handler& handler, newHandlers) {
if (existing.isEmpty())
existing.append(handler);
else {
}
}
-
// priority is ignored, and only the first (should be most specialized) filter is being used
// fun things could happen if you used the registerEventFilter() methods in the wrong order though
-void EventManager::insertFilters(const QList<Handler> &newFilters, QHash<QObject *, Handler> &existing)
+void EventManager::insertFilters(const QList<Handler>& newFilters, QHash<QObject*, Handler>& existing)
{
- foreach(const Handler &filter, newFilters) {
+ foreach (const Handler& filter, newFilters) {
if (!existing.contains(filter.object))
existing[filter.object] = filter;
}
}
-
QMetaEnum EventManager::_enum;
Q_FLAGS(EventFlag EventFlags)
Q_ENUMS(EventType)
-public :
-
- enum RegistrationMode {
+public:
+ enum RegistrationMode
+ {
Prepend,
Append
};
- enum Priority {
+ enum Priority
+ {
VeryLowPriority,
LowPriority,
NormalPriority,
HighestPriority
};
- enum EventFlag {
- Self = 0x01, ///< Self-generated (user input) event
- Fake = 0x08, ///< Ignore this in CoreSessionEventProcessor
- Netsplit = 0x10, ///< Netsplit join/part, ignore on display
- Backlog = 0x20,
- Silent = 0x40, ///< Don't generate a MessageEvent
- Stopped = 0x80
+ enum EventFlag
+ {
+ Self = 0x01, ///< Self-generated (user input) event
+ Fake = 0x08, ///< Ignore this in CoreSessionEventProcessor
+ Netsplit = 0x10, ///< Netsplit join/part, ignore on display
+ Backlog = 0x20,
+ Silent = 0x40, ///< Don't generate a MessageEvent
+ Stopped = 0x80
};
Q_DECLARE_FLAGS(EventFlags, EventFlag)
*/
/* These values make sense! Don't change without knowing what you do! */
- enum EventType {
- Invalid = 0xffffffff,
- GenericEvent = 0x00000000,
+ enum EventType
+ {
+ Invalid = 0xffffffff,
+ GenericEvent = 0x00000000,
// for event group handlers (handleIrcEvent() will handle all IrcEvent* enums)
// event groups are specified by bits 20-24
- EventGroupMask = 0x00ff0000,
+ EventGroupMask = 0x00ff0000,
- NetworkEvent = 0x00010000,
+ NetworkEvent = 0x00010000,
NetworkConnecting,
NetworkInitializing,
NetworkInitialized,
NetworkSplitQuit,
NetworkIncoming,
- IrcServerEvent = 0x00020000,
+ IrcServerEvent = 0x00020000,
IrcServerIncoming,
IrcServerParseError,
- IrcEvent = 0x00030000,
+ IrcEvent = 0x00030000,
IrcEventAuthenticate,
IrcEventAccount,
IrcEventAway,
IrcEventPrivmsg,
IrcEventQuit,
IrcEventTopic,
- IrcEventError, /// ERROR message from server
+ IrcEventError, /// ERROR message from server
IrcEventWallops,
- IrcEventRawPrivmsg, ///< Undecoded privmsg (still needs CTCP parsing)
- IrcEventRawNotice, ///< Undecoded notice (still needs CTCP parsing)
- IrcEventUnknown, ///< Unknown non-numeric cmd
+ IrcEventRawPrivmsg, ///< Undecoded privmsg (still needs CTCP parsing)
+ IrcEventRawNotice, ///< Undecoded notice (still needs CTCP parsing)
+ IrcEventUnknown, ///< Unknown non-numeric cmd
- IrcEventNumeric = 0x00031000, /* needs 1000 (0x03e8) consecutive free values! */
- IrcEventNumericMask = 0x00000fff, /* for checking if an event is numeric */
+ IrcEventNumeric = 0x00031000, /* needs 1000 (0x03e8) consecutive free values! */
+ IrcEventNumericMask = 0x00000fff, /* for checking if an event is numeric */
- MessageEvent = 0x00040000, ///< Stringified event suitable for converting to Message
+ MessageEvent = 0x00040000, ///< Stringified event suitable for converting to Message
- CtcpEvent = 0x00050000,
+ CtcpEvent = 0x00050000,
CtcpEventFlush,
- KeyEvent = 0x00060000
+ KeyEvent = 0x00060000
};
- EventManager(QObject *parent = nullptr);
+ EventManager(QObject* parent = nullptr);
- static EventType eventTypeByName(const QString &name);
- static EventType eventGroupByName(const QString &name);
+ static EventType eventTypeByName(const QString& name);
+ static EventType eventGroupByName(const QString& name);
static QString enumName(EventType type);
- static QString enumName(int type); // for sanity tests
+ static QString enumName(int type); // for sanity tests
- Event *createEvent(const QVariantMap &map);
+ Event* createEvent(const QVariantMap& map);
public slots:
- void registerObject(QObject *object, Priority priority = NormalPriority,
- const QString &methodPrefix = "process",
- const QString &filterPrefix = "filter");
- void registerEventHandler(EventType event, QObject *object, const char *slot,
- Priority priority = NormalPriority, bool isFilter = false);
- void registerEventHandler(QList<EventType> events, QObject *object, const char *slot,
- Priority priority = NormalPriority, bool isFilter = false);
+ void registerObject(QObject* object,
+ Priority priority = NormalPriority,
+ const QString& methodPrefix = "process",
+ const QString& filterPrefix = "filter");
+ void registerEventHandler(EventType event, QObject* object, const char* slot, Priority priority = NormalPriority, bool isFilter = false);
+ void registerEventHandler(
+ QList<EventType> events, QObject* object, const char* slot, Priority priority = NormalPriority, bool isFilter = false);
- void registerEventFilter(EventType event, QObject *object, const char *slot);
- void registerEventFilter(QList<EventType> events, QObject *object, const char *slot);
+ void registerEventFilter(EventType event, QObject* object, const char* slot);
+ void registerEventFilter(QList<EventType> events, QObject* object, const char* slot);
//! Send an event to the registered handlers
/**
The EventManager takes ownership of the event and will delete it once it's processed.
@param event The event to be dispatched
*/
- void postEvent(Event *event);
+ void postEvent(Event* event);
protected:
- virtual Network *networkById(NetworkId id) const = 0;
- void customEvent(QEvent *event) override;
+ virtual Network* networkById(NetworkId id) const = 0;
+ void customEvent(QEvent* event) override;
private:
- struct Handler {
- QObject *object;
+ struct Handler
+ {
+ QObject* object;
int methodIndex;
Priority priority;
- explicit Handler(QObject *obj = nullptr, int method = 0, Priority prio = NormalPriority)
+ explicit Handler(QObject* obj = nullptr, int method = 0, Priority prio = NormalPriority)
{
object = obj;
methodIndex = method;
using HandlerHash = QHash<uint, QList<Handler>>;
- inline const HandlerHash ®isteredHandlers() const { return _registeredHandlers; }
- inline HandlerHash ®isteredHandlers() { return _registeredHandlers; }
+ inline const HandlerHash& registeredHandlers() const { return _registeredHandlers; }
+ inline HandlerHash& registeredHandlers() { return _registeredHandlers; }
- inline const HandlerHash ®isteredFilters() const { return _registeredFilters; }
- inline HandlerHash ®isteredFilters() { return _registeredFilters; }
+ inline const HandlerHash& registeredFilters() const { return _registeredFilters; }
+ inline HandlerHash& registeredFilters() { return _registeredFilters; }
//! Add handlers to an existing sorted (by priority) handler list
- void insertHandlers(const QList<Handler> &newHandlers, QList<Handler> &existing, bool checkDupes = false);
+ void insertHandlers(const QList<Handler>& newHandlers, QList<Handler>& existing, bool checkDupes = false);
//! Add filters to an existing filter hash
- void insertFilters(const QList<Handler> &newFilters, QHash<QObject *, Handler> &existing);
+ void insertFilters(const QList<Handler>& newFilters, QHash<QObject*, Handler>& existing);
- int findEventType(const QString &methodSignature, const QString &methodPrefix) const;
+ int findEventType(const QString& methodSignature, const QString& methodPrefix) const;
- void processEvent(Event *event);
- void dispatchEvent(Event *event);
+ void processEvent(Event* event);
+ void dispatchEvent(Event* event);
//! @return the EventType enum
static QMetaEnum eventEnum();
HandlerHash _registeredHandlers;
HandlerHash _registeredFilters;
- QList<Event *> _eventQueue;
+ QList<Event*> _eventQueue;
static QMetaEnum _enum;
};
-
Q_DECLARE_OPERATORS_FOR_FLAGS(EventManager::EventFlags)
#include "logmessage.h"
-ExpressionMatch::ExpressionMatch(const QString &expression, MatchMode mode, bool caseSensitive)
+ExpressionMatch::ExpressionMatch(const QString& expression, MatchMode mode, bool caseSensitive)
{
// Store the original parameters for later reference
_sourceExpression = expression;
cacheRegEx();
}
-
-bool ExpressionMatch::match(const QString &string, bool matchEmpty) const
+bool ExpressionMatch::match(const QString& string, bool matchEmpty) const
{
// Handle empty expression strings
if (_sourceExpressionEmpty) {
}
}
-
-QString ExpressionMatch::trimMultiWildcardWhitespace(const QString &originalRule)
+QString ExpressionMatch::trimMultiWildcardWhitespace(const QString& originalRule)
{
// This gets handled in two steps:
//
break;
default:
// This shouldn't ever happen (even with invalid wildcard rules), log a warning
- qWarning() << Q_FUNC_INFO << "Wildcard rule"
- << rule << "resulted in rule component"
- << curString << "with unexpected count of consecutive '\\' ("
- << consecutiveSlashes << "), ignoring" << curChar << "character!";
+ qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString
+ << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" << curChar
+ << "character!";
break;
}
consecutiveSlashes = 0;
}
else if (consecutiveSlashes > 3) {
// This shouldn't ever happen (even with invalid wildcard rules), log a warning
- qWarning() << Q_FUNC_INFO << "Wildcard rule"
- << rule << "resulted in rule component"
- << curString << "with unexpected count of consecutive '\\' ("
- << consecutiveSlashes << "), ignoring" << curChar << "character!";
+ qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString
+ << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" << curChar
+ << "character!";
break;
}
break;
break;
default:
// This shouldn't ever happen (even with invalid wildcard rules), log a warning
- qWarning() << Q_FUNC_INFO << "Wildcard rule"
- << rule << "resulted in rule component"
- << curString << "with unexpected count of consecutive '\\' ("
- << consecutiveSlashes << "), applying newline split anyways!";
+ qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString
+ << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), applying newline split anyways!";
break;
}
break;
default:
// This shouldn't ever happen (even with invalid wildcard rules), log a warning
- qWarning() << Q_FUNC_INFO << "Wildcard rule"
- << rule << "resulted in rule component"
- << curString << "with unexpected count of consecutive '\\' ("
- << consecutiveSlashes << "), ignoring " << curChar << "char escape!";
+ qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString
+ << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring " << curChar
+ << "char escape!";
break;
}
consecutiveSlashes = 0;
return result.trimmed();
}
-
void ExpressionMatch::cacheRegEx()
{
_matchRegExActive = false;
// Match entire phrase, noninverted
// Don't trim whitespace for phrase matching as someone might want to match on " word ", a
// more-specific request than "word".
- _matchRegEx = regExFactory("(?:^|\\W)" + regExEscape(_sourceExpression) + "(?:\\W|$)",
- _sourceCaseSensitive);
+ _matchRegEx = regExFactory("(?:^|\\W)" + regExEscape(_sourceExpression) + "(?:\\W|$)", _sourceCaseSensitive);
_matchRegExActive = true;
break;
case MatchMode::MatchMultiPhrase:
if (_sourceExpression.startsWith("!")) {
// Inverted rule: take the remainder of the string
// "^" + invertComponents.at(0) + "$"
- _matchInvertRegEx = regExFactory("^" + wildcardToRegEx(_sourceExpression.mid(1)) + "$",
- _sourceCaseSensitive);
+ _matchInvertRegEx = regExFactory("^" + wildcardToRegEx(_sourceExpression.mid(1)) + "$", _sourceCaseSensitive);
_matchInvertRegExActive = true;
}
else {
// Normal rule: take the whole string
// Account for any escaped "!" (i.e. "\!") by skipping past the "\", but don't skip past
// escaped "\" (i.e. "\\!")
- _matchRegEx =
- regExFactory("^" + wildcardToRegEx(_sourceExpression.startsWith("\\!")
- ? _sourceExpression.mid(1)
- : _sourceExpression) + "$",
- _sourceCaseSensitive);
+ _matchRegEx = regExFactory("^" + wildcardToRegEx(_sourceExpression.startsWith("\\!") ? _sourceExpression.mid(1) : _sourceExpression)
+ + "$",
+ _sourceCaseSensitive);
_matchRegExActive = true;
}
break;
// Normal rule: take the whole string
// Account for any escaped "!" (i.e. "\!") by skipping past the "\", but don't skip past
// escaped "\" (i.e. "\\!")
- _matchRegEx =
- regExFactory(_sourceExpression.startsWith("\\!") ? _sourceExpression.mid(1)
- : _sourceExpression,
- _sourceCaseSensitive);
+ _matchRegEx = regExFactory(_sourceExpression.startsWith("\\!") ? _sourceExpression.mid(1) : _sourceExpression,
+ _sourceCaseSensitive);
_matchRegExActive = true;
}
break;
// level as ideally someone's not just going to leave a broken match rule around. For
// MatchRegEx, they probably need to fix their regex rule. For the other modes, there's
// probably a bug in the parsing routines (which should also be fixed).
- quInfo() << "Could not parse expression match rule"
- << _sourceExpression << "(match mode:" << (int)_sourceMode
+ quInfo() << "Could not parse expression match rule" << _sourceExpression << "(match mode:" << (int)_sourceMode
<< "), this rule will be ignored";
}
}
-
-QRegularExpression ExpressionMatch::regExFactory(const QString ®ExString,
- bool caseSensitive)
+QRegularExpression ExpressionMatch::regExFactory(const QString& regExString, bool caseSensitive)
{
// Construct the regular expression object, setting case sensitivity as appropriate
- QRegularExpression newRegEx = QRegularExpression(regExString, caseSensitive ?
- QRegularExpression::PatternOption::NoPatternOption
- : QRegularExpression::PatternOption::CaseInsensitiveOption);
+ QRegularExpression newRegEx = QRegularExpression(regExString,
+ caseSensitive ? QRegularExpression::PatternOption::NoPatternOption
+ : QRegularExpression::PatternOption::CaseInsensitiveOption);
// Check if rule is valid
if (!newRegEx.isValid()) {
// This can happen with invalid regex, so make it a bit more user-friendly. Keep this
// distinct from the main info-level message for easier debugging in case a regex component
// in Wildcard or Phrase mode breaks.
- qDebug() << "Internal regular expression component" << regExString
- << "is invalid and will be ignored";
+ qDebug() << "Internal regular expression component" << regExString << "is invalid and will be ignored";
}
// Qt offers explicit control over when QRegularExpression objects get optimized.
// By default, patterns are only optimized after some number of uses as defined
return newRegEx;
}
-
-QString ExpressionMatch::regExEscape(const QString &phrase)
+QString ExpressionMatch::regExEscape(const QString& phrase)
{
// Escape the given phrase of any special regular expression characters
return QRegularExpression::escape(phrase);
}
-
-QString ExpressionMatch::convertFromMultiPhrase(const QString &originalRule)
+QString ExpressionMatch::convertFromMultiPhrase(const QString& originalRule)
{
// Convert the multi-phrase rule into regular expression format
// Split apart the original rule into components
// Use QStringList instead of std::vector<QString> to make use of Qt's built-in .join() method
QStringList components = {};
// Split on "\n"
- for (auto &&component : originalRule.split("\n", QString::SkipEmptyParts)) {
+ for (auto&& component : originalRule.split("\n", QString::SkipEmptyParts)) {
// Don't trim whitespace to maintain consistency with single phrase matching
// As trimming is not performed, empty components will already be skipped. This means " "
// is considered a valid matching phrase.
}
}
-
-void ExpressionMatch::generateFromMultiWildcard(const QString &originalRule, bool caseSensitive)
+void ExpressionMatch::generateFromMultiWildcard(const QString& originalRule, bool caseSensitive)
{
// Convert the wildcard rule into regular expression format
// First, reset the existing match expressions
// "\\" and "\" are not downconverted to allow for other escape codes to be detected in
// ExpressionMatch::wildcardToRegex
-
// Example:
//
// > Wildcard rule
break;
default:
// This shouldn't ever happen (even with invalid wildcard rules), log a warning
- qWarning() << Q_FUNC_INFO << "Wildcard rule"
- << rule << "resulted in rule component"
- << curString << "with unexpected count of consecutive '\\' ("
- << consecutiveSlashes << "), ignoring" << curChar << "character!";
+ qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString
+ << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" << curChar
+ << "character!";
isRuleStart = false;
break;
}
break;
default:
// This shouldn't ever happen (even with invalid wildcard rules), log a warning
- qWarning() << Q_FUNC_INFO << "Wildcard rule"
- << rule << "resulted in rule component"
- << curString << "with unexpected count of consecutive '\\' ("
- << consecutiveSlashes << "), ignoring" << curChar << "character!";
+ qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString
+ << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" << curChar
+ << "character!";
break;
}
}
break;
case 1:
case 2:
- // "\!" -> Elsewhere: keep as "\!"
- // "\\!" -> Elsewhere: keep as "\\!"
+ // "\!" -> Elsewhere: keep as "\!"
+ // "\\!" -> Elsewhere: keep as "\\!"
curString.append(QString(R"(\)").repeated(consecutiveSlashes) + "!");
break;
default:
// This shouldn't ever happen (even with invalid wildcard rules), log a warning
- qWarning() << Q_FUNC_INFO << "Wildcard rule"
- << rule << "resulted in rule component"
- << curString << "with unexpected count of consecutive '\\' ("
- << consecutiveSlashes << "), ignoring" << curChar << "character!";
+ qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString
+ << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" << curChar
+ << "character!";
break;
}
}
}
else if (consecutiveSlashes > 3) {
// This shouldn't ever happen (even with invalid wildcard rules), log a warning
- qWarning() << Q_FUNC_INFO << "Wildcard rule"
- << rule << "resulted in rule component"
- << curString << "with unexpected count of consecutive '\\' ("
- << consecutiveSlashes << "), ignoring" << curChar << "character!";
+ qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString
+ << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring" << curChar
+ << "character!";
break;
}
// Don't set "isRuleStart" here as "\" is used in escape sequences
break;
default:
// This shouldn't ever happen (even with invalid wildcard rules), log a warning
- qWarning() << Q_FUNC_INFO << "Wildcard rule"
- << rule << "resulted in rule component"
- << curString << "with unexpected count of consecutive '\\' ("
- << consecutiveSlashes << "), applying newline split anyways!";
+ qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString
+ << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), applying newline split anyways!";
break;
}
break;
default:
// This shouldn't ever happen (even with invalid wildcard rules), log a warning
- qWarning() << Q_FUNC_INFO << "Wildcard rule"
- << rule << "resulted in rule component"
- << curString << "with unexpected count of consecutive '\\' ("
- << consecutiveSlashes << "), ignoring " << curChar << "char escape!";
+ qWarning() << Q_FUNC_INFO << "Wildcard rule" << rule << "resulted in rule component" << curString
+ << "with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring " << curChar
+ << "char escape!";
break;
}
// Don't mark as past rule start for whitespace (whitespace gets trimmed)
_matchInvertRegEx = regExFactory("^" + invertComponents.at(0) + "$", caseSensitive);
}
else {
- _matchInvertRegEx =
- regExFactory("^(?:" + invertComponents.join("|") + ")$", caseSensitive);
+ _matchInvertRegEx = regExFactory("^(?:" + invertComponents.join("|") + ")$", caseSensitive);
}
_matchInvertRegExActive = true;
}
}
-
-QString ExpressionMatch::wildcardToRegEx(const QString &expression)
+QString ExpressionMatch::wildcardToRegEx(const QString& expression)
{
// Convert the wildcard expression into regular expression format
break;
default:
// This shouldn't ever happen (even with invalid wildcard rules), log a warning
- qWarning() << Q_FUNC_INFO << "Wildcard rule"
- << expression << "resulted in escaped regular expression string"
- << regExEscaped << " with unexpected count of consecutive '\\' ("
- << consecutiveSlashes << "), ignoring" << curChar << "character!";
+ qWarning() << Q_FUNC_INFO << "Wildcard rule" << expression << "resulted in escaped regular expression string"
+ << regExEscaped << " with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring"
+ << curChar << "character!";
break;
}
consecutiveSlashes = 0;
break;
default:
// This shouldn't ever happen (even with invalid wildcard rules), log a warning
- qWarning() << Q_FUNC_INFO << "Wildcard rule"
- << expression << "resulted in escaped regular expression string"
- << regExEscaped << " with unexpected count of consecutive '\\' ("
- << consecutiveSlashes << "), ignoring" << curChar << "character!";
+ qWarning() << Q_FUNC_INFO << "Wildcard rule" << expression << "resulted in escaped regular expression string"
+ << regExEscaped << " with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring"
+ << curChar << "character!";
break;
}
consecutiveSlashes = 0;
break;
default:
// This shouldn't ever happen (even with invalid wildcard rules), log a warning
- qWarning() << Q_FUNC_INFO << "Wildcard rule"
- << expression << "resulted in escaped regular expression string"
- << regExEscaped << " with unexpected count of consecutive '\\' ("
- << consecutiveSlashes << "), ignoring" << curChar << "char escape!";
+ qWarning() << Q_FUNC_INFO << "Wildcard rule" << expression << "resulted in escaped regular expression string"
+ << regExEscaped << " with unexpected count of consecutive '\\' (" << consecutiveSlashes << "), ignoring"
+ << curChar << "char escape!";
break;
}
consecutiveSlashes = 0;
*/
class COMMON_EXPORT ExpressionMatch
{
-
public:
/// Expression matching mode
- enum class MatchMode {
- MatchPhrase, ///< Match phrase as specified, no special handling
- MatchMultiPhrase, ///< Match phrase as specified, split on \n only
- MatchWildcard, ///< Match wildcards, "!" at start inverts, "\" escapes
- MatchMultiWildcard, ///< Match wildcards, split ; or \n, "!" at start inverts, "\" escapes
- MatchRegEx ///< Match as regular expression, "!..." invert regex, "\" escapes
+ enum class MatchMode
+ {
+ MatchPhrase, ///< Match phrase as specified, no special handling
+ MatchMultiPhrase, ///< Match phrase as specified, split on \n only
+ MatchWildcard, ///< Match wildcards, "!" at start inverts, "\" escapes
+ MatchMultiWildcard, ///< Match wildcards, split ; or \n, "!" at start inverts, "\" escapes
+ MatchRegEx ///< Match as regular expression, "!..." invert regex, "\" escapes
};
/**
* @endparblock
* @param caseSensitive If true, match case-sensitively, otherwise ignore case when matching
*/
- ExpressionMatch(const QString &expression, MatchMode mode, bool caseSensitive);
+ ExpressionMatch(const QString& expression, MatchMode mode, bool caseSensitive);
/**
* Check if the given string matches the stored expression
* @param matchEmpty If true, always match when the expression is empty, otherwise never match
* @return True if match found, otherwise false
*/
- bool match(const QString &string, bool matchEmpty = false) const;
+ bool match(const QString& string, bool matchEmpty = false) const;
/**
* Gets if the source expression is empty
*
* @return True if given expression is valid, otherwise false
*/
- inline bool isValid() const {
+ inline bool isValid() const
+ {
// Either this must be empty, or normal or inverted rules must be valid and active
- return (_sourceExpressionEmpty
- || (_matchRegExActive && _matchRegEx.isValid())
+ return (_sourceExpressionEmpty || (_matchRegExActive && _matchRegEx.isValid())
|| (_matchInvertRegExActive && _matchInvertRegEx.isValid()));
}
*
* @param expression A phrase, wildcard expression, or regular expression
*/
- void setSourceExpression(const QString &expression) {
+ void setSourceExpression(const QString& expression)
+ {
if (_sourceExpression != expression) {
_sourceExpression = expression;
cacheRegEx();
* @see ExpressionMatch::MatchMode
* @endparblock
*/
- void setSourceMode(MatchMode mode) {
+ void setSourceMode(MatchMode mode)
+ {
if (_sourceMode != mode) {
_sourceMode = mode;
cacheRegEx();
*
* @param caseSensitive If true, match case-sensitively, otherwise ignore case when matching
*/
- void setSourceCaseSensitive(bool caseSensitive) {
+ void setSourceCaseSensitive(bool caseSensitive)
+ {
if (_sourceCaseSensitive != caseSensitive) {
_sourceCaseSensitive = caseSensitive;
cacheRegEx();
}
}
- bool operator!=(const ExpressionMatch &other) const
+ bool operator!=(const ExpressionMatch& other) const
{
- return (_sourceExpression != other._sourceExpression ||
- _sourceMode != other._sourceMode ||
- _sourceCaseSensitive != other._sourceCaseSensitive);
+ return (_sourceExpression != other._sourceExpression || _sourceMode != other._sourceMode
+ || _sourceCaseSensitive != other._sourceCaseSensitive);
}
/**
* @param originalRule MultiWildcard rule list, ";"-separated
* @return Trimmed MultiWildcard rule list
*/
- static QString trimMultiWildcardWhitespace(const QString &originalRule);
+ static QString trimMultiWildcardWhitespace(const QString& originalRule);
private:
/**
* @param caseSensitive If true, match case-sensitively, otherwise ignore case when matching
* @return Configured QRegularExpression
*/
- static QRegularExpression regExFactory(const QString ®ExString, bool caseSensitive);
+ static QRegularExpression regExFactory(const QString& regExString, bool caseSensitive);
/**
* Escapes any regular expression characters in a string so they have no special meaning
* @param phrase String containing potential regular expression special characters
* @return QString with all regular expression characters escaped
*/
- static QString regExEscape(const QString &phrase);
+ static QString regExEscape(const QString& phrase);
/**
* Converts a multiple-phrase rule into a regular expression
* @param originalRule MultiPhrase rule list, "\n"-separated
* @return A regular expression matching the given phrases
*/
- static QString convertFromMultiPhrase(const QString &originalRule);
+ static QString convertFromMultiPhrase(const QString& originalRule);
/**
* Internally converts a wildcard rule into regular expressions
* @param originalRule MultiWildcard rule list, ";"-separated
* @param caseSensitive If true, match case-sensitively, otherwise ignore case when matching
*/
- void generateFromMultiWildcard(const QString &originalRule, bool caseSensitive);
+ void generateFromMultiWildcard(const QString& originalRule, bool caseSensitive);
/**
* Converts a wildcard expression into a regular expression
* @see ExpressionMatch::convertFromWildcard()
* @return QString with all regular expression characters escaped
*/
- static QString wildcardToRegEx(const QString &expression);
+ static QString wildcardToRegEx(const QString& expression);
// Original/source components
QString _sourceExpression = {}; ///< Expression match string given on creation
bool _sourceCaseSensitive = false; ///< Expression case sensitive on creation
// Derived components
- bool _sourceExpressionEmpty = false; ///< Cached expression match string is empty
+ bool _sourceExpressionEmpty = false; ///< Cached expression match string is empty
/// Underlying regular expression matching instance for normal (noninverted) rules
QRegularExpression _matchRegEx = {};
- bool _matchRegExActive = false; ///< If true, use normal expression in matching
+ bool _matchRegExActive = false; ///< If true, use normal expression in matching
/// Underlying regular expression matching instance for inverted rules
QRegularExpression _matchInvertRegEx = {};
- bool _matchInvertRegExActive = false; ///< If true, use invert expression in matching
+ bool _matchInvertRegExActive = false; ///< If true, use invert expression in matching
};
// Primary template
template<typename Func>
-struct FuncHelper : public FuncHelper<decltype(&Func::operator())> {};
+struct FuncHelper : public FuncHelper<decltype(&Func::operator())>
+{};
// Overload for member function with const call operator
-template<typename C, typename R, typename ...Args>
-struct FuncHelper<R(C::*)(Args...) const> : public FuncHelper<R(C::*)(Args...)> {};
+template<typename C, typename R, typename... Args>
+struct FuncHelper<R (C::*)(Args...) const> : public FuncHelper<R (C::*)(Args...)>
+{};
// Overload for member function with non-const call operator
-template<typename C, typename R, typename ...Args>
-struct FuncHelper<R(C::*)(Args...)> {
+template<typename C, typename R, typename... Args>
+struct FuncHelper<R (C::*)(Args...)>
+{
using ClassType = C;
using FunctionType = std::function<R(Args...)>;
using ReturnType = R;
/// @endcond
-} // detail
+} // namespace detail
/**
* Provides traits for the given callable.
#include "expressionmatch.h"
#include "util.h"
-HighlightRuleManager &HighlightRuleManager::operator=(const HighlightRuleManager &other)
+HighlightRuleManager& HighlightRuleManager::operator=(const HighlightRuleManager& other)
{
if (this == &other)
return *this;
return *this;
}
-
int HighlightRuleManager::indexOf(int id) const
{
for (int i = 0; i < _highlightRuleList.count(); i++) {
return -1;
}
-
int HighlightRuleManager::nextId()
{
int max = 0;
return max + 1;
}
-
QVariantMap HighlightRuleManager::initHighlightRuleList() const
{
QVariantList id;
return highlightRuleListMap;
}
-
-void HighlightRuleManager::initSetHighlightRuleList(const QVariantMap &highlightRuleList)
+void HighlightRuleManager::initSetHighlightRuleList(const QVariantMap& highlightRuleList)
{
QVariantList id = highlightRuleList["id"].toList();
QStringList name = highlightRuleList["name"].toStringList();
QStringList channel = highlightRuleList["channel"].toStringList();
int count = id.count();
- if (count != name.count() || count != isRegEx.count() || count != isCaseSensitive.count() ||
- count != isActive.count() || count != isInverse.count() || count != sender.count() ||
- count != channel.count()) {
+ if (count != name.count() || count != isRegEx.count() || count != isCaseSensitive.count() || count != isActive.count()
+ || count != isInverse.count() || count != sender.count() || count != channel.count()) {
qWarning() << "Corrupted HighlightRuleList settings! (Count mismatch)";
return;
}
_highlightRuleList.clear();
for (int i = 0; i < name.count(); i++) {
- _highlightRuleList << HighlightRule(id[i].toInt(), name[i], isRegEx[i].toBool(), isCaseSensitive[i].toBool(),
- isActive[i].toBool(), isInverse[i].toBool(), sender[i], channel[i]);
+ _highlightRuleList << HighlightRule(id[i].toInt(),
+ name[i],
+ isRegEx[i].toBool(),
+ isCaseSensitive[i].toBool(),
+ isActive[i].toBool(),
+ isInverse[i].toBool(),
+ sender[i],
+ channel[i]);
}
}
-
-void HighlightRuleManager::addHighlightRule(int id, const QString &name, bool isRegEx, bool isCaseSensitive,
- bool isActive, bool isInverse, const QString &sender,
- const QString &channel)
+void HighlightRuleManager::addHighlightRule(
+ int id, const QString& name, bool isRegEx, bool isCaseSensitive, bool isActive, bool isInverse, const QString& sender, const QString& channel)
{
if (contains(id)) {
return;
HighlightRule newItem = HighlightRule(id, name, isRegEx, isCaseSensitive, isActive, isInverse, sender, channel);
_highlightRuleList << newItem;
- SYNC(ARG(id), ARG(name), ARG(isRegEx), ARG(isCaseSensitive), ARG(isActive), ARG(isInverse), ARG(sender),
- ARG(channel))
+ SYNC(ARG(id), ARG(name), ARG(isRegEx), ARG(isCaseSensitive), ARG(isActive), ARG(isInverse), ARG(sender), ARG(channel))
}
-
-bool HighlightRuleManager::match(const NetworkId &netId,
- const QString &msgContents,
- const QString &msgSender,
+bool HighlightRuleManager::match(const NetworkId& netId,
+ const QString& msgContents,
+ const QString& msgSender,
Message::Type msgType,
Message::Flags msgFlags,
- const QString &bufferName,
- const QString ¤tNick,
- const QStringList &identityNicks)
+ const QString& bufferName,
+ const QString& currentNick,
+ const QStringList& identityNicks)
{
if (!((msgType & (Message::Plain | Message::Notice | Message::Action)) && !(msgFlags & Message::Self))) {
- return false;
+ return false;
}
bool matches = false;
for (int i = 0; i < _highlightRuleList.count(); i++) {
- auto &rule = _highlightRuleList.at(i);
+ auto& rule = _highlightRuleList.at(i);
if (!rule.isEnabled())
continue;
return false;
}
-
void HighlightRuleManager::removeHighlightRule(int highlightRule)
{
removeAt(indexOf(highlightRule));
SYNC(ARG(highlightRule))
}
-
void HighlightRuleManager::toggleHighlightRule(int highlightRule)
{
int idx = indexOf(highlightRule);
SYNC(ARG(highlightRule))
}
-
-bool HighlightRuleManager::match(const Message &msg, const QString ¤tNick, const QStringList &identityNicks)
+bool HighlightRuleManager::match(const Message& msg, const QString& currentNick, const QStringList& identityNicks)
{
- return match(msg.bufferInfo().networkId(), msg.contents(), msg.sender(), msg.type(), msg.flags(),
- msg.bufferInfo().bufferName(), currentNick, identityNicks);
+ return match(msg.bufferInfo().networkId(),
+ msg.contents(),
+ msg.sender(),
+ msg.type(),
+ msg.flags(),
+ msg.bufferInfo().bufferName(),
+ currentNick,
+ identityNicks);
}
-
/**************************************************************************
* HighlightRule
*************************************************************************/
-bool HighlightRuleManager::HighlightRule::operator!=(const HighlightRule &other) const
+bool HighlightRuleManager::HighlightRule::operator!=(const HighlightRule& other) const
{
- return (_id != other._id ||
- _contents != other._contents ||
- _isRegEx != other._isRegEx ||
- _isCaseSensitive != other._isCaseSensitive ||
- _isEnabled != other._isEnabled ||
- _isInverse != other._isInverse ||
- _sender != other._sender ||
- _chanName != other._chanName);
+ return (_id != other._id || _contents != other._contents || _isRegEx != other._isRegEx || _isCaseSensitive != other._isCaseSensitive
+ || _isEnabled != other._isEnabled || _isInverse != other._isInverse || _sender != other._sender || _chanName != other._chanName);
// Don't compare ExpressionMatch objects as they are created as needed from the above
}
-
void HighlightRuleManager::HighlightRule::determineExpressions() const
{
// Don't update if not needed
// Set up matching rules
// Message is either phrase or regex
- ExpressionMatch::MatchMode contentsMode =
- _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx :
- ExpressionMatch::MatchMode::MatchPhrase;
+ ExpressionMatch::MatchMode contentsMode = _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx : ExpressionMatch::MatchMode::MatchPhrase;
// Sender and channel are either multiple wildcard entries or regex
- ExpressionMatch::MatchMode scopeMode =
- _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx :
- ExpressionMatch::MatchMode::MatchMultiWildcard;
+ ExpressionMatch::MatchMode scopeMode = _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx : ExpressionMatch::MatchMode::MatchMultiWildcard;
_contentsMatch = ExpressionMatch(_contents, contentsMode, _isCaseSensitive);
_senderMatch = ExpressionMatch(_sender, scopeMode, _isCaseSensitive);
Q_PROPERTY(bool nicksCaseSensitive READ nicksCaseSensitive WRITE setNicksCaseSensitive)
public:
- enum HighlightNickType {
+ enum HighlightNickType
+ {
NoNick = 0x00,
CurrentNick = 0x01,
AllNicks = 0x02
};
- inline HighlightRuleManager(QObject *parent = nullptr) : SyncableObject(parent) { setAllowClientUpdates(true); }
- HighlightRuleManager &operator=(const HighlightRuleManager &other);
+ inline HighlightRuleManager(QObject* parent = nullptr)
+ : SyncableObject(parent)
+ {
+ setAllowClientUpdates(true);
+ }
+ HighlightRuleManager& operator=(const HighlightRuleManager& other);
/**
* Individual highlight rule
* @param sender String representing a message sender expression to match
* @param chanName String representing a channel name expression to match
*/
- HighlightRule(int id, QString contents, bool isRegEx, bool isCaseSensitive, bool isEnabled,
- bool isInverse, QString sender, QString chanName)
- : _id(id), _contents(std::move(contents)), _isRegEx(isRegEx), _isCaseSensitive(isCaseSensitive),
- _isEnabled(isEnabled), _isInverse(isInverse), _sender(std::move(sender)), _chanName(std::move(chanName))
+ HighlightRule(
+ int id, QString contents, bool isRegEx, bool isCaseSensitive, bool isEnabled, bool isInverse, QString sender, QString chanName)
+ : _id(id)
+ , _contents(std::move(contents))
+ , _isRegEx(isRegEx)
+ , _isCaseSensitive(isCaseSensitive)
+ , _isEnabled(isEnabled)
+ , _isInverse(isInverse)
+ , _sender(std::move(sender))
+ , _chanName(std::move(chanName))
{
_cacheInvalid = true;
// Cache expression matches on construction
*
* @return Integer ID of the rule
*/
- inline int id() const {
- return _id;
- }
+ inline int id() const { return _id; }
/**
* Sets the ID of this rule
*
*
* @param id Integer ID of the rule
*/
- inline void setId(int id) {
- _id = id;
- }
+ inline void setId(int id) { _id = id; }
/**
* Gets the message contents this rule matches
*
* @return String representing a phrase or expression to match
*/
- inline QString contents() const {
- return _contents;
- }
+ inline QString contents() const { return _contents; }
/**
* Sets the message contents this rule matches
*
* @param contents String representing a phrase or expression to match
*/
- inline void setContents(const QString &contents) {
+ inline void setContents(const QString& contents)
+ {
_contents = contents;
_cacheInvalid = true;
}
*
* @return True if regular expression, otherwise false
*/
- inline bool isRegEx() const {
- return _isRegEx;
- }
+ inline bool isRegEx() const { return _isRegEx; }
/**
* Sets if this rule is a regular expression rule
*
* @param isRegEx True if regular expression, otherwise false
*/
- inline void setIsRegEx(bool isRegEx) {
+ inline void setIsRegEx(bool isRegEx)
+ {
_isRegEx = isRegEx;
_cacheInvalid = true;
}
*
* @return True if case sensitive, otherwise false
*/
- inline bool isCaseSensitive() const {
- return _isCaseSensitive;
- }
+ inline bool isCaseSensitive() const { return _isCaseSensitive; }
/**
* Sets if this rule is case sensitive
*
* @param isCaseSensitive True if case sensitive, otherwise false
*/
- inline void setIsCaseSensitive(bool isCaseSensitive) {
+ inline void setIsCaseSensitive(bool isCaseSensitive)
+ {
_isCaseSensitive = isCaseSensitive;
_cacheInvalid = true;
}
*
* @return True if enabled, otherwise false
*/
- inline bool isEnabled() const {
- return _isEnabled;
- }
+ inline bool isEnabled() const { return _isEnabled; }
/**
* Sets if this rule is enabled and active
*
* @param isEnabled True if enabled, otherwise false
*/
- inline void setIsEnabled(bool isEnabled) {
- _isEnabled = isEnabled;
- }
+ inline void setIsEnabled(bool isEnabled) { _isEnabled = isEnabled; }
/**
* Gets if this rule is a highlight ignore rule
*
* @return True if rule is treated as highlight ignore, otherwise false
*/
- inline bool isInverse() const {
- return _isInverse;
- }
+ inline bool isInverse() const { return _isInverse; }
/**
* Sets if this rule is a highlight ignore rule
*
* @param isInverse True if rule is treated as highlight ignore, otherwise false
*/
- inline void setIsInverse(bool isInverse) {
- _isInverse = isInverse;
- }
+ inline void setIsInverse(bool isInverse) { _isInverse = isInverse; }
/**
* Gets the message sender this rule matches
*
* @param sender String representing a phrase or expression to match
*/
- inline void setSender(const QString &sender) {
+ inline void setSender(const QString& sender)
+ {
_sender = sender;
_cacheInvalid = true;
}
*
* @param chanName String representing a phrase or expression to match
*/
- inline void setChanName(const QString &chanName) {
+ inline void setChanName(const QString& chanName)
+ {
_chanName = chanName;
_cacheInvalid = true;
}
*
* @return Expression matcher to compare with message contents
*/
- inline ExpressionMatch contentsMatcher() const {
+ inline ExpressionMatch contentsMatcher() const
+ {
if (_cacheInvalid) {
determineExpressions();
}
*
* @return Expression matcher to compare with message sender
*/
- inline ExpressionMatch senderMatcher() const {
+ inline ExpressionMatch senderMatcher() const
+ {
if (_cacheInvalid) {
determineExpressions();
}
*
* @return Expression matcher to compare with channel name
*/
- inline ExpressionMatch chanNameMatcher() const {
+ inline ExpressionMatch chanNameMatcher() const
+ {
if (_cacheInvalid) {
determineExpressions();
}
return _chanNameMatch;
}
- bool operator!=(const HighlightRule &other) const;
+ bool operator!=(const HighlightRule& other) const;
private:
/**
// These represent internal cache and should be safe to mutate in 'const' functions
// See https://stackoverflow.com/questions/3141087/what-is-meant-with-const-at-end-of-function-declaration
- mutable bool _cacheInvalid = true; ///< If true, match cache needs redone
- mutable ExpressionMatch _contentsMatch = {}; ///< Expression match cache for message content
- mutable ExpressionMatch _senderMatch = {}; ///< Expression match cache for sender
- mutable ExpressionMatch _chanNameMatch = {}; ///< Expression match cache for channel name
+ mutable bool _cacheInvalid = true; ///< If true, match cache needs redone
+ mutable ExpressionMatch _contentsMatch = {}; ///< Expression match cache for message content
+ mutable ExpressionMatch _senderMatch = {}; ///< Expression match cache for sender
+ mutable ExpressionMatch _chanNameMatch = {}; ///< Expression match cache for channel name
};
using HighlightRuleList = QList<HighlightRule>;
inline int count() const { return _highlightRuleList.count(); }
inline void removeAt(int index) { _highlightRuleList.removeAt(index); }
inline void clear() { _highlightRuleList.clear(); }
- inline HighlightRule &operator[](int i) { return _highlightRuleList[i]; }
- inline const HighlightRule &operator[](int i) const { return _highlightRuleList.at(i); }
- inline const HighlightRuleList &highlightRuleList() const { return _highlightRuleList; }
+ inline HighlightRule& operator[](int i) { return _highlightRuleList[i]; }
+ inline const HighlightRule& operator[](int i) const { return _highlightRuleList.at(i); }
+ inline const HighlightRuleList& highlightRuleList() const { return _highlightRuleList; }
int nextId();
//! Check if a message matches the HighlightRule
/** This method checks if a message matches the users highlight rules.
- * \param msg The Message that should be checked
- */
- bool match(const Message &msg, const QString ¤tNick, const QStringList &identityNicks);
+ * \param msg The Message that should be checked
+ */
+ bool match(const Message& msg, const QString& currentNick, const QStringList& identityNicks);
public slots:
virtual QVariantMap initHighlightRuleList() const;
- virtual void initSetHighlightRuleList(const QVariantMap &HighlightRuleList);
+ virtual void initSetHighlightRuleList(const QVariantMap& HighlightRuleList);
//! Request removal of an ignore rule based on the rule itself.
/** Use this method if you want to remove a single ignore rule
- * and get that synced with the core immediately.
- * \param highlightRule A valid ignore rule
- */
+ * and get that synced with the core immediately.
+ * \param highlightRule A valid ignore rule
+ */
virtual inline void requestRemoveHighlightRule(int highlightRule) { REQUEST(ARG(highlightRule)) }
virtual void removeHighlightRule(int highlightRule);
//! Request toggling of "isEnabled" flag of a given ignore rule.
/** Use this method if you want to toggle the "isEnabled" flag of a single ignore rule
- * and get that synced with the core immediately.
- * \param highlightRule A valid ignore rule
- */
+ * and get that synced with the core immediately.
+ * \param highlightRule A valid ignore rule
+ */
virtual inline void requestToggleHighlightRule(int highlightRule) { REQUEST(ARG(highlightRule)) }
virtual void toggleHighlightRule(int highlightRule);
//! Request an HighlightRule to be added to the ignore list
/** Items added to the list with this method, get immediately synced with the core
- * \param name The rule
- * \param isRegEx If the rule should be interpreted as a nickname, or a regex
- * \param isCaseSensitive If the rule should be interpreted as case-sensitive
- * \param isEnabled If the rule is active
- * @param chanName The channel in which the rule should apply
- */
- virtual inline void requestAddHighlightRule(int id, const QString &name, bool isRegEx, bool isCaseSensitive, bool isEnabled,
- bool isInverse, const QString &sender, const QString &chanName)
+ * \param name The rule
+ * \param isRegEx If the rule should be interpreted as a nickname, or a regex
+ * \param isCaseSensitive If the rule should be interpreted as case-sensitive
+ * \param isEnabled If the rule is active
+ * @param chanName The channel in which the rule should apply
+ */
+ virtual inline void requestAddHighlightRule(int id,
+ const QString& name,
+ bool isRegEx,
+ bool isCaseSensitive,
+ bool isEnabled,
+ bool isInverse,
+ const QString& sender,
+ const QString& chanName)
{
- REQUEST(ARG(id), ARG(name), ARG(isRegEx), ARG(isCaseSensitive), ARG(isEnabled), ARG(isInverse), ARG(sender),
- ARG(chanName))
+ REQUEST(ARG(id), ARG(name), ARG(isRegEx), ARG(isCaseSensitive), ARG(isEnabled), ARG(isInverse), ARG(sender), ARG(chanName))
}
+ virtual void addHighlightRule(int id,
+ const QString& name,
+ bool isRegEx,
+ bool isCaseSensitive,
+ bool isEnabled,
+ bool isInverse,
+ const QString& sender,
+ const QString& chanName);
- virtual void addHighlightRule(int id, const QString &name, bool isRegEx, bool isCaseSensitive, bool isEnabled,
- bool isInverse, const QString &sender, const QString &chanName);
+ virtual inline void requestSetHighlightNick(int highlightNick) { REQUEST(ARG(highlightNick)) }
- virtual inline void requestSetHighlightNick(int highlightNick)
+ inline void setHighlightNick(int highlightNick)
{
- REQUEST(ARG(highlightNick))
- }
-
- inline void setHighlightNick(int highlightNick) {
_highlightNick = static_cast<HighlightNickType>(highlightNick);
// Convert from HighlightRuleManager::HighlightNickType to
// NickHighlightMatcher::HighlightNickType
- _nickMatcher.setHighlightMode(
- static_cast<NickHighlightMatcher::HighlightNickType>(_highlightNick));
+ _nickMatcher.setHighlightMode(static_cast<NickHighlightMatcher::HighlightNickType>(_highlightNick));
}
- virtual inline void requestSetNicksCaseSensitive(bool nicksCaseSensitive)
- {
- REQUEST(ARG(nicksCaseSensitive))
- }
+ virtual inline void requestSetNicksCaseSensitive(bool nicksCaseSensitive) { REQUEST(ARG(nicksCaseSensitive)) }
- inline void setNicksCaseSensitive(bool nicksCaseSensitive) {
+ inline void setNicksCaseSensitive(bool nicksCaseSensitive)
+ {
_nicksCaseSensitive = nicksCaseSensitive;
// Update nickname matcher, too
_nickMatcher.setCaseSensitive(nicksCaseSensitive);
*
* @param id Network ID of removed network
*/
- inline void networkRemoved(NetworkId id) {
+ inline void networkRemoved(NetworkId id)
+ {
// Clean up nickname matching cache
_nickMatcher.removeNetwork(id);
}
protected:
- void setHighlightRuleList(const QList<HighlightRule> &HighlightRuleList) { _highlightRuleList = HighlightRuleList; }
+ void setHighlightRuleList(const QList<HighlightRule>& HighlightRuleList) { _highlightRuleList = HighlightRuleList; }
- bool match(const NetworkId &netId,
- const QString &msgContents,
- const QString &msgSender,
+ bool match(const NetworkId& netId,
+ const QString& msgContents,
+ const QString& msgSender,
Message::Type msgType,
Message::Flags msgFlags,
- const QString &bufferName,
- const QString ¤tNick,
- const QStringList &identityNicks);
+ const QString& bufferName,
+ const QString& currentNick,
+ const QStringList& identityNicks);
signals:
void ruleAdded(QString name, bool isRegEx, bool isCaseSensitive, bool isEnabled, bool isInverse, QString sender, QString chanName);
private:
- HighlightRuleList _highlightRuleList = {}; ///< Custom highlight rule list
- NickHighlightMatcher _nickMatcher = {}; ///< Nickname highlight matcher
+ HighlightRuleList _highlightRuleList = {}; ///< Custom highlight rule list
+ NickHighlightMatcher _nickMatcher = {}; ///< Nickname highlight matcher
/// Nickname highlighting mode
HighlightNickType _highlightNick = HighlightNickType::CurrentNick;
- bool _nicksCaseSensitive = false; ///< If true, match nicknames with exact case
+ bool _nicksCaseSensitive = false; ///< If true, match nicknames with exact case
};
#include "identity.h"
#include <QMetaProperty>
-#include <QVariantMap>
#include <QString>
+#include <QVariantMap>
#ifdef Q_OS_MAC
-# include <CoreServices/CoreServices.h>
-# include "mac_utils.h"
+# include <CoreServices/CoreServices.h>
+
+# include "mac_utils.h"
#endif
#ifdef Q_OS_UNIX
-# include <sys/types.h>
-# include <pwd.h>
-# include <unistd.h>
+# include <pwd.h>
+# include <sys/types.h>
+# include <unistd.h>
#endif
#ifdef Q_OS_WIN
-# include <windows.h>
-# include <Winbase.h>
-# define SECURITY_WIN32
-# include <Security.h>
+# include <windows.h>
+# include <Winbase.h>
+# define SECURITY_WIN32
+# include <Security.h>
#endif
-Identity::Identity(IdentityId id, QObject *parent)
- : SyncableObject(parent),
- _identityId(id)
+Identity::Identity(IdentityId id, QObject* parent)
+ : SyncableObject(parent)
+ , _identityId(id)
{
init();
setToDefaults();
}
-
-Identity::Identity(const Identity &other, QObject *parent)
- : SyncableObject(parent),
- _identityId(other.id()),
- _identityName(other.identityName()),
- _realName(other.realName()),
- _nicks(other.nicks()),
- _awayNick(other.awayNick()),
- _awayNickEnabled(other.awayNickEnabled()),
- _awayReason(other.awayReason()),
- _awayReasonEnabled(other.awayReasonEnabled()),
- _autoAwayEnabled(other.autoAwayEnabled()),
- _autoAwayTime(other.autoAwayTime()),
- _autoAwayReason(other.autoAwayReason()),
- _autoAwayReasonEnabled(other.autoAwayReasonEnabled()),
- _detachAwayEnabled(other.detachAwayEnabled()),
- _detachAwayReason(other.detachAwayReason()),
- _detachAwayReasonEnabled(other.detachAwayReasonEnabled()),
- _ident(other.ident()),
- _kickReason(other.kickReason()),
- _partReason(other.partReason()),
- _quitReason(other.quitReason())
+Identity::Identity(const Identity& other, QObject* parent)
+ : SyncableObject(parent)
+ , _identityId(other.id())
+ , _identityName(other.identityName())
+ , _realName(other.realName())
+ , _nicks(other.nicks())
+ , _awayNick(other.awayNick())
+ , _awayNickEnabled(other.awayNickEnabled())
+ , _awayReason(other.awayReason())
+ , _awayReasonEnabled(other.awayReasonEnabled())
+ , _autoAwayEnabled(other.autoAwayEnabled())
+ , _autoAwayTime(other.autoAwayTime())
+ , _autoAwayReason(other.autoAwayReason())
+ , _autoAwayReasonEnabled(other.autoAwayReasonEnabled())
+ , _detachAwayEnabled(other.detachAwayEnabled())
+ , _detachAwayReason(other.detachAwayReason())
+ , _detachAwayReasonEnabled(other.detachAwayReasonEnabled())
+ , _ident(other.ident())
+ , _kickReason(other.kickReason())
+ , _partReason(other.partReason())
+ , _quitReason(other.quitReason())
{
init();
}
-
#ifdef Q_OS_WIN
-#ifdef UNICODE
-QString tcharToQString(TCHAR *tchar)
+# ifdef UNICODE
+QString tcharToQString(TCHAR* tchar)
{
- return QString::fromUtf16(reinterpret_cast<ushort *>(tchar));
+ return QString::fromUtf16(reinterpret_cast<ushort*>(tchar));
}
-
-#else
-QString tcharToQString(TCHAR *tchar)
+# else
+QString tcharToQString(TCHAR* tchar)
{
return QString::fromLocal8Bit(tchar);
}
-
-#endif
+# endif
#endif
void Identity::init()
setAllowClientUpdates(true);
}
-
QString Identity::defaultNick()
{
- QString nick = QString("quassel%1").arg(qrand() & 0xff); // FIXME provide more sensible default nicks
+ QString nick = QString("quassel%1").arg(qrand() & 0xff); // FIXME provide more sensible default nicks
#ifdef Q_OS_MAC
QString shortUserName = CFStringToQString(CSCopyUserName(true));
#elif defined(Q_OS_UNIX)
QString userName;
- struct passwd *pwd = getpwuid(getuid());
+ struct passwd* pwd = getpwuid(getuid());
if (pwd)
userName = pwd->pw_name;
if (!userName.isEmpty())
#elif defined(Q_OS_WIN)
TCHAR infoBuf[128];
DWORD bufCharCount = 128;
- //if(GetUserNameEx(/* NameSamCompatible */ 1, infoBuf, &bufCharCount))
+ // if(GetUserNameEx(/* NameSamCompatible */ 1, infoBuf, &bufCharCount))
if (GetUserNameEx(NameSamCompatible, infoBuf, &bufCharCount)) {
QString nickName(tcharToQString(infoBuf));
int lastBs = nickName.lastIndexOf('\\');
return nick;
}
-
QString Identity::defaultRealName()
{
QString generalDefault = tr("Quassel IRC User");
#elif defined(Q_OS_UNIX)
QString realName;
- struct passwd *pwd = getpwuid(getuid());
+ struct passwd* pwd = getpwuid(getuid());
if (pwd)
realName = QString::fromUtf8(pwd->pw_gecos);
if (!realName.isEmpty())
#endif
}
-
void Identity::setToDefaults()
{
setIdentityName(tr("<empty>"));
setQuitReason(tr("https://quassel-irc.org - Chat comfortably. Anywhere."));
}
-
/*** setters ***/
void Identity::setId(IdentityId _id)
renameObject(QString::number(id().toInt()));
}
-
-void Identity::setIdentityName(const QString &identityName)
+void Identity::setIdentityName(const QString& identityName)
{
_identityName = identityName;
SYNC(ARG(identityName))
}
-
-void Identity::setRealName(const QString &realName)
+void Identity::setRealName(const QString& realName)
{
_realName = realName;
SYNC(ARG(realName))
}
-
-void Identity::setNicks(const QStringList &nicks)
+void Identity::setNicks(const QStringList& nicks)
{
_nicks = nicks;
SYNC(ARG(nicks))
emit nicksSet(nicks);
}
-
-void Identity::setAwayNick(const QString &nick)
+void Identity::setAwayNick(const QString& nick)
{
_awayNick = nick;
SYNC(ARG(nick))
}
-
-void Identity::setAwayReason(const QString &reason)
+void Identity::setAwayReason(const QString& reason)
{
_awayReason = reason;
SYNC(ARG(reason))
}
-
void Identity::setAwayNickEnabled(bool enabled)
{
_awayNickEnabled = enabled;
SYNC(ARG(enabled))
}
-
void Identity::setAwayReasonEnabled(bool enabled)
{
_awayReasonEnabled = enabled;
SYNC(ARG(enabled))
}
-
void Identity::setAutoAwayEnabled(bool enabled)
{
_autoAwayEnabled = enabled;
SYNC(ARG(enabled))
}
-
void Identity::setAutoAwayTime(int time)
{
_autoAwayTime = time;
SYNC(ARG(time))
}
-
-void Identity::setAutoAwayReason(const QString &reason)
+void Identity::setAutoAwayReason(const QString& reason)
{
_autoAwayReason = reason;
SYNC(ARG(reason))
}
-
void Identity::setAutoAwayReasonEnabled(bool enabled)
{
_autoAwayReasonEnabled = enabled;
SYNC(ARG(enabled))
}
-
void Identity::setDetachAwayEnabled(bool enabled)
{
_detachAwayEnabled = enabled;
SYNC(ARG(enabled))
}
-
-void Identity::setDetachAwayReason(const QString &reason)
+void Identity::setDetachAwayReason(const QString& reason)
{
_detachAwayReason = reason;
SYNC(ARG(reason))
}
-
void Identity::setDetachAwayReasonEnabled(bool enabled)
{
_detachAwayReasonEnabled = enabled;
SYNC(ARG(enabled))
}
-
-void Identity::setIdent(const QString &ident)
+void Identity::setIdent(const QString& ident)
{
_ident = ident;
SYNC(ARG(ident))
}
-
-void Identity::setKickReason(const QString &reason)
+void Identity::setKickReason(const QString& reason)
{
_kickReason = reason;
SYNC(ARG(reason))
}
-
-void Identity::setPartReason(const QString &reason)
+void Identity::setPartReason(const QString& reason)
{
_partReason = reason;
SYNC(ARG(reason))
}
-
-void Identity::setQuitReason(const QString &reason)
+void Identity::setQuitReason(const QString& reason)
{
_quitReason = reason;
SYNC(ARG(reason))
}
-
/*** ***/
-void Identity::copyFrom(const Identity &other)
+void Identity::copyFrom(const Identity& other)
{
for (int idx = staticMetaObject.propertyOffset(); idx < staticMetaObject.propertyCount(); idx++) {
QMetaProperty metaProp = staticMetaObject.property(idx);
}
}
-
-bool Identity::operator==(const Identity &other) const
+bool Identity::operator==(const Identity& other) const
{
for (int idx = staticMetaObject.propertyOffset(); idx < staticMetaObject.propertyCount(); idx++) {
QMetaProperty metaProp = staticMetaObject.property(idx);
Q_ASSERT(metaProp.isValid());
QVariant v1 = this->property(metaProp.name());
- QVariant v2 = other.property(metaProp.name()); // qDebug() << v1 << v2;
+ QVariant v2 = other.property(metaProp.name()); // qDebug() << v1 << v2;
// QVariant cannot compare custom types, so we need to check for this special case
if (QString(v1.typeName()) == "IdentityId") {
- if (v1.value<IdentityId>() != v2.value<IdentityId>()) return false;
+ if (v1.value<IdentityId>() != v2.value<IdentityId>())
+ return false;
}
else {
- if (v1 != v2) return false;
+ if (v1 != v2)
+ return false;
}
}
return true;
}
-
-bool Identity::operator!=(const Identity &other) const
+bool Identity::operator!=(const Identity& other) const
{
return !(*this == other);
}
-
///////////////////////////////
-QDataStream &operator<<(QDataStream &out, Identity id)
+QDataStream& operator<<(QDataStream& out, Identity id)
{
out << id.toVariantMap();
return out;
}
-
-QDataStream &operator>>(QDataStream &in, Identity &id)
+QDataStream& operator>>(QDataStream& in, Identity& id)
{
QVariantMap i;
in >> i;
#include <QString>
#include <QStringList>
-#include "types.h"
#include "syncableobject.h"
+#include "types.h"
class COMMON_EXPORT Identity : public SyncableObject
{
Q_PROPERTY(QString partReason READ partReason WRITE setPartReason)
Q_PROPERTY(QString quitReason READ quitReason WRITE setQuitReason)
-public :
- Identity(IdentityId id = 0, QObject *parent = nullptr);
- Identity(const Identity &other, QObject *parent = nullptr);
+public:
+ Identity(IdentityId id = 0, QObject* parent = nullptr);
+ Identity(const Identity& other, QObject* parent = nullptr);
void setToDefaults();
- bool operator==(const Identity &other) const;
- bool operator!=(const Identity &other) const;
+ bool operator==(const Identity& other) const;
+ bool operator!=(const Identity& other) const;
inline bool isValid() const { return id().isValid(); }
inline IdentityId id() const { return _identityId; }
- inline const QString &identityName() const { return _identityName; }
- inline const QString &realName() const { return _realName; }
- inline const QStringList &nicks() const { return _nicks; }
- inline const QString &awayNick() const { return _awayNick; }
+ inline const QString& identityName() const { return _identityName; }
+ inline const QString& realName() const { return _realName; }
+ inline const QStringList& nicks() const { return _nicks; }
+ inline const QString& awayNick() const { return _awayNick; }
inline bool awayNickEnabled() const { return _awayNickEnabled; }
- inline const QString &awayReason() const { return _awayReason; }
+ inline const QString& awayReason() const { return _awayReason; }
inline bool awayReasonEnabled() const { return _awayReasonEnabled; }
inline bool autoAwayEnabled() const { return _autoAwayEnabled; }
inline int autoAwayTime() const { return _autoAwayTime; }
- inline const QString &autoAwayReason() const { return _autoAwayReason; }
+ inline const QString& autoAwayReason() const { return _autoAwayReason; }
inline bool autoAwayReasonEnabled() const { return _autoAwayReasonEnabled; }
inline bool detachAwayEnabled() const { return _detachAwayEnabled; }
- inline const QString &detachAwayReason() const { return _detachAwayReason; }
+ inline const QString& detachAwayReason() const { return _detachAwayReason; }
inline bool detachAwayReasonEnabled() const { return _detachAwayReasonEnabled; }
- inline const QString &ident() const { return _ident; }
- inline const QString &kickReason() const { return _kickReason; }
- inline const QString &partReason() const { return _partReason; }
- inline const QString &quitReason() const { return _quitReason; }
+ inline const QString& ident() const { return _ident; }
+ inline const QString& kickReason() const { return _kickReason; }
+ inline const QString& partReason() const { return _partReason; }
+ inline const QString& quitReason() const { return _quitReason; }
public slots:
void setId(IdentityId id);
- void setIdentityName(const QString &name);
- void setRealName(const QString &realName);
- void setNicks(const QStringList &nicks);
- void setAwayNick(const QString &awayNick);
+ void setIdentityName(const QString& name);
+ void setRealName(const QString& realName);
+ void setNicks(const QStringList& nicks);
+ void setAwayNick(const QString& awayNick);
void setAwayNickEnabled(bool enabled);
- void setAwayReason(const QString &awayReason);
+ void setAwayReason(const QString& awayReason);
void setAwayReasonEnabled(bool enabled);
void setAutoAwayEnabled(bool enabled);
void setAutoAwayTime(int time);
- void setAutoAwayReason(const QString &reason);
+ void setAutoAwayReason(const QString& reason);
void setAutoAwayReasonEnabled(bool enabled);
void setDetachAwayEnabled(bool enabled);
- void setDetachAwayReason(const QString &reason);
+ void setDetachAwayReason(const QString& reason);
void setDetachAwayReasonEnabled(bool enabled);
- void setIdent(const QString &ident);
- void setKickReason(const QString &reason);
- void setPartReason(const QString &reason);
- void setQuitReason(const QString &reason);
+ void setIdent(const QString& ident);
+ void setKickReason(const QString& reason);
+ void setPartReason(const QString& reason);
+ void setQuitReason(const QString& reason);
- void copyFrom(const Identity &other);
+ void copyFrom(const Identity& other);
signals:
void idSet(IdentityId id);
-// void identityNameSet(const QString &name);
-// void realNameSet(const QString &realName);
- void nicksSet(const QStringList &nicks);
-// void awayNickSet(const QString &awayNick);
-// void awayNickEnabledSet(bool);
-// void awayReasonSet(const QString &awayReason);
-// void awayReasonEnabledSet(bool);
-// void autoAwayEnabledSet(bool);
-// void autoAwayTimeSet(int);
-// void autoAwayReasonSet(const QString &);
-// void autoAwayReasonEnabledSet(bool);
-// void detachAwayEnabledSet(bool);
-// void detachAwayReasonSet(const QString &);
-// void detachAwayReasonEnabledSet(bool);
-// void identSet(const QString &);
-// void kickReasonSet(const QString &);
-// void partReasonSet(const QString &);
-// void quitReasonSet(const QString &);
+ // void identityNameSet(const QString &name);
+ // void realNameSet(const QString &realName);
+ void nicksSet(const QStringList& nicks);
+ // void awayNickSet(const QString &awayNick);
+ // void awayNickEnabledSet(bool);
+ // void awayReasonSet(const QString &awayReason);
+ // void awayReasonEnabledSet(bool);
+ // void autoAwayEnabledSet(bool);
+ // void autoAwayTimeSet(int);
+ // void autoAwayReasonSet(const QString &);
+ // void autoAwayReasonEnabledSet(bool);
+ // void detachAwayEnabledSet(bool);
+ // void detachAwayReasonSet(const QString &);
+ // void detachAwayReasonEnabledSet(bool);
+ // void identSet(const QString &);
+ // void kickReasonSet(const QString &);
+ // void partReasonSet(const QString &);
+ // void quitReasonSet(const QString &);
private:
IdentityId _identityId;
QString defaultNick();
QString defaultRealName();
- friend QDataStream &operator>>(QDataStream &in, Identity &identity);
+ friend QDataStream& operator>>(QDataStream& in, Identity& identity);
};
-
-QDataStream &operator<<(QDataStream &out, Identity identity);
-QDataStream &operator>>(QDataStream &in, Identity &identity);
+QDataStream& operator<<(QDataStream& out, Identity identity);
+QDataStream& operator>>(QDataStream& in, Identity& identity);
Q_DECLARE_METATYPE(Identity)
#ifdef HAVE_SSL
-#include <QSslKey>
-#include <QSslCertificate>
+# include <QSslCertificate>
+# include <QSslKey>
class COMMON_EXPORT CertManager : public SyncableObject
{
Q_PROPERTY(QByteArray sslKey READ sslKeyPem WRITE setSslKey)
Q_PROPERTY(QByteArray sslCert READ sslCertPem WRITE setSslCert)
-public :
- CertManager(IdentityId id, QObject *parent = nullptr) : SyncableObject(QString::number(id.toInt()), parent) {}
+public:
+ CertManager(IdentityId id, QObject* parent = nullptr)
+ : SyncableObject(QString::number(id.toInt()), parent)
+ {}
- virtual const QSslKey &sslKey() const = 0;
+ virtual const QSslKey& sslKey() const = 0;
inline QByteArray sslKeyPem() const { return sslKey().toPem(); }
- virtual const QSslCertificate &sslCert() const = 0;
+ virtual const QSslCertificate& sslCert() const = 0;
inline QByteArray sslCertPem() const { return sslCert().toPem(); }
public slots:
- inline virtual void setSslKey(const QByteArray &encoded) { SYNC(ARG(encoded)) }
- inline virtual void setSslCert(const QByteArray &encoded) { SYNC(ARG(encoded)) }
+ inline virtual void setSslKey(const QByteArray& encoded) { SYNC(ARG(encoded)) }
+ inline virtual void setSslCert(const QByteArray& encoded) { SYNC(ARG(encoded)) }
};
-#endif // HAVE_SSL
+#endif // HAVE_SSL
#include "ignorelistmanager.h"
-#include <QtCore>
#include <QDebug>
#include <QStringList>
+#include <QtCore>
-IgnoreListManager &IgnoreListManager::operator=(const IgnoreListManager &other)
+IgnoreListManager& IgnoreListManager::operator=(const IgnoreListManager& other)
{
if (this == &other)
return *this;
return *this;
}
-
-int IgnoreListManager::indexOf(const QString &ignore) const
+int IgnoreListManager::indexOf(const QString& ignore) const
{
for (int i = 0; i < _ignoreList.count(); i++) {
if (_ignoreList[i].contents() == ignore)
return -1;
}
-
QVariantMap IgnoreListManager::initIgnoreList() const
{
QVariantMap ignoreListMap;
return ignoreListMap;
}
-
-void IgnoreListManager::initSetIgnoreList(const QVariantMap &ignoreList)
+void IgnoreListManager::initSetIgnoreList(const QVariantMap& ignoreList)
{
QVariantList ignoreType = ignoreList["ignoreType"].toList();
QStringList ignoreRule = ignoreList["ignoreRule"].toStringList();
QVariantList isActive = ignoreList["isActive"].toList();
int count = ignoreRule.count();
- if (count != scopeRule.count() || count != isRegEx.count() ||
- count != scope.count() || count != strictness.count() || count != ignoreType.count() || count != isActive.count()) {
+ if (count != scopeRule.count() || count != isRegEx.count() || count != scope.count() || count != strictness.count()
+ || count != ignoreType.count() || count != isActive.count()) {
qWarning() << "Corrupted IgnoreList settings! (Count mismatch)";
return;
}
_ignoreList.clear();
for (int i = 0; i < ignoreRule.count(); i++) {
- _ignoreList << IgnoreListItem(static_cast<IgnoreType>(ignoreType[i].toInt()), ignoreRule[i], isRegEx[i].toBool(),
- static_cast<StrictnessType>(strictness[i].toInt()), static_cast<ScopeType>(scope[i].toInt()),
- scopeRule[i], isActive[i].toBool());
+ _ignoreList << IgnoreListItem(static_cast<IgnoreType>(ignoreType[i].toInt()),
+ ignoreRule[i],
+ isRegEx[i].toBool(),
+ static_cast<StrictnessType>(strictness[i].toInt()),
+ static_cast<ScopeType>(scope[i].toInt()),
+ scopeRule[i],
+ isActive[i].toBool());
}
}
-
/* since overloaded methods aren't syncable (yet?) we can't use that anymore
void IgnoreListManager::addIgnoreListItem(const IgnoreListItem &item) {
addIgnoreListItem(item.type(), item.contents(), item.isRegEx(), item.strictness(), item.scope(), item.scopeRule(), item.isEnabled());
}
*/
-void IgnoreListManager::addIgnoreListItem(int type, const QString &ignoreRule, bool isRegEx, int strictness,
- int scope, const QString &scopeRule, bool isActive)
+void IgnoreListManager::addIgnoreListItem(
+ int type, const QString& ignoreRule, bool isRegEx, int strictness, int scope, const QString& scopeRule, bool isActive)
{
if (contains(ignoreRule)) {
return;
}
- IgnoreListItem newItem = IgnoreListItem(static_cast<IgnoreType>(type), ignoreRule, isRegEx, static_cast<StrictnessType>(strictness),
- static_cast<ScopeType>(scope), scopeRule, isActive);
+ IgnoreListItem newItem = IgnoreListItem(static_cast<IgnoreType>(type),
+ ignoreRule,
+ isRegEx,
+ static_cast<StrictnessType>(strictness),
+ static_cast<ScopeType>(scope),
+ scopeRule,
+ isActive);
_ignoreList << newItem;
SYNC(ARG(type), ARG(ignoreRule), ARG(isRegEx), ARG(strictness), ARG(scope), ARG(scopeRule), ARG(isActive))
}
-
-IgnoreListManager::StrictnessType IgnoreListManager::_match(const QString &msgContents, const QString &msgSender, Message::Type msgType, const QString &network, const QString &bufferName)
+IgnoreListManager::StrictnessType IgnoreListManager::_match(
+ const QString& msgContents, const QString& msgSender, Message::Type msgType, const QString& network, const QString& bufferName)
{
// We method don't rely on a proper Message object to make this method more versatile.
// This allows us to use it in the core with unprocessed Messages or in the Client
if (!(msgType & (Message::Plain | Message::Notice | Message::Action)))
return UnmatchedStrictness;
- foreach(IgnoreListItem item, _ignoreList) {
+ foreach (IgnoreListItem item, _ignoreList) {
if (!item.isEnabled() || item.type() == CtcpIgnore)
continue;
- if (item.scope() == GlobalScope
- || (item.scope() == NetworkScope && item.scopeRuleMatcher().match(network))
+ if (item.scope() == GlobalScope || (item.scope() == NetworkScope && item.scopeRuleMatcher().match(network))
|| (item.scope() == ChannelScope && item.scopeRuleMatcher().match(bufferName))) {
QString str;
if (item.type() == MessageIgnore)
else
str = msgSender;
-// qDebug() << "IgnoreListManager::match: ";
-// qDebug() << "string: " << str;
-// qDebug() << "pattern: " << ruleRx.pattern();
-// qDebug() << "scopeRule: " << item.scopeRule;
-// qDebug() << "now testing";
+ // qDebug() << "IgnoreListManager::match: ";
+ // qDebug() << "string: " << str;
+ // qDebug() << "pattern: " << ruleRx.pattern();
+ // qDebug() << "scopeRule: " << item.scopeRule;
+ // qDebug() << "now testing";
if (item.contentsMatcher().match(str)) {
return item.strictness();
}
return UnmatchedStrictness;
}
-
-void IgnoreListManager::removeIgnoreListItem(const QString &ignoreRule)
+void IgnoreListManager::removeIgnoreListItem(const QString& ignoreRule)
{
removeAt(indexOf(ignoreRule));
SYNC(ARG(ignoreRule))
}
-
-void IgnoreListManager::toggleIgnoreRule(const QString &ignoreRule)
+void IgnoreListManager::toggleIgnoreRule(const QString& ignoreRule)
{
int idx = indexOf(ignoreRule);
if (idx == -1)
SYNC(ARG(ignoreRule))
}
-
-bool IgnoreListManager::ctcpMatch(const QString sender, const QString &network, const QString &type)
+bool IgnoreListManager::ctcpMatch(const QString sender, const QString& network, const QString& type)
{
- foreach(IgnoreListItem item, _ignoreList) {
+ foreach (IgnoreListItem item, _ignoreList) {
if (!item.isEnabled())
continue;
- if (item.scope() == GlobalScope
- || (item.scope() == NetworkScope && item.scopeRuleMatcher().match(network))) {
-
+ if (item.scope() == GlobalScope || (item.scope() == NetworkScope && item.scopeRuleMatcher().match(network))) {
// For CTCP ignore rules, use ctcpSender
if (item.senderCTCPMatcher().match(sender)) {
// Sender matches, check types
- if (item.ctcpTypes().isEmpty()
- || item.ctcpTypes().contains(type, Qt::CaseInsensitive)) {
+ if (item.ctcpTypes().isEmpty() || item.ctcpTypes().contains(type, Qt::CaseInsensitive)) {
// Either all types are blocked, or type matches
return true;
}
return false;
}
-
/**************************************************************************
* IgnoreListItem
*************************************************************************/
-bool IgnoreListManager::IgnoreListItem::operator!=(const IgnoreListItem &other) const
+bool IgnoreListManager::IgnoreListItem::operator!=(const IgnoreListItem& other) const
{
- return (_type != other._type ||
- _contents != other._contents ||
- _isRegEx != other._isRegEx ||
- _strictness != other._strictness ||
- _scope != other._scope ||
- _scopeRule != other._scopeRule ||
- _isEnabled != other._isEnabled);
+ return (_type != other._type || _contents != other._contents || _isRegEx != other._isRegEx || _strictness != other._strictness
+ || _scope != other._scope || _scopeRule != other._scopeRule || _isEnabled != other._isEnabled);
// Don't compare ExpressionMatch objects as they are created as needed from the above
}
-
void IgnoreListManager::IgnoreListItem::determineExpressions() const
{
// Don't update if not needed
// Set up matching rules
// Message is either wildcard or regex
- ExpressionMatch::MatchMode contentsMode =
- _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx :
- ExpressionMatch::MatchMode::MatchWildcard;
+ ExpressionMatch::MatchMode contentsMode = _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx : ExpressionMatch::MatchMode::MatchWildcard;
// Ignore rules are always case-insensitive
// Scope matching is always wildcard
}
// Scope rules are always multiple wildcard entries
// (Adding a regex option would be awesome, but requires a backwards-compatible protocol change)
- _scopeRuleMatch = ExpressionMatch(_scopeRule,
- ExpressionMatch::MatchMode::MatchMultiWildcard, false);
+ _scopeRuleMatch = ExpressionMatch(_scopeRule, ExpressionMatch::MatchMode::MatchMultiWildcard, false);
_cacheInvalid = false;
}
#include "common-export.h"
+#include <utility>
+
+#include <QRegExp>
#include <QString>
#include <QStringList>
-#include <QRegExp>
-#include <utility>
#include "expressionmatch.h"
#include "message.h"
SYNCABLE_OBJECT
public:
- inline IgnoreListManager(QObject *parent = nullptr) : SyncableObject(parent) { setAllowClientUpdates(true); }
- IgnoreListManager &operator=(const IgnoreListManager &other);
+ inline IgnoreListManager(QObject* parent = nullptr)
+ : SyncableObject(parent)
+ {
+ setAllowClientUpdates(true);
+ }
+ IgnoreListManager& operator=(const IgnoreListManager& other);
- enum IgnoreType {
+ enum IgnoreType
+ {
SenderIgnore,
MessageIgnore,
CtcpIgnore
};
- enum StrictnessType {
+ enum StrictnessType
+ {
UnmatchedStrictness = 0,
SoftStrictness = 1,
HardStrictness = 2
};
- enum ScopeType {
+ enum ScopeType
+ {
GlobalScope,
NetworkScope,
ChannelScope,
/**
* Individual ignore list rule
*/
- class COMMON_EXPORT IgnoreListItem {
+ class COMMON_EXPORT IgnoreListItem
+ {
public:
/**
* Construct an empty ignore rule
* @param scopeRule String representing a scope rule expression to match
* @param isEnabled True if enabled, otherwise false
*/
- IgnoreListItem(IgnoreType type, QString contents, bool isRegEx,
- StrictnessType strictness, ScopeType scope, QString scopeRule,
- bool isEnabled)
- : _contents(std::move(contents)), _isRegEx(isRegEx), _strictness(strictness),
- _scope(scope), _scopeRule(std::move(scopeRule)), _isEnabled(isEnabled)
+ IgnoreListItem(
+ IgnoreType type, QString contents, bool isRegEx, StrictnessType strictness, ScopeType scope, QString scopeRule, bool isEnabled)
+ : _contents(std::move(contents))
+ , _isRegEx(isRegEx)
+ , _strictness(strictness)
+ , _scope(scope)
+ , _scopeRule(std::move(scopeRule))
+ , _isEnabled(isEnabled)
{
// Allow passing empty "contents" as they can happen when editing an ignore rule
*
* @return IgnoreType of the rule
*/
- inline IgnoreType type() const {
- return _type;
- }
+ inline IgnoreType type() const { return _type; }
/**
* Sets the type of this ignore rule
*
* @param type IgnoreType of the rule
*/
- inline void setType(IgnoreType type) {
+ inline void setType(IgnoreType type)
+ {
// Handle CTCP ignores
if (type == CtcpIgnore) {
// This is not performance-intensive; sticking with QRegExp for Qt 4 is fine
*
* @return String representing a phrase or expression to match
*/
- inline QString contents() const {
- return _contents;
- }
+ inline QString contents() const { return _contents; }
/**
* Sets the message contents this rule matches
*
* @param contents String representing a phrase or expression to match
*/
- inline void setContents(const QString &contents) {
+ inline void setContents(const QString& contents)
+ {
// Allow passing empty "contents" as they can happen when editing an ignore rule
_contents = contents;
_cacheInvalid = true;
*
* @return True if regular expression, otherwise false
*/
- inline bool isRegEx() const {
- return _isRegEx;
- }
+ inline bool isRegEx() const { return _isRegEx; }
/**
* Sets if this rule is a regular expression rule
*
* @param isRegEx True if regular expression, otherwise false
*/
- inline void setIsRegEx(bool isRegEx) {
+ inline void setIsRegEx(bool isRegEx)
+ {
_isRegEx = isRegEx;
_cacheInvalid = true;
}
*
* @return StrictnessType of the rule
*/
- inline StrictnessType strictness() const {
- return _strictness;
- }
+ inline StrictnessType strictness() const { return _strictness; }
/**
* Sets the strictness of this ignore rule
*
* @param strictness StrictnessType of the rule
*/
- inline void setStrictness(StrictnessType strictness) {
- _strictness = strictness;
- }
+ inline void setStrictness(StrictnessType strictness) { _strictness = strictness; }
/**
* Gets what to match scope rule against
*
* @return ScopeType of the rule
*/
- inline ScopeType scope() const {
- return _scope;
- }
+ inline ScopeType scope() const { return _scope; }
/**
* Sets what to match scope rule against
*
* @param type ScopeType of the rule
*/
- inline void setScope(ScopeType scope) {
- _scope = scope;
- }
+ inline void setScope(ScopeType scope) { _scope = scope; }
/**
* Gets the scope rule this rule matches
*
* @return String representing a phrase or expression to match
*/
- inline QString scopeRule() const {
- return _scopeRule;
- }
+ inline QString scopeRule() const { return _scopeRule; }
/**
* Sets the scope rule this rule matches
*
* @param scopeRule String representing a phrase or expression to match
*/
- inline void setScopeRule(const QString &scopeRule) {
+ inline void setScopeRule(const QString& scopeRule)
+ {
_scopeRule = scopeRule;
_cacheInvalid = true;
}
*
* @return True if enabled, otherwise false
*/
- inline bool isEnabled() const {
- return _isEnabled;
- }
+ inline bool isEnabled() const { return _isEnabled; }
/**
* Sets if this rule is enabled and active
*
* @param isEnabled True if enabled, otherwise false
*/
- inline void setIsEnabled(bool isEnabled) {
- _isEnabled = isEnabled;
- }
+ inline void setIsEnabled(bool isEnabled) { _isEnabled = isEnabled; }
/**
* Gets the ignored CTCP types for CTCP ignores
*
* @return List of CTCP types to ignore, or empty for all
*/
- inline QStringList ctcpTypes() const {
- return _cacheCtcpTypes;
- }
+ inline QStringList ctcpTypes() const { return _cacheCtcpTypes; }
/**
* Gets the expression matcher for the message contents, caching if needed
*
* @return Expression matcher to compare with message contents
*/
- inline ExpressionMatch contentsMatcher() const {
+ inline ExpressionMatch contentsMatcher() const
+ {
if (_cacheInvalid) {
determineExpressions();
}
*
* @return Expression matcher to compare with scope
*/
- inline ExpressionMatch scopeRuleMatcher() const {
+ inline ExpressionMatch scopeRuleMatcher() const
+ {
if (_cacheInvalid) {
determineExpressions();
}
*
* @return Expression matcher to compare with message contents
*/
- inline ExpressionMatch senderCTCPMatcher() const {
+ inline ExpressionMatch senderCTCPMatcher() const
+ {
if (_cacheInvalid) {
determineExpressions();
}
return _ctcpSenderMatch;
}
- bool operator!=(const IgnoreListItem &other) const;
+ bool operator!=(const IgnoreListItem& other) const;
private:
/**
QString _scopeRule = {};
bool _isEnabled = true;
- QString _cacheCtcpSender = {}; ///< For CTCP rules, precalculate sender
- QStringList _cacheCtcpTypes = {}; ///< For CTCP rules, precalculate types
+ QString _cacheCtcpSender = {}; ///< For CTCP rules, precalculate sender
+ QStringList _cacheCtcpTypes = {}; ///< For CTCP rules, precalculate types
// These represent internal cache and should be safe to mutate in 'const' functions
// See https://stackoverflow.com/questions/3141087/what-is-meant-with-const-at-end-of-function-declaration
- mutable bool _cacheInvalid = true; ///< If true, match cache needs redone
- mutable ExpressionMatch _contentsMatch = {}; ///< Expression match cache for message
- mutable ExpressionMatch _scopeRuleMatch = {}; ///< Expression match cache for scope rule
- mutable ExpressionMatch _ctcpSenderMatch = {}; ///< Expression match cache for CTCP nick
+ mutable bool _cacheInvalid = true; ///< If true, match cache needs redone
+ mutable ExpressionMatch _contentsMatch = {}; ///< Expression match cache for message
+ mutable ExpressionMatch _scopeRuleMatch = {}; ///< Expression match cache for scope rule
+ mutable ExpressionMatch _ctcpSenderMatch = {}; ///< Expression match cache for CTCP nick
};
using IgnoreList = QList<IgnoreListItem>;
- int indexOf(const QString &ignore) const;
- inline bool contains(const QString &ignore) const { return indexOf(ignore) != -1; }
+ int indexOf(const QString& ignore) const;
+ inline bool contains(const QString& ignore) const { return indexOf(ignore) != -1; }
inline bool isEmpty() const { return _ignoreList.isEmpty(); }
inline int count() const { return _ignoreList.count(); }
inline void removeAt(int index) { _ignoreList.removeAt(index); }
- inline IgnoreListItem &operator[](int i) { return _ignoreList[i]; }
- inline const IgnoreListItem &operator[](int i) const { return _ignoreList.at(i); }
- inline const IgnoreList &ignoreList() const { return _ignoreList; }
+ inline IgnoreListItem& operator[](int i) { return _ignoreList[i]; }
+ inline const IgnoreListItem& operator[](int i) const { return _ignoreList.at(i); }
+ inline const IgnoreList& ignoreList() const { return _ignoreList; }
//! Check if a message matches the IgnoreRule
/** This method checks if a message matches the users ignorelist.
- * \param msg The Message that should be checked
- * \param network The networkname the message belongs to
- * \return UnmatchedStrictness, HardStrictness or SoftStrictness representing the match type
- */
- inline StrictnessType match(const Message &msg, const QString &network = QString()) { return _match(msg.contents(), msg.sender(), msg.type(), network, msg.bufferInfo().bufferName()); }
+ * \param msg The Message that should be checked
+ * \param network The networkname the message belongs to
+ * \return UnmatchedStrictness, HardStrictness or SoftStrictness representing the match type
+ */
+ inline StrictnessType match(const Message& msg, const QString& network = QString())
+ {
+ return _match(msg.contents(), msg.sender(), msg.type(), network, msg.bufferInfo().bufferName());
+ }
- bool ctcpMatch(const QString sender, const QString &network, const QString &type = QString());
+ bool ctcpMatch(const QString sender, const QString& network, const QString& type = QString());
-// virtual void addIgnoreListItem(const IgnoreListItem &item);
+ // virtual void addIgnoreListItem(const IgnoreListItem &item);
public slots:
virtual QVariantMap initIgnoreList() const;
- virtual void initSetIgnoreList(const QVariantMap &ignoreList);
+ virtual void initSetIgnoreList(const QVariantMap& ignoreList);
//! Request removal of an ignore rule based on the rule itself.
/** Use this method if you want to remove a single ignore rule
- * and get that synced with the core immediately.
- * \param ignoreRule A valid ignore rule
- */
- virtual inline void requestRemoveIgnoreListItem(const QString &ignoreRule) { REQUEST(ARG(ignoreRule)) }
- virtual void removeIgnoreListItem(const QString &ignoreRule);
+ * and get that synced with the core immediately.
+ * \param ignoreRule A valid ignore rule
+ */
+ virtual inline void requestRemoveIgnoreListItem(const QString& ignoreRule) { REQUEST(ARG(ignoreRule)) }
+ virtual void removeIgnoreListItem(const QString& ignoreRule);
//! Request toggling of "isActive" flag of a given ignore rule.
/** Use this method if you want to toggle the "isActive" flag of a single ignore rule
- * and get that synced with the core immediately.
- * \param ignoreRule A valid ignore rule
- */
- virtual inline void requestToggleIgnoreRule(const QString &ignoreRule) { REQUEST(ARG(ignoreRule)) }
- virtual void toggleIgnoreRule(const QString &ignoreRule);
+ * and get that synced with the core immediately.
+ * \param ignoreRule A valid ignore rule
+ */
+ virtual inline void requestToggleIgnoreRule(const QString& ignoreRule) { REQUEST(ARG(ignoreRule)) }
+ virtual void toggleIgnoreRule(const QString& ignoreRule);
//! Request an IgnoreListItem to be added to the ignore list
/** Items added to the list with this method, get immediately synced with the core
- * \param type The IgnoreType of the new rule
- * \param ignoreRule The rule itself
- * \param isRegEx Signals if the rule should be interpreted as a regular expression
- * \param strictness Th StrictnessType that should be applied
- * \param scope The ScopeType that should be set
- * \param scopeRule A string of semi-colon separated network- or channelnames
- * \param isActive Signals if the rule is enabled or not
- */
- virtual inline void requestAddIgnoreListItem(int type, const QString &ignoreRule, bool isRegEx, int strictness,
- int scope, const QString &scopeRule, bool isActive)
+ * \param type The IgnoreType of the new rule
+ * \param ignoreRule The rule itself
+ * \param isRegEx Signals if the rule should be interpreted as a regular expression
+ * \param strictness Th StrictnessType that should be applied
+ * \param scope The ScopeType that should be set
+ * \param scopeRule A string of semi-colon separated network- or channelnames
+ * \param isActive Signals if the rule is enabled or not
+ */
+ virtual inline void requestAddIgnoreListItem(
+ int type, const QString& ignoreRule, bool isRegEx, int strictness, int scope, const QString& scopeRule, bool isActive)
{
REQUEST(ARG(type), ARG(ignoreRule), ARG(isRegEx), ARG(strictness), ARG(scope), ARG(scopeRule), ARG(isActive))
}
-
- virtual void addIgnoreListItem(int type, const QString &ignoreRule, bool isRegEx, int strictness,
- int scope, const QString &scopeRule, bool isActive);
+ virtual void addIgnoreListItem(
+ int type, const QString& ignoreRule, bool isRegEx, int strictness, int scope, const QString& scopeRule, bool isActive);
protected:
- void setIgnoreList(const QList<IgnoreListItem> &ignoreList) { _ignoreList = ignoreList; }
+ void setIgnoreList(const QList<IgnoreListItem>& ignoreList) { _ignoreList = ignoreList; }
- StrictnessType _match(const QString &msgContents, const QString &msgSender, Message::Type msgType, const QString &network, const QString &bufferName);
+ StrictnessType _match(
+ const QString& msgContents, const QString& msgSender, Message::Type msgType, const QString& network, const QString& bufferName);
signals:
- void ignoreAdded(IgnoreType type, const QString &ignoreRule, bool isRegex, StrictnessType strictness, ScopeType scope, const QVariant &scopeRule, bool isActive);
+ void ignoreAdded(IgnoreType type,
+ const QString& ignoreRule,
+ bool isRegex,
+ StrictnessType strictness,
+ ScopeType scope,
+ const QVariant& scopeRule,
+ bool isActive);
private:
IgnoreList _ignoreList;
***************************************************************************/
#include "internalpeer.h"
+
#include "util.h"
using namespace Protocol;
-InternalPeer::InternalPeer(QObject *parent)
+InternalPeer::InternalPeer(QObject* parent)
: Peer(nullptr, parent)
{
static bool registered = []() {
setFeatures(Quassel::Features{});
}
-
InternalPeer::~InternalPeer()
{
if (_isOpen) {
}
}
-
QString InternalPeer::description() const
{
return tr("internal connection");
}
-
QString InternalPeer::address() const
{
return tr("internal connection");
}
-
quint16 InternalPeer::port() const
{
return 0;
}
-
bool InternalPeer::isOpen() const
{
return _isOpen;
}
-
bool InternalPeer::isSecure() const
{
return true;
}
-
bool InternalPeer::isLocal() const
{
return true;
}
-
-void InternalPeer::close(const QString &reason)
+void InternalPeer::close(const QString& reason)
{
Q_UNUSED(reason);
_isOpen = false;
}
-
int InternalPeer::lag() const
{
return 0;
}
-
-::SignalProxy *InternalPeer::signalProxy() const
+::SignalProxy* InternalPeer::signalProxy() const
{
return _proxy;
}
-
-void InternalPeer::setSignalProxy(::SignalProxy *proxy)
+void InternalPeer::setSignalProxy(::SignalProxy* proxy)
{
if (!proxy && _proxy) {
_proxy = nullptr;
qWarning() << Q_FUNC_INFO << "Changing the SignalProxy is not supported!";
}
-
-void InternalPeer::setPeer(InternalPeer *peer)
-{
- connect(peer, selectOverload<const Protocol::SyncMessage&>(&InternalPeer::dispatchMessage),
- this, selectOverload<const Protocol::SyncMessage&>(&InternalPeer::handleMessage));
- connect(peer, selectOverload<const Protocol::RpcCall&>(&InternalPeer::dispatchMessage),
- this, selectOverload<const Protocol::RpcCall&>(&InternalPeer::handleMessage));
- connect(peer, selectOverload<const Protocol::InitRequest&>(&InternalPeer::dispatchMessage),
- this, selectOverload<const Protocol::InitRequest&>(&InternalPeer::handleMessage));
- connect(peer, selectOverload<const Protocol::InitData&>(&InternalPeer::dispatchMessage),
- this, selectOverload<const Protocol::InitData&>(&InternalPeer::handleMessage));
+void InternalPeer::setPeer(InternalPeer* peer)
+{
+ connect(peer,
+ selectOverload<const Protocol::SyncMessage&>(&InternalPeer::dispatchMessage),
+ this,
+ selectOverload<const Protocol::SyncMessage&>(&InternalPeer::handleMessage));
+ connect(peer,
+ selectOverload<const Protocol::RpcCall&>(&InternalPeer::dispatchMessage),
+ this,
+ selectOverload<const Protocol::RpcCall&>(&InternalPeer::handleMessage));
+ connect(peer,
+ selectOverload<const Protocol::InitRequest&>(&InternalPeer::dispatchMessage),
+ this,
+ selectOverload<const Protocol::InitRequest&>(&InternalPeer::handleMessage));
+ connect(peer,
+ selectOverload<const Protocol::InitData&>(&InternalPeer::dispatchMessage),
+ this,
+ selectOverload<const Protocol::InitData&>(&InternalPeer::handleMessage));
connect(peer, &Peer::disconnected, this, &InternalPeer::peerDisconnected);
_isOpen = true;
}
-
void InternalPeer::peerDisconnected()
{
disconnect(sender(), nullptr, this, nullptr);
}
}
-
-void InternalPeer::dispatch(const SyncMessage &msg)
+void InternalPeer::dispatch(const SyncMessage& msg)
{
emit dispatchMessage(msg);
}
-
-void InternalPeer::dispatch(const RpcCall &msg)
+void InternalPeer::dispatch(const RpcCall& msg)
{
emit dispatchMessage(msg);
}
-
-void InternalPeer::dispatch(const InitRequest &msg)
+void InternalPeer::dispatch(const InitRequest& msg)
{
emit dispatchMessage(msg);
}
-
-void InternalPeer::dispatch(const InitData &msg)
+void InternalPeer::dispatch(const InitData& msg)
{
emit dispatchMessage(msg);
}
-
-void InternalPeer::handleMessage(const Protocol::SyncMessage &msg)
+void InternalPeer::handleMessage(const Protocol::SyncMessage& msg)
{
handle(msg);
}
-
-void InternalPeer::handleMessage(const Protocol::RpcCall &msg)
+void InternalPeer::handleMessage(const Protocol::RpcCall& msg)
{
handle(msg);
}
-
-void InternalPeer::handleMessage(const Protocol::InitRequest &msg)
+void InternalPeer::handleMessage(const Protocol::InitRequest& msg)
{
handle(msg);
}
-
-void InternalPeer::handleMessage(const Protocol::InitData &msg)
+void InternalPeer::handleMessage(const Protocol::InitData& msg)
{
handle(msg);
}
-
template<class T>
-void InternalPeer::handle(const T &msg)
+void InternalPeer::handle(const T& msg)
{
- static auto setSourcePeer = [](Peer *peer) {
+ static auto setSourcePeer = [](Peer* peer) {
auto p = SignalProxy::current();
if (p) {
p->setSourcePeer(peer);
Q_OBJECT
public:
- InternalPeer(QObject *parent = nullptr);
+ InternalPeer(QObject* parent = nullptr);
~InternalPeer() override;
Protocol::Type protocol() const override { return Protocol::InternalProtocol; }
QString address() const override;
quint16 port() const override;
- SignalProxy *signalProxy() const override;
- void setSignalProxy(SignalProxy *proxy) override;
+ SignalProxy* signalProxy() const override;
+ void setSignalProxy(SignalProxy* proxy) override;
- InternalPeer *peer() const;
- void setPeer(InternalPeer *peer);
+ InternalPeer* peer() const;
+ void setPeer(InternalPeer* peer);
bool isOpen() const override;
bool isSecure() const override;
int lag() const override;
- void dispatch(const Protocol::SyncMessage &msg) override;
- void dispatch(const Protocol::RpcCall &msg) override;
- void dispatch(const Protocol::InitRequest &msg) override;
- void dispatch(const Protocol::InitData &msg) override;
+ void dispatch(const Protocol::SyncMessage& msg) override;
+ void dispatch(const Protocol::RpcCall& msg) override;
+ void dispatch(const Protocol::InitRequest& msg) override;
+ void dispatch(const Protocol::InitData& msg) override;
/* These are not needed for InternalPeer */
- void dispatch(const Protocol::RegisterClient &) override {}
- void dispatch(const Protocol::ClientDenied &) override {}
- void dispatch(const Protocol::ClientRegistered &) override {}
- void dispatch(const Protocol::SetupData &) override {}
- void dispatch(const Protocol::SetupFailed &) override {}
- void dispatch(const Protocol::SetupDone &) override {}
- void dispatch(const Protocol::Login &) override {}
- void dispatch(const Protocol::LoginFailed &) override {}
- void dispatch(const Protocol::LoginSuccess &) override {}
- void dispatch(const Protocol::SessionState &) override {}
+ void dispatch(const Protocol::RegisterClient&) override {}
+ void dispatch(const Protocol::ClientDenied&) override {}
+ void dispatch(const Protocol::ClientRegistered&) override {}
+ void dispatch(const Protocol::SetupData&) override {}
+ void dispatch(const Protocol::SetupFailed&) override {}
+ void dispatch(const Protocol::SetupDone&) override {}
+ void dispatch(const Protocol::Login&) override {}
+ void dispatch(const Protocol::LoginFailed&) override {}
+ void dispatch(const Protocol::LoginSuccess&) override {}
+ void dispatch(const Protocol::SessionState&) override {}
public slots:
- void close(const QString &reason = QString()) override;
+ void close(const QString& reason = QString()) override;
signals:
- void dispatchMessage(const Protocol::SyncMessage &msg);
- void dispatchMessage(const Protocol::RpcCall &msg);
- void dispatchMessage(const Protocol::InitRequest &msg);
- void dispatchMessage(const Protocol::InitData &msg);
+ void dispatchMessage(const Protocol::SyncMessage& msg);
+ void dispatchMessage(const Protocol::RpcCall& msg);
+ void dispatchMessage(const Protocol::InitRequest& msg);
+ void dispatchMessage(const Protocol::InitData& msg);
private slots:
void peerDisconnected();
- void handleMessage(const Protocol::SyncMessage &msg);
- void handleMessage(const Protocol::RpcCall &msg);
- void handleMessage(const Protocol::InitRequest &msg);
- void handleMessage(const Protocol::InitData &msg);
+ void handleMessage(const Protocol::SyncMessage& msg);
+ void handleMessage(const Protocol::RpcCall& msg);
+ void handleMessage(const Protocol::InitRequest& msg);
+ void handleMessage(const Protocol::InitData& msg);
private:
template<typename T>
- void handle(const T &msg);
+ void handle(const T& msg);
private:
- SignalProxy *_proxy{nullptr};
+ SignalProxy* _proxy{nullptr};
bool _isOpen{true};
};
*/
namespace IrcCap {
- // NOTE: If you add or modify the constants below, update the knownCaps list.
-
- /**
- * Account change notification.
- *
- * http://ircv3.net/specs/extensions/account-notify-3.1.html
- */
- const QString ACCOUNT_NOTIFY = "account-notify";
-
- /**
- * Magic number for WHOX, used to ignore user-requested WHOX replies from servers
- *
- * If a user initiates a WHOX, there's no easy way to tell what fields were requested. It's
- * simpler to not attempt to parse data from user-requested WHOX replies.
- */
- const uint ACCOUNT_NOTIFY_WHOX_NUM = 369;
-
- /**
- * Away change notification.
- *
- * http://ircv3.net/specs/extensions/away-notify-3.1.html
- */
- const QString AWAY_NOTIFY = "away-notify";
-
- /**
- * Capability added/removed notification.
- *
- * This is implicitly enabled via CAP LS 302, and is here for servers that only partially
- * support IRCv3.2.
- *
- * http://ircv3.net/specs/extensions/cap-notify-3.2.html
- */
- const QString CAP_NOTIFY = "cap-notify";
-
- /**
- * Hostname/user changed notification.
- *
- * http://ircv3.net/specs/extensions/chghost-3.2.html
- */
- const QString CHGHOST = "chghost";
-
- /**
- * Extended join information.
- *
- * http://ircv3.net/specs/extensions/extended-join-3.1.html
- */
- const QString EXTENDED_JOIN = "extended-join";
-
- /**
- * Multiple mode prefixes in MODE and WHO replies.
- *
- * http://ircv3.net/specs/extensions/multi-prefix-3.1.html
- */
- const QString MULTI_PREFIX = "multi-prefix";
-
- /**
- * SASL authentication.
- *
- * http://ircv3.net/specs/extensions/sasl-3.2.html
- */
- const QString SASL = "sasl";
-
- /**
- * Userhost in names replies.
- *
- * http://ircv3.net/specs/extensions/userhost-in-names-3.2.html
- */
- const QString USERHOST_IN_NAMES = "userhost-in-names";
-
- /**
- * Vendor-specific capabilities
- */
- namespace Vendor {
-
- /**
- * Twitch.tv membership message support
- *
- * User list in a channel can be quite large and often non required for bot users and is then optional.
- *
- * From Twitch.tv documentation:
- * "Adds membership state event data. By default, we do not send this data to clients without this capability."
- *
- * https://dev.twitch.tv/docs/v5/guides/irc/#twitch-irc-capability-membership
- */
- const QString TWITCH_MEMBERSHIP = "twitch.tv/membership";
-
- /**
- * Self message support, as recognized by ZNC.
- *
- * Some servers (e.g. Bitlbee) assume self-message support; ZNC requires a capability
- * instead. As self-message is already implemented, there's little reason to not do this.
- *
- * More information in the IRCv3 commit that removed the 'self-message' capability.
- *
- * https://github.com/ircv3/ircv3-specifications/commit/1bfba47843c2526707c902034b3395af934713c8
- */
- const QString ZNC_SELF_MESSAGE = "znc.in/self-message";
- }
-
- /**
- * List of capabilities currently implemented and requested during capability negotiation.
- */
- const QStringList knownCaps = QStringList {
- ACCOUNT_NOTIFY,
- AWAY_NOTIFY,
- CAP_NOTIFY,
- CHGHOST,
- EXTENDED_JOIN,
- MULTI_PREFIX,
- SASL,
- USERHOST_IN_NAMES,
- Vendor::TWITCH_MEMBERSHIP,
- Vendor::ZNC_SELF_MESSAGE
- };
- // NOTE: If you modify the knownCaps list, update the constants above as needed.
-
- /**
- * SASL authentication mechanisms
- *
- * http://ircv3.net/specs/extensions/sasl-3.1.html
- */
- namespace SaslMech {
- /**
- * PLAIN authentication, e.g. hashed password
- */
- const QString PLAIN = "PLAIN";
-
- /**
- * EXTERNAL authentication, e.g. SSL certificate and keys
- */
- const QString EXTERNAL = "EXTERNAL";
- }
-}
-
-#endif // IRCCAP_H
+// NOTE: If you add or modify the constants below, update the knownCaps list.
+
+/**
+ * Account change notification.
+ *
+ * http://ircv3.net/specs/extensions/account-notify-3.1.html
+ */
+const QString ACCOUNT_NOTIFY = "account-notify";
+
+/**
+ * Magic number for WHOX, used to ignore user-requested WHOX replies from servers
+ *
+ * If a user initiates a WHOX, there's no easy way to tell what fields were requested. It's
+ * simpler to not attempt to parse data from user-requested WHOX replies.
+ */
+const uint ACCOUNT_NOTIFY_WHOX_NUM = 369;
+
+/**
+ * Away change notification.
+ *
+ * http://ircv3.net/specs/extensions/away-notify-3.1.html
+ */
+const QString AWAY_NOTIFY = "away-notify";
+
+/**
+ * Capability added/removed notification.
+ *
+ * This is implicitly enabled via CAP LS 302, and is here for servers that only partially
+ * support IRCv3.2.
+ *
+ * http://ircv3.net/specs/extensions/cap-notify-3.2.html
+ */
+const QString CAP_NOTIFY = "cap-notify";
+
+/**
+ * Hostname/user changed notification.
+ *
+ * http://ircv3.net/specs/extensions/chghost-3.2.html
+ */
+const QString CHGHOST = "chghost";
+
+/**
+ * Extended join information.
+ *
+ * http://ircv3.net/specs/extensions/extended-join-3.1.html
+ */
+const QString EXTENDED_JOIN = "extended-join";
+
+/**
+ * Multiple mode prefixes in MODE and WHO replies.
+ *
+ * http://ircv3.net/specs/extensions/multi-prefix-3.1.html
+ */
+const QString MULTI_PREFIX = "multi-prefix";
+
+/**
+ * SASL authentication.
+ *
+ * http://ircv3.net/specs/extensions/sasl-3.2.html
+ */
+const QString SASL = "sasl";
+
+/**
+ * Userhost in names replies.
+ *
+ * http://ircv3.net/specs/extensions/userhost-in-names-3.2.html
+ */
+const QString USERHOST_IN_NAMES = "userhost-in-names";
+
+/**
+ * Vendor-specific capabilities
+ */
+namespace Vendor {
+
+/**
+ * Twitch.tv membership message support
+ *
+ * User list in a channel can be quite large and often non required for bot users and is then optional.
+ *
+ * From Twitch.tv documentation:
+ * "Adds membership state event data. By default, we do not send this data to clients without this capability."
+ *
+ * https://dev.twitch.tv/docs/v5/guides/irc/#twitch-irc-capability-membership
+ */
+const QString TWITCH_MEMBERSHIP = "twitch.tv/membership";
+
+/**
+ * Self message support, as recognized by ZNC.
+ *
+ * Some servers (e.g. Bitlbee) assume self-message support; ZNC requires a capability
+ * instead. As self-message is already implemented, there's little reason to not do this.
+ *
+ * More information in the IRCv3 commit that removed the 'self-message' capability.
+ *
+ * https://github.com/ircv3/ircv3-specifications/commit/1bfba47843c2526707c902034b3395af934713c8
+ */
+const QString ZNC_SELF_MESSAGE = "znc.in/self-message";
+} // namespace Vendor
+
+/**
+ * List of capabilities currently implemented and requested during capability negotiation.
+ */
+const QStringList knownCaps = QStringList{ACCOUNT_NOTIFY,
+ AWAY_NOTIFY,
+ CAP_NOTIFY,
+ CHGHOST,
+ EXTENDED_JOIN,
+ MULTI_PREFIX,
+ SASL,
+ USERHOST_IN_NAMES,
+ Vendor::TWITCH_MEMBERSHIP,
+ Vendor::ZNC_SELF_MESSAGE};
+// NOTE: If you modify the knownCaps list, update the constants above as needed.
+
+/**
+ * SASL authentication mechanisms
+ *
+ * http://ircv3.net/specs/extensions/sasl-3.1.html
+ */
+namespace SaslMech {
+/**
+ * PLAIN authentication, e.g. hashed password
+ */
+const QString PLAIN = "PLAIN";
+
+/**
+ * EXTERNAL authentication, e.g. SSL certificate and keys
+ */
+const QString EXTERNAL = "EXTERNAL";
+} // namespace SaslMech
+} // namespace IrcCap
+
+#endif // IRCCAP_H
#include "ircchannel.h"
-#include "network.h"
-#include "ircuser.h"
-#include "util.h"
-
-#include <QMapIterator>
+#include <QDebug>
#include <QHashIterator>
+#include <QMapIterator>
#include <QTextCodec>
-#include <QDebug>
+#include "ircuser.h"
+#include "network.h"
+#include "util.h"
-IrcChannel::IrcChannel(const QString &channelname, Network *network)
- : SyncableObject(network),
- _initialized(false),
- _name(channelname),
- _topic(QString()),
- _encrypted(false),
- _network(network),
- _codecForEncoding(nullptr),
- _codecForDecoding(nullptr)
+IrcChannel::IrcChannel(const QString& channelname, Network* network)
+ : SyncableObject(network)
+ , _initialized(false)
+ , _name(channelname)
+ , _topic(QString())
+ , _encrypted(false)
+ , _network(network)
+ , _codecForEncoding(nullptr)
+ , _codecForDecoding(nullptr)
{
- setObjectName(QString::number(network->networkId().toInt()) + "/" + channelname);
+ setObjectName(QString::number(network->networkId().toInt()) + "/" + channelname);
}
-
// ====================
// PUBLIC:
// ====================
-bool IrcChannel::isKnownUser(IrcUser *ircuser) const
+bool IrcChannel::isKnownUser(IrcUser* ircuser) const
{
if (ircuser == nullptr) {
qWarning() << "Channel" << name() << "received IrcUser Nullpointer!";
return true;
}
-
-bool IrcChannel::isValidChannelUserMode(const QString &mode) const
+bool IrcChannel::isValidChannelUserMode(const QString& mode) const
{
bool isvalid = true;
if (mode.size() > 1) {
return isvalid;
}
-
-QString IrcChannel::userModes(IrcUser *ircuser) const
+QString IrcChannel::userModes(IrcUser* ircuser) const
{
if (_userModes.contains(ircuser))
return _userModes[ircuser];
return QString();
}
-
-QString IrcChannel::userModes(const QString &nick) const
+QString IrcChannel::userModes(const QString& nick) const
{
return userModes(network()->ircUser(nick));
}
-
-void IrcChannel::setCodecForEncoding(const QString &name)
+void IrcChannel::setCodecForEncoding(const QString& name)
{
setCodecForEncoding(QTextCodec::codecForName(name.toLatin1()));
}
-
-void IrcChannel::setCodecForEncoding(QTextCodec *codec)
+void IrcChannel::setCodecForEncoding(QTextCodec* codec)
{
_codecForEncoding = codec;
}
-
-void IrcChannel::setCodecForDecoding(const QString &name)
+void IrcChannel::setCodecForDecoding(const QString& name)
{
setCodecForDecoding(QTextCodec::codecForName(name.toLatin1()));
}
-
-void IrcChannel::setCodecForDecoding(QTextCodec *codec)
+void IrcChannel::setCodecForDecoding(QTextCodec* codec)
{
_codecForDecoding = codec;
}
-
-QString IrcChannel::decodeString(const QByteArray &text) const
+QString IrcChannel::decodeString(const QByteArray& text) const
{
- if (!codecForDecoding()) return network()->decodeString(text);
+ if (!codecForDecoding())
+ return network()->decodeString(text);
return ::decodeString(text, _codecForDecoding);
}
-
-QByteArray IrcChannel::encodeString(const QString &string) const
+QByteArray IrcChannel::encodeString(const QString& string) const
{
if (codecForEncoding()) {
return _codecForEncoding->fromUnicode(string);
return network()->encodeString(string);
}
-
// ====================
// PUBLIC SLOTS:
// ====================
-void IrcChannel::setTopic(const QString &topic)
+void IrcChannel::setTopic(const QString& topic)
{
_topic = topic;
SYNC(ARG(topic))
emit topicSet(topic);
}
-
-void IrcChannel::setPassword(const QString &password)
+void IrcChannel::setPassword(const QString& password)
{
_password = password;
SYNC(ARG(password))
emit encryptedSet(encrypted);
}
-
-void IrcChannel::joinIrcUsers(const QList<IrcUser *> &users, const QStringList &modes)
+void IrcChannel::joinIrcUsers(const QList<IrcUser*>& users, const QStringList& modes)
{
if (users.isEmpty())
return;
QStringList newNicks;
QStringList newModes;
- QList<IrcUser *> newUsers;
+ QList<IrcUser*> newUsers;
- IrcUser *ircuser;
+ IrcUser* ircuser;
for (int i = 0; i < users.count(); i++) {
ircuser = users[i];
if (!ircuser)
for (int i_m = 0; i_m < sortedModes[i].count(); ++i_m) {
addUserMode(ircuser, sortedModes[i][i_m]);
}
- } else {
+ }
+ else {
addUserMode(ircuser, sortedModes[i]);
}
continue;
emit ircUsersJoined(newUsers);
}
-
-void IrcChannel::joinIrcUsers(const QStringList &nicks, const QStringList &modes)
+void IrcChannel::joinIrcUsers(const QStringList& nicks, const QStringList& modes)
{
- QList<IrcUser *> users;
- foreach(QString nick, nicks)
- users << network()->newIrcUser(nick);
+ QList<IrcUser*> users;
+ foreach (QString nick, nicks)
+ users << network()->newIrcUser(nick);
joinIrcUsers(users, modes);
}
-
-void IrcChannel::joinIrcUser(IrcUser *ircuser)
+void IrcChannel::joinIrcUser(IrcUser* ircuser)
{
- QList<IrcUser *> users;
+ QList<IrcUser*> users;
users << ircuser;
QStringList modes;
modes << QString();
joinIrcUsers(users, modes);
}
-
-void IrcChannel::part(IrcUser *ircuser)
+void IrcChannel::part(IrcUser* ircuser)
{
if (isKnownUser(ircuser)) {
_userModes.remove(ircuser);
if (network()->isMe(ircuser) || _userModes.isEmpty()) {
// in either case we're no longer in the channel
// -> clean up the channel and destroy it
- QList<IrcUser *> users = _userModes.keys();
+ QList<IrcUser*> users = _userModes.keys();
_userModes.clear();
- foreach(IrcUser *user, users) {
+ foreach (IrcUser* user, users) {
disconnect(user, nullptr, this, nullptr);
user->partChannel(this);
}
}
}
-
-void IrcChannel::part(const QString &nick)
+void IrcChannel::part(const QString& nick)
{
part(network()->ircUser(nick));
}
-
// SET USER MODE
-void IrcChannel::setUserModes(IrcUser *ircuser, const QString &modes)
+void IrcChannel::setUserModes(IrcUser* ircuser, const QString& modes)
{
if (isKnownUser(ircuser)) {
// Keep user modes sorted
}
}
-
-void IrcChannel::setUserModes(const QString &nick, const QString &modes)
+void IrcChannel::setUserModes(const QString& nick, const QString& modes)
{
setUserModes(network()->ircUser(nick), modes);
}
-
// ADD USER MODE
-void IrcChannel::addUserMode(IrcUser *ircuser, const QString &mode)
+void IrcChannel::addUserMode(IrcUser* ircuser, const QString& mode)
{
if (!isKnownUser(ircuser) || !isValidChannelUserMode(mode))
return;
}
}
-
-void IrcChannel::addUserMode(const QString &nick, const QString &mode)
+void IrcChannel::addUserMode(const QString& nick, const QString& mode)
{
addUserMode(network()->ircUser(nick), mode);
}
-
// REMOVE USER MODE
-void IrcChannel::removeUserMode(IrcUser *ircuser, const QString &mode)
+void IrcChannel::removeUserMode(IrcUser* ircuser, const QString& mode)
{
if (!isKnownUser(ircuser) || !isValidChannelUserMode(mode))
return;
}
}
-
-void IrcChannel::removeUserMode(const QString &nick, const QString &mode)
+void IrcChannel::removeUserMode(const QString& nick, const QString& mode)
{
removeUserMode(network()->ircUser(nick), mode);
}
-
// INIT SET USER MODES
QVariantMap IrcChannel::initUserModes() const
{
QVariantMap usermodes;
- QHash<IrcUser *, QString>::const_iterator iter = _userModes.constBegin();
+ QHash<IrcUser*, QString>::const_iterator iter = _userModes.constBegin();
while (iter != _userModes.constEnd()) {
usermodes[iter.key()->nick()] = iter.value();
++iter;
return usermodes;
}
-
-void IrcChannel::initSetUserModes(const QVariantMap &usermodes)
+void IrcChannel::initSetUserModes(const QVariantMap& usermodes)
{
- QList<IrcUser *> users;
+ QList<IrcUser*> users;
QStringList modes;
QVariantMap::const_iterator iter = usermodes.constBegin();
while (iter != usermodes.constEnd()) {
joinIrcUsers(users, modes);
}
-
QVariantMap IrcChannel::initChanModes() const
{
QVariantMap channelModes;
return channelModes;
}
-
-void IrcChannel::initSetChanModes(const QVariantMap &channelModes)
+void IrcChannel::initSetChanModes(const QVariantMap& channelModes)
{
QVariantMap::const_iterator iter = channelModes["A"].toMap().constBegin();
QVariantMap::const_iterator iterEnd = channelModes["A"].toMap().constEnd();
}
}
-
void IrcChannel::ircUserDestroyed()
{
- auto *ircUser = static_cast<IrcUser *>(sender());
+ auto* ircUser = static_cast<IrcUser*>(sender());
Q_ASSERT(ircUser);
_userModes.remove(ircUser);
// no further propagation.
// this leads only to fuck ups.
}
-
void IrcChannel::ircUserNickSet(QString nick)
{
- auto *ircUser = qobject_cast<IrcUser *>(sender());
+ auto* ircUser = qobject_cast<IrcUser*>(sender());
Q_ASSERT(ircUser);
emit ircUserNickSet(ircUser, nick);
}
-
/*******************************************************************************
*
* 3.3 CHANMODES
// NOTE: the behavior of addChannelMode and removeChannelMode depends on the type of mode
// see list above for chanmode types
-void IrcChannel::addChannelMode(const QChar &mode, const QString &value)
+void IrcChannel::addChannelMode(const QChar& mode, const QString& value)
{
Network::ChannelModeType modeType = network()->channelModeType(mode);
SYNC(ARG(mode), ARG(value))
}
-
-void IrcChannel::removeChannelMode(const QChar &mode, const QString &value)
+void IrcChannel::removeChannelMode(const QChar& mode, const QString& value)
{
Network::ChannelModeType modeType = network()->channelModeType(mode);
SYNC(ARG(mode), ARG(value))
}
-
-bool IrcChannel::hasMode(const QChar &mode) const
+bool IrcChannel::hasMode(const QChar& mode) const
{
Network::ChannelModeType modeType = network()->channelModeType(mode);
return false;
}
-
-QString IrcChannel::modeValue(const QChar &mode) const
+QString IrcChannel::modeValue(const QChar& mode) const
{
Network::ChannelModeType modeType = network()->channelModeType(mode);
}
}
-
-QStringList IrcChannel::modeValueList(const QChar &mode) const
+QStringList IrcChannel::modeValueList(const QChar& mode) const
{
Network::ChannelModeType modeType = network()->channelModeType(mode);
return {};
}
-
QString IrcChannel::channelModeString() const
{
QStringList params;
Q_PROPERTY(QString password READ password WRITE setPassword)
Q_PROPERTY(bool encrypted READ encrypted WRITE setEncrypted)
-public :
- IrcChannel(const QString &channelname, Network *network);
+public:
+ IrcChannel(const QString& channelname, Network* network);
- bool isKnownUser(IrcUser *ircuser) const;
- bool isValidChannelUserMode(const QString &mode) const;
+ bool isKnownUser(IrcUser* ircuser) const;
+ bool isValidChannelUserMode(const QString& mode) const;
inline QString name() const { return _name; }
inline QString topic() const { return _topic; }
inline QString password() const { return _password; }
inline bool encrypted() const { return _encrypted; }
- inline Network *network() const { return _network; }
+ inline Network* network() const { return _network; }
- inline QList<IrcUser *> ircUsers() const { return _userModes.keys(); }
+ inline QList<IrcUser*> ircUsers() const { return _userModes.keys(); }
- QString userModes(IrcUser *ircuser) const;
- QString userModes(const QString &nick) const;
+ QString userModes(IrcUser* ircuser) const;
+ QString userModes(const QString& nick) const;
- bool hasMode(const QChar &mode) const;
- QString modeValue(const QChar &mode) const;
- QStringList modeValueList(const QChar &mode) const;
+ bool hasMode(const QChar& mode) const;
+ QString modeValue(const QChar& mode) const;
+ QStringList modeValueList(const QChar& mode) const;
QString channelModeString() const;
- inline QTextCodec *codecForEncoding() const { return _codecForEncoding; }
- inline QTextCodec *codecForDecoding() const { return _codecForDecoding; }
- void setCodecForEncoding(const QString &codecName);
- void setCodecForEncoding(QTextCodec *codec);
- void setCodecForDecoding(const QString &codecName);
- void setCodecForDecoding(QTextCodec *codec);
+ inline QTextCodec* codecForEncoding() const { return _codecForEncoding; }
+ inline QTextCodec* codecForDecoding() const { return _codecForDecoding; }
+ void setCodecForEncoding(const QString& codecName);
+ void setCodecForEncoding(QTextCodec* codec);
+ void setCodecForDecoding(const QString& codecName);
+ void setCodecForDecoding(QTextCodec* codec);
- QString decodeString(const QByteArray &text) const;
- QByteArray encodeString(const QString &string) const;
+ QString decodeString(const QByteArray& text) const;
+ QByteArray encodeString(const QString& string) const;
public slots:
- void setTopic(const QString &topic);
- void setPassword(const QString &password);
+ void setTopic(const QString& topic);
+ void setPassword(const QString& password);
void setEncrypted(bool encrypted);
- void joinIrcUsers(const QList<IrcUser *> &users, const QStringList &modes);
- void joinIrcUsers(const QStringList &nicks, const QStringList &modes);
- void joinIrcUser(IrcUser *ircuser);
+ void joinIrcUsers(const QList<IrcUser*>& users, const QStringList& modes);
+ void joinIrcUsers(const QStringList& nicks, const QStringList& modes);
+ void joinIrcUser(IrcUser* ircuser);
- void part(IrcUser *ircuser);
- void part(const QString &nick);
+ void part(IrcUser* ircuser);
+ void part(const QString& nick);
- void setUserModes(IrcUser *ircuser, const QString &modes);
- void setUserModes(const QString &nick, const QString &modes);
+ void setUserModes(IrcUser* ircuser, const QString& modes);
+ void setUserModes(const QString& nick, const QString& modes);
- void addUserMode(IrcUser *ircuser, const QString &mode);
- void addUserMode(const QString &nick, const QString &mode);
+ void addUserMode(IrcUser* ircuser, const QString& mode);
+ void addUserMode(const QString& nick, const QString& mode);
- void removeUserMode(IrcUser *ircuser, const QString &mode);
- void removeUserMode(const QString &nick, const QString &mode);
+ void removeUserMode(IrcUser* ircuser, const QString& mode);
+ void removeUserMode(const QString& nick, const QString& mode);
- void addChannelMode(const QChar &mode, const QString &value);
- void removeChannelMode(const QChar &mode, const QString &value);
+ void addChannelMode(const QChar& mode, const QString& value);
+ void removeChannelMode(const QChar& mode, const QString& value);
// init geters
QVariantMap initUserModes() const;
QVariantMap initChanModes() const;
// init seters
- void initSetUserModes(const QVariantMap &usermodes);
- void initSetChanModes(const QVariantMap &chanModes);
+ void initSetUserModes(const QVariantMap& usermodes);
+ void initSetChanModes(const QVariantMap& chanModes);
signals:
- void topicSet(const QString &topic); // needed by NetworkModel
+ void topicSet(const QString& topic); // needed by NetworkModel
void encryptedSet(bool encrypted);
-// void passwordSet(const QString &password);
-// void userModesSet(QString nick, QString modes);
-// void userModeAdded(QString nick, QString mode);
-// void userModeRemoved(QString nick, QString mode);
-// void channelModeAdded(const QChar &mode, const QString &value);
-// void channelModeRemoved(const QChar &mode, const QString &value);
-
- void ircUsersJoined(const QList<IrcUser *> &ircusers);
-// void ircUsersJoined(QStringList nicks, QStringList modes);
- void ircUserParted(IrcUser *ircuser);
- void ircUserNickSet(IrcUser *ircuser, QString nick);
- void ircUserModeAdded(IrcUser *ircuser, QString mode);
- void ircUserModeRemoved(IrcUser *ircuser, QString mode);
- void ircUserModesSet(IrcUser *ircuser, QString modes);
-
- void parted(); // convenience signal emitted before channels destruction
+ // void passwordSet(const QString &password);
+ // void userModesSet(QString nick, QString modes);
+ // void userModeAdded(QString nick, QString mode);
+ // void userModeRemoved(QString nick, QString mode);
+ // void channelModeAdded(const QChar &mode, const QString &value);
+ // void channelModeRemoved(const QChar &mode, const QString &value);
+
+ void ircUsersJoined(const QList<IrcUser*>& ircusers);
+ // void ircUsersJoined(QStringList nicks, QStringList modes);
+ void ircUserParted(IrcUser* ircuser);
+ void ircUserNickSet(IrcUser* ircuser, QString nick);
+ void ircUserModeAdded(IrcUser* ircuser, QString mode);
+ void ircUserModeRemoved(IrcUser* ircuser, QString mode);
+ void ircUserModesSet(IrcUser* ircuser, QString modes);
+
+ void parted(); // convenience signal emitted before channels destruction
private slots:
void ircUserDestroyed();
QString _password;
bool _encrypted;
- QHash<IrcUser *, QString> _userModes;
+ QHash<IrcUser*, QString> _userModes;
- Network *_network;
+ Network* _network;
- QTextCodec *_codecForEncoding;
- QTextCodec *_codecForDecoding;
+ QTextCodec* _codecForEncoding;
+ QTextCodec* _codecForDecoding;
QHash<QChar, QStringList> _A_channelModes;
QHash<QChar, QString> _B_channelModes;
#include "ircevent.h"
-Event *IrcEvent::create(EventManager::EventType type, QVariantMap &map, Network *network)
+Event* IrcEvent::create(EventManager::EventType type, QVariantMap& map, Network* network)
{
if ((type & ~EventManager::IrcEventNumericMask) == EventManager::IrcEventNumeric)
return new IrcEventNumeric(type, map, network);
}
}
-
-IrcEvent::IrcEvent(EventManager::EventType type, QVariantMap &map, Network *network)
+IrcEvent::IrcEvent(EventManager::EventType type, QVariantMap& map, Network* network)
: NetworkEvent(type, map, network)
{
_prefix = map.take("prefix").toString();
_params = map.take("params").toStringList();
}
-
-void IrcEvent::toVariantMap(QVariantMap &map) const
+void IrcEvent::toVariantMap(QVariantMap& map) const
{
NetworkEvent::toVariantMap(map);
map["prefix"] = prefix();
map["params"] = params();
}
-
-IrcEventNumeric::IrcEventNumeric(EventManager::EventType type, QVariantMap &map, Network *network)
+IrcEventNumeric::IrcEventNumeric(EventManager::EventType type, QVariantMap& map, Network* network)
: IrcEvent(type, map, network)
{
_number = map.take("number").toUInt();
_target = map.take("target").toString();
}
-
-void IrcEventNumeric::toVariantMap(QVariantMap &map) const
+void IrcEventNumeric::toVariantMap(QVariantMap& map) const
{
IrcEvent::toVariantMap(map);
map["number"] = number();
map["target"] = target();
}
-
-IrcEventRawMessage::IrcEventRawMessage(EventManager::EventType type, QVariantMap &map, Network *network)
+IrcEventRawMessage::IrcEventRawMessage(EventManager::EventType type, QVariantMap& map, Network* network)
: IrcEvent(type, map, network)
{
_rawMessage = map.take("rawMessage").toByteArray();
}
-
-void IrcEventRawMessage::toVariantMap(QVariantMap &map) const
+void IrcEventRawMessage::toVariantMap(QVariantMap& map) const
{
IrcEvent::toVariantMap(map);
map["rawMessage"] = rawMessage();
#pragma once
-#include <utility>
-
#include "common-export.h"
+#include <utility>
+
#include "networkevent.h"
#include "util.h"
class COMMON_EXPORT IrcEvent : public NetworkEvent
{
public:
- explicit IrcEvent(EventManager::EventType type, Network *network, QString prefix, QStringList params = QStringList())
- : NetworkEvent(type, network),
- _prefix(std::move(prefix)),
- _params(std::move(params))
+ explicit IrcEvent(EventManager::EventType type, Network* network, QString prefix, QStringList params = QStringList())
+ : NetworkEvent(type, network)
+ , _prefix(std::move(prefix))
+ , _params(std::move(params))
{}
inline QString prefix() const { return _prefix; }
- inline void setPrefix(const QString &prefix) { _prefix = prefix; }
+ inline void setPrefix(const QString& prefix) { _prefix = prefix; }
inline QString nick() const { return nickFromMask(prefix()); }
inline QStringList params() const { return _params; }
- inline void setParams(const QStringList ¶ms) { _params = params; }
+ inline void setParams(const QStringList& params) { _params = params; }
- static Event *create(EventManager::EventType type, QVariantMap &map, Network *network);
+ static Event* create(EventManager::EventType type, QVariantMap& map, Network* network);
protected:
- explicit IrcEvent(EventManager::EventType type, QVariantMap &map, Network *network);
- void toVariantMap(QVariantMap &map) const override;
+ explicit IrcEvent(EventManager::EventType type, QVariantMap& map, Network* network);
+ void toVariantMap(QVariantMap& map) const override;
inline QString className() const override { return "IrcEvent"; }
- inline void debugInfo(QDebug &dbg) const override
+ inline void debugInfo(QDebug& dbg) const override
{
NetworkEvent::debugInfo(dbg);
- dbg << ", prefix = " << qPrintable(prefix())
- << ", params = " << params();
+ dbg << ", prefix = " << qPrintable(prefix()) << ", params = " << params();
}
-
private:
QString _prefix;
QStringList _params;
};
-
class COMMON_EXPORT IrcEventNumeric : public IrcEvent
{
public:
- explicit IrcEventNumeric(uint number, Network *network, const QString &prefix, QString target, const QStringList ¶ms = QStringList())
- : IrcEvent(EventManager::IrcEventNumeric, network, prefix, params),
- _number(number),
- _target(std::move(target))
+ explicit IrcEventNumeric(uint number, Network* network, const QString& prefix, QString target, const QStringList& params = QStringList())
+ : IrcEvent(EventManager::IrcEventNumeric, network, prefix, params)
+ , _number(number)
+ , _target(std::move(target))
{}
inline uint number() const { return _number; }
inline QString target() const { return _target; }
- inline void setTarget(const QString &target) { _target = target; }
+ inline void setTarget(const QString& target) { _target = target; }
protected:
- explicit IrcEventNumeric(EventManager::EventType type, QVariantMap &map, Network *network);
- void toVariantMap(QVariantMap &map) const override;
+ explicit IrcEventNumeric(EventManager::EventType type, QVariantMap& map, Network* network);
+ void toVariantMap(QVariantMap& map) const override;
inline QString className() const override { return "IrcEventNumeric"; }
- inline void debugInfo(QDebug &dbg) const override
+ inline void debugInfo(QDebug& dbg) const override
{
dbg << ", num = " << number();
NetworkEvent::debugInfo(dbg);
- dbg << ", target = " << qPrintable(target())
- << ", prefix = " << qPrintable(prefix())
- << ", params = " << params();
+ dbg << ", target = " << qPrintable(target()) << ", prefix = " << qPrintable(prefix()) << ", params = " << params();
}
-
private:
uint _number;
QString _target;
friend class IrcEvent;
};
-
class COMMON_EXPORT IrcEventRawMessage : public IrcEvent
{
public:
- explicit inline IrcEventRawMessage(EventManager::EventType type, Network *network,
- QByteArray rawMessage, const QString &prefix, const QString &target,
- const QDateTime ×tamp = QDateTime())
- : IrcEvent(type, network, prefix, QStringList() << target),
- _rawMessage(std::move(rawMessage))
+ explicit inline IrcEventRawMessage(EventManager::EventType type,
+ Network* network,
+ QByteArray rawMessage,
+ const QString& prefix,
+ const QString& target,
+ const QDateTime& timestamp = QDateTime())
+ : IrcEvent(type, network, prefix, QStringList() << target)
+ , _rawMessage(std::move(rawMessage))
{
setTimestamp(timestamp);
}
-
inline QString target() const { return params().at(0); }
- inline void setTarget(const QString &target) { setParams(QStringList() << target); }
+ inline void setTarget(const QString& target) { setParams(QStringList() << target); }
inline QByteArray rawMessage() const { return _rawMessage; }
- inline void setRawMessage(const QByteArray &rawMessage) { _rawMessage = rawMessage; }
+ inline void setRawMessage(const QByteArray& rawMessage) { _rawMessage = rawMessage; }
protected:
- explicit IrcEventRawMessage(EventManager::EventType type, QVariantMap &map, Network *network);
- void toVariantMap(QVariantMap &map) const override;
+ explicit IrcEventRawMessage(EventManager::EventType type, QVariantMap& map, Network* network);
+ void toVariantMap(QVariantMap& map) const override;
inline QString className() const override { return "IrcEventRawMessage"; }
- inline void debugInfo(QDebug &dbg) const override
+ inline void debugInfo(QDebug& dbg) const override
{
NetworkEvent::debugInfo(dbg);
- dbg << ", target = " << qPrintable(target())
- << ", prefix = " << qPrintable(prefix())
- << ", msg = " << rawMessage();
+ dbg << ", target = " << qPrintable(target()) << ", prefix = " << qPrintable(prefix()) << ", msg = " << rawMessage();
}
-
private:
QByteArray _rawMessage;
#pragma once
-#include <utility>
-
#include "common-export.h"
+#include <utility>
+
#include "syncableobject.h"
#include "types.h"
SYNCABLE_OBJECT
public:
- inline IrcListHelper(QObject *parent = nullptr) : SyncableObject(parent) { setInitialized(); };
+ inline IrcListHelper(QObject* parent = nullptr)
+ : SyncableObject(parent)
+ {
+ setInitialized();
+ };
- struct ChannelDescription {
+ struct ChannelDescription
+ {
QString channelName;
quint32 userCount;
QString topic;
- ChannelDescription(QString channelName_, quint32 userCount_, QString topic_) : channelName(std::move(channelName_)), userCount(userCount_), topic(std::move(topic_)) {};
+ ChannelDescription(QString channelName_, quint32 userCount_, QString topic_)
+ : channelName(std::move(channelName_))
+ , userCount(userCount_)
+ , topic(std::move(topic_)){};
};
public slots:
- inline virtual QVariantList requestChannelList(const NetworkId &netId, const QStringList &channelFilters) { REQUEST(ARG(netId), ARG(channelFilters)); return QVariantList(); }
- inline virtual void receiveChannelList(const NetworkId &, const QStringList &, const QVariantList &) {};
- inline virtual void reportFinishedList(const NetworkId &netId) { SYNC(ARG(netId)) }
- inline virtual void reportError(const QString &error) { SYNC(ARG(error)) }
+ inline virtual QVariantList requestChannelList(const NetworkId& netId, const QStringList& channelFilters)
+ {
+ REQUEST(ARG(netId), ARG(channelFilters));
+ return QVariantList();
+ }
+ inline virtual void receiveChannelList(const NetworkId&, const QStringList&, const QVariantList&){};
+ inline virtual void reportFinishedList(const NetworkId& netId) { SYNC(ARG(netId)) }
+ inline virtual void reportError(const QString& error) { SYNC(ARG(error)) }
};
***************************************************************************/
#include "ircuser.h"
-#include "util.h"
+#include <QDebug>
+#include <QTextCodec>
+
+#include "ircchannel.h"
#include "network.h"
#include "signalproxy.h"
-#include "ircchannel.h"
-
-#include <QTextCodec>
-#include <QDebug>
+#include "util.h"
-IrcUser::IrcUser(const QString &hostmask, Network *network) : SyncableObject(network),
- _initialized(false),
- _nick(nickFromMask(hostmask)),
- _user(userFromMask(hostmask)),
- _host(hostFromMask(hostmask)),
- _realName(),
- _awayMessage(),
- _away(false),
- _server(),
+IrcUser::IrcUser(const QString& hostmask, Network* network)
+ : SyncableObject(network)
+ , _initialized(false)
+ , _nick(nickFromMask(hostmask))
+ , _user(userFromMask(hostmask))
+ , _host(hostFromMask(hostmask))
+ , _realName()
+ , _awayMessage()
+ , _away(false)
+ , _server()
+ ,
// _idleTime(QDateTime::currentDateTime()),
- _ircOperator(),
- _lastAwayMessageTime(),
- _whoisServiceReply(),
- _encrypted(false),
- _network(network),
- _codecForEncoding(nullptr),
- _codecForDecoding(nullptr)
+ _ircOperator()
+ , _lastAwayMessageTime()
+ , _whoisServiceReply()
+ , _encrypted(false)
+ , _network(network)
+ , _codecForEncoding(nullptr)
+ , _codecForDecoding(nullptr)
{
updateObjectName();
_lastAwayMessageTime.setTimeSpec(Qt::UTC);
_lastAwayMessageTime.setMSecsSinceEpoch(0);
}
-
// ====================
// PUBLIC:
// ====================
return QString("%1!%2@%3").arg(nick()).arg(user()).arg(host());
}
-
QDateTime IrcUser::idleTime()
{
- if ((QDateTime::currentDateTime().toMSecsSinceEpoch() - _idleTimeSet.toMSecsSinceEpoch())
- > 1200000) {
+ if ((QDateTime::currentDateTime().toMSecsSinceEpoch() - _idleTimeSet.toMSecsSinceEpoch()) > 1200000) {
// 20 * 60 * 1000 = 1200000
// 20 minutes have elapsed, clear the known idle time as it's likely inaccurate by now
_idleTime = QDateTime();
return _idleTime;
}
-
QStringList IrcUser::channels() const
{
QStringList chanList;
- IrcChannel *channel;
- foreach(channel, _channels) {
+ IrcChannel* channel;
+ foreach (channel, _channels) {
chanList << channel->name();
}
return chanList;
}
-
-void IrcUser::setCodecForEncoding(const QString &name)
+void IrcUser::setCodecForEncoding(const QString& name)
{
setCodecForEncoding(QTextCodec::codecForName(name.toLatin1()));
}
-
-void IrcUser::setCodecForEncoding(QTextCodec *codec)
+void IrcUser::setCodecForEncoding(QTextCodec* codec)
{
_codecForEncoding = codec;
}
-
-void IrcUser::setCodecForDecoding(const QString &name)
+void IrcUser::setCodecForDecoding(const QString& name)
{
setCodecForDecoding(QTextCodec::codecForName(name.toLatin1()));
}
-
-void IrcUser::setCodecForDecoding(QTextCodec *codec)
+void IrcUser::setCodecForDecoding(QTextCodec* codec)
{
_codecForDecoding = codec;
}
-
-QString IrcUser::decodeString(const QByteArray &text) const
+QString IrcUser::decodeString(const QByteArray& text) const
{
- if (!codecForDecoding()) return network()->decodeString(text);
+ if (!codecForDecoding())
+ return network()->decodeString(text);
return ::decodeString(text, codecForDecoding());
}
-
-QByteArray IrcUser::encodeString(const QString &string) const
+QByteArray IrcUser::encodeString(const QString& string) const
{
if (codecForEncoding()) {
return codecForEncoding()->fromUnicode(string);
return network()->encodeString(string);
}
-
// ====================
// PUBLIC SLOTS:
// ====================
-void IrcUser::setUser(const QString &user)
+void IrcUser::setUser(const QString& user)
{
if (!user.isEmpty() && _user != user) {
_user = user;
}
}
-
-void IrcUser::setRealName(const QString &realName)
+void IrcUser::setRealName(const QString& realName)
{
if (!realName.isEmpty() && _realName != realName) {
_realName = realName;
}
}
-
-void IrcUser::setAccount(const QString &account)
+void IrcUser::setAccount(const QString& account)
{
if (_account != account) {
_account = account;
}
}
-
void IrcUser::setAway(bool away)
{
if (away != _away) {
}
}
-
-void IrcUser::setAwayMessage(const QString &awayMessage)
+void IrcUser::setAwayMessage(const QString& awayMessage)
{
if (!awayMessage.isEmpty() && _awayMessage != awayMessage) {
_awayMessage = awayMessage;
}
}
-
-void IrcUser::setIdleTime(const QDateTime &idleTime)
+void IrcUser::setIdleTime(const QDateTime& idleTime)
{
if (idleTime.isValid() && _idleTime != idleTime) {
_idleTime = idleTime;
}
}
-
-void IrcUser::setLoginTime(const QDateTime &loginTime)
+void IrcUser::setLoginTime(const QDateTime& loginTime)
{
if (loginTime.isValid() && _loginTime != loginTime) {
_loginTime = loginTime;
}
}
-
-void IrcUser::setServer(const QString &server)
+void IrcUser::setServer(const QString& server)
{
if (!server.isEmpty() && _server != server) {
_server = server;
}
}
-
-void IrcUser::setIrcOperator(const QString &ircOperator)
+void IrcUser::setIrcOperator(const QString& ircOperator)
{
if (!ircOperator.isEmpty() && _ircOperator != ircOperator) {
_ircOperator = ircOperator;
}
}
-
// This function is only ever called by SYNC calls from legacy cores (pre-0.13).
// Therefore, no SYNC call is needed here.
void IrcUser::setLastAwayMessage(int lastAwayMessage)
setLastAwayMessageTime(lastAwayMessageTime);
}
-
-void IrcUser::setLastAwayMessageTime(const QDateTime &lastAwayMessageTime)
+void IrcUser::setLastAwayMessageTime(const QDateTime& lastAwayMessageTime)
{
if (lastAwayMessageTime > _lastAwayMessageTime) {
_lastAwayMessageTime = lastAwayMessageTime;
}
}
-
-void IrcUser::setHost(const QString &host)
+void IrcUser::setHost(const QString& host)
{
if (!host.isEmpty() && _host != host) {
_host = host;
}
}
-
-void IrcUser::setNick(const QString &nick)
+void IrcUser::setNick(const QString& nick)
{
if (!nick.isEmpty() && nick != _nick) {
_nick = nick;
}
}
-
-void IrcUser::setWhoisServiceReply(const QString &whoisServiceReply)
+void IrcUser::setWhoisServiceReply(const QString& whoisServiceReply)
{
if (!whoisServiceReply.isEmpty() && whoisServiceReply != _whoisServiceReply) {
_whoisServiceReply = whoisServiceReply;
}
}
-
-void IrcUser::setSuserHost(const QString &suserHost)
+void IrcUser::setSuserHost(const QString& suserHost)
{
if (!suserHost.isEmpty() && suserHost != _suserHost) {
_suserHost = suserHost;
}
}
-
void IrcUser::setEncrypted(bool encrypted)
{
_encrypted = encrypted;
SYNC(ARG(encrypted))
}
-
void IrcUser::updateObjectName()
{
renameObject(QString::number(network()->networkId().toInt()) + "/" + _nick);
}
-
-void IrcUser::updateHostmask(const QString &mask)
+void IrcUser::updateHostmask(const QString& mask)
{
if (mask == hostmask())
return;
setHost(host);
}
-
-void IrcUser::joinChannel(IrcChannel *channel, bool skip_channel_join)
+void IrcUser::joinChannel(IrcChannel* channel, bool skip_channel_join)
{
Q_ASSERT(channel);
if (!_channels.contains(channel)) {
}
}
-
-void IrcUser::joinChannel(const QString &channelname)
+void IrcUser::joinChannel(const QString& channelname)
{
joinChannel(network()->newIrcChannel(channelname));
}
-
-void IrcUser::partChannel(IrcChannel *channel)
+void IrcUser::partChannel(IrcChannel* channel)
{
if (_channels.contains(channel)) {
_channels.remove(channel);
}
}
-
-void IrcUser::partChannel(const QString &channelname)
+void IrcUser::partChannel(const QString& channelname)
{
- IrcChannel *channel = network()->ircChannel(channelname);
+ IrcChannel* channel = network()->ircChannel(channelname);
if (channel == nullptr) {
qWarning() << "IrcUser::partChannel(): received part for unknown Channel" << channelname;
}
}
}
-
void IrcUser::quit()
{
- QList<IrcChannel *> channels = _channels.toList();
+ QList<IrcChannel*> channels = _channels.toList();
_channels.clear();
- foreach(IrcChannel *channel, channels) {
+ foreach (IrcChannel* channel, channels) {
disconnect(channel, nullptr, this, nullptr);
channel->part(this);
}
emit quited();
}
-
void IrcUser::channelDestroyed()
{
// private slot!
- auto *channel = static_cast<IrcChannel *>(sender());
+ auto* channel = static_cast<IrcChannel*>(sender());
if (_channels.contains(channel)) {
_channels.remove(channel);
if (_channels.isEmpty() && !network()->isMe(this))
}
}
-
-void IrcUser::setUserModes(const QString &modes)
+void IrcUser::setUserModes(const QString& modes)
{
if (_userModes != modes) {
_userModes = modes;
}
}
-
-void IrcUser::addUserModes(const QString &modes)
+void IrcUser::addUserModes(const QString& modes)
{
if (modes.isEmpty())
return;
}
}
-
-void IrcUser::removeUserModes(const QString &modes)
+void IrcUser::removeUserModes(const QString& modes)
{
if (modes.isEmpty())
return;
emit userModesRemoved(modes);
}
-
-void IrcUser::setLastChannelActivity(BufferId buffer, const QDateTime &time)
+void IrcUser::setLastChannelActivity(BufferId buffer, const QDateTime& time)
{
_lastActivity[buffer] = time;
emit lastChannelActivityUpdated(buffer, time);
}
-
-void IrcUser::setLastSpokenTo(BufferId buffer, const QDateTime &time)
+void IrcUser::setLastSpokenTo(BufferId buffer, const QDateTime& time)
{
_lastSpokenTo[buffer] = time;
emit lastSpokenToUpdated(buffer, time);
#include "common-export.h"
+#include <QDateTime>
#include <QSet>
#include <QString>
#include <QStringList>
#include <QVariantMap>
-#include <QDateTime>
#include "syncableobject.h"
#include "types.h"
Q_PROPERTY(QStringList channels READ channels)
Q_PROPERTY(QString userModes READ userModes WRITE setUserModes)
-public :
- IrcUser(const QString &hostmask, Network *network);
+public:
+ IrcUser(const QString& hostmask, Network* network);
inline QString user() const { return _user; }
inline QString host() const { return _host; }
inline QString whoisServiceReply() const { return _whoisServiceReply; }
inline QString suserHost() const { return _suserHost; }
inline bool encrypted() const { return _encrypted; }
- inline Network *network() const { return _network; }
+ inline Network* network() const { return _network; }
inline QString userModes() const { return _userModes; }
QStringList channels() const;
// user-specific encodings
- inline QTextCodec *codecForEncoding() const { return _codecForEncoding; }
- inline QTextCodec *codecForDecoding() const { return _codecForDecoding; }
- void setCodecForEncoding(const QString &codecName);
- void setCodecForEncoding(QTextCodec *codec);
- void setCodecForDecoding(const QString &codecName);
- void setCodecForDecoding(QTextCodec *codec);
+ inline QTextCodec* codecForEncoding() const { return _codecForEncoding; }
+ inline QTextCodec* codecForDecoding() const { return _codecForDecoding; }
+ void setCodecForEncoding(const QString& codecName);
+ void setCodecForEncoding(QTextCodec* codec);
+ void setCodecForDecoding(const QString& codecName);
+ void setCodecForDecoding(QTextCodec* codec);
- QString decodeString(const QByteArray &text) const;
- QByteArray encodeString(const QString &string) const;
+ QString decodeString(const QByteArray& text) const;
+ QByteArray encodeString(const QString& string) const;
// only valid on client side, these are not synced!
inline QDateTime lastChannelActivity(BufferId id) const { return _lastActivity.value(id); }
- void setLastChannelActivity(BufferId id, const QDateTime &time);
+ void setLastChannelActivity(BufferId id, const QDateTime& time);
inline QDateTime lastSpokenTo(BufferId id) const { return _lastSpokenTo.value(id); }
- void setLastSpokenTo(BufferId id, const QDateTime &time);
+ void setLastSpokenTo(BufferId id, const QDateTime& time);
/**
* Gets whether or not the away state has changed since it was last acknowledged
}
public slots:
- void setUser(const QString &user);
- void setHost(const QString &host);
- void setNick(const QString &nick);
- void setRealName(const QString &realName);
+ void setUser(const QString& user);
+ void setHost(const QString& host);
+ void setNick(const QString& nick);
+ void setRealName(const QString& realName);
/**
* Set account name, e.g. NickServ/SASL account
*
* @param[in] account Account name if logged in, * if logged out, or empty string if unknown
*/
- void setAccount(const QString &account);
+ void setAccount(const QString& account);
void setAway(bool away);
- void setAwayMessage(const QString &awayMessage);
- void setIdleTime(const QDateTime &idleTime);
- void setLoginTime(const QDateTime &loginTime);
- void setServer(const QString &server);
- void setIrcOperator(const QString &ircOperator);
+ void setAwayMessage(const QString& awayMessage);
+ void setIdleTime(const QDateTime& idleTime);
+ void setLoginTime(const QDateTime& loginTime);
+ void setServer(const QString& server);
+ void setIrcOperator(const QString& ircOperator);
// setLastAwayMessage is only called by legacy (pre-0.13) cores, which automatically gets
// converted to setting the appropriate lastAwayMessageTime. Do not use this in new code.
void setLastAwayMessage(int lastAwayMessage);
- void setLastAwayMessageTime(const QDateTime &lastAwayMessageTime);
- void setWhoisServiceReply(const QString &whoisServiceReply);
- void setSuserHost(const QString &suserHost);
+ void setLastAwayMessageTime(const QDateTime& lastAwayMessageTime);
+ void setWhoisServiceReply(const QString& whoisServiceReply);
+ void setSuserHost(const QString& suserHost);
void setEncrypted(bool encrypted);
- void updateHostmask(const QString &mask);
+ void updateHostmask(const QString& mask);
- void setUserModes(const QString &modes);
+ void setUserModes(const QString& modes);
/*!
* \brief joinChannel Called when user joins some channel, this function inserts the channel to internal list of channels this user is in.
* \param channel Pointer to a channel this user just joined
* \param skip_channel_join If this is false, this function will also call IrcChannel::joinIrcUser, can be set to true as a performance tweak.
*/
- void joinChannel(IrcChannel *channel, bool skip_channel_join = false);
- void joinChannel(const QString &channelname);
- void partChannel(IrcChannel *channel);
- void partChannel(const QString &channelname);
+ void joinChannel(IrcChannel* channel, bool skip_channel_join = false);
+ void joinChannel(const QString& channelname);
+ void partChannel(IrcChannel* channel);
+ void partChannel(const QString& channelname);
void quit();
- void addUserModes(const QString &modes);
- void removeUserModes(const QString &modes);
+ void addUserModes(const QString& modes);
+ void removeUserModes(const QString& modes);
signals:
-// void userSet(QString user);
-// void hostSet(QString host);
- void nickSet(QString newnick); // needed in NetworkModel
-// void realNameSet(QString realName);
- void awaySet(bool away); // needed in NetworkModel
-// void awayMessageSet(QString awayMessage);
-// void idleTimeSet(QDateTime idleTime);
-// void loginTimeSet(QDateTime loginTime);
-// void serverSet(QString server);
-// void ircOperatorSet(QString ircOperator);
-// void lastAwayMessageTimeSet(QDateTime lastAwayMessageTime);
-// void whoisServiceReplySet(QString whoisServiceReply);
-// void suserHostSet(QString suserHost);
+ // void userSet(QString user);
+ // void hostSet(QString host);
+ void nickSet(QString newnick); // needed in NetworkModel
+ // void realNameSet(QString realName);
+ void awaySet(bool away); // needed in NetworkModel
+ // void awayMessageSet(QString awayMessage);
+ // void idleTimeSet(QDateTime idleTime);
+ // void loginTimeSet(QDateTime loginTime);
+ // void serverSet(QString server);
+ // void ircOperatorSet(QString ircOperator);
+ // void lastAwayMessageTimeSet(QDateTime lastAwayMessageTime);
+ // void whoisServiceReplySet(QString whoisServiceReply);
+ // void suserHostSet(QString suserHost);
void encryptedSet(bool encrypted);
void userModesSet(QString modes);
void channelParted(QString channel);
void quited();
- void lastChannelActivityUpdated(BufferId id, const QDateTime &newTime);
- void lastSpokenToUpdated(BufferId id, const QDateTime &newTime);
+ void lastChannelActivityUpdated(BufferId id, const QDateTime& newTime);
+ void lastSpokenToUpdated(BufferId id, const QDateTime& newTime);
private slots:
void updateObjectName();
void channelDestroyed();
private:
- inline bool operator==(const IrcUser &ircuser2)
- {
- return (_nick.toLower() == ircuser2.nick().toLower());
- }
+ inline bool operator==(const IrcUser& ircuser2) { return (_nick.toLower() == ircuser2.nick().toLower()); }
-
- inline bool operator==(const QString &nickname)
- {
- return (_nick.toLower() == nickname.toLower());
- }
+ inline bool operator==(const QString& nickname) { return (_nick.toLower() == nickname.toLower()); }
/**
* Sets the last away state change as unacknowledged
*
* @see IrcUser::hasAwayChanged()
*/
- inline void markAwayChanged()
- {
- _awayChanged = true;
- }
+ inline void markAwayChanged() { _awayChanged = true; }
bool _initialized;
QString _user;
QString _host;
QString _realName;
- QString _account; /// Account name, e.g. NickServ/SASL account
+ QString _account; /// Account name, e.g. NickServ/SASL account
QString _awayMessage;
bool _away;
QString _server;
bool _encrypted;
// QSet<QString> _channels;
- QSet<IrcChannel *> _channels;
+ QSet<IrcChannel*> _channels;
QString _userModes;
- Network *_network;
+ Network* _network;
- QTextCodec *_codecForEncoding;
- QTextCodec *_codecForDecoding;
+ QTextCodec* _codecForEncoding;
+ QTextCodec* _codecForDecoding;
QHash<BufferId, QDateTime> _lastActivity;
QHash<BufferId, QDateTime> _lastSpokenTo;
#include "quassel.h"
#if defined(HAVE_BACKTRACE) && !defined(Q_OS_MAC)
-# define BUILD_CRASHHANDLER
-# include <dlfcn.h>
-# include <cxxabi.h>
-# include <QFile>
-# include <QTextStream>
-# include <QDebug>
-# include "backtrace_config.h"
+# define BUILD_CRASHHANDLER
+# include <QDebug>
+# include <QFile>
+# include <QTextStream>
+
+# include <cxxabi.h>
+# include <dlfcn.h>
+
+# include "backtrace_config.h"
#endif
-void Quassel::logBacktrace(const QString &filename)
+void Quassel::logBacktrace(const QString& filename)
{
#ifndef BUILD_CRASHHANDLER
Q_UNUSED(filename)
#else
- void *callstack[128];
+ void* callstack[128];
int i, frames = backtrace(callstack, 128);
QFile dumpFile(filename);
// void *dli_saddr; /* Exact value of nearest symbol. */
// } Dl_info;
- #ifdef __LP64__
+# ifdef __LP64__
int addrSize = 16;
- #else
+# else
int addrSize = 8;
- #endif
+# endif
QString funcName;
if (info.dli_sname) {
- char *func = abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, nullptr);
+ char* func = abi::__cxa_demangle(info.dli_sname, nullptr, nullptr, nullptr);
if (func) {
funcName = QString(func);
free(func);
fileName = fileName.mid(slashPos + 1);
}
- QString debugLine = QString("#%1 %2 0x%3 %4").arg(i, 3, 10)
- .arg(fileName, -20)
- .arg((ulong)(callstack[i]), addrSize, 16, QLatin1Char('0'))
- .arg(funcName);
+ QString debugLine = QString("#%1 %2 0x%3 %4")
+ .arg(i, 3, 10)
+ .arg(fileName, -20)
+ .arg((ulong)(callstack[i]), addrSize, 16, QLatin1Char('0'))
+ .arg(funcName);
dumpStream << debugLine << "\n";
qDebug() << qPrintable(debugLine);
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include "quassel.h"
+#include <cstdio>
#include <windows.h>
#include <dbghelp.h>
-#include <stdio.h>
-// #include <QDebug>
#include <QFile>
#include <QTextStream>
-void loadHelpStackFrame(IMAGEHLP_STACK_FRAME &ihsf, const STACKFRAME64 &stackFrame)
+#include "quassel.h"
+
+void loadHelpStackFrame(IMAGEHLP_STACK_FRAME& ihsf, const STACKFRAME64& stackFrame)
{
ZeroMemory(&ihsf, sizeof(IMAGEHLP_STACK_FRAME));
ihsf.InstructionOffset = stackFrame.AddrPC.Offset;
ihsf.FrameOffset = stackFrame.AddrFrame.Offset;
}
-
BOOL CALLBACK EnumSymbolsCB(PSYMBOL_INFO symInfo, ULONG size, PVOID user)
{
Q_UNUSED(size)
- QStringList *params = (QStringList *)user;
+ QStringList* params = (QStringList*)user;
if (symInfo->Flags & SYMFLAG_PARAMETER) {
params->append(symInfo->Name);
}
return TRUE;
}
-
-struct EnumModulesContext {
+struct EnumModulesContext
+{
HANDLE hProcess;
- QTextStream &stream;
- EnumModulesContext(HANDLE hProcess, QTextStream &stream) : hProcess(hProcess), stream(stream) {}
+ QTextStream& stream;
+ EnumModulesContext(HANDLE hProcess, QTextStream& stream)
+ : hProcess(hProcess)
+ , stream(stream)
+ {}
};
BOOL CALLBACK EnumModulesCB(LPCSTR ModuleName, DWORD64 BaseOfDll, PVOID UserContext)
{
Q_UNUSED(ModuleName)
IMAGEHLP_MODULE64 mod;
- EnumModulesContext *context = (EnumModulesContext *)UserContext;
+ EnumModulesContext* context = (EnumModulesContext*)UserContext;
mod.SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
if (SymGetModuleInfo64(context->hProcess, BaseOfDll, &mod)) {
- QString line = QString("%1 0x%2 Image: %3").arg(mod.ModuleName, -14)
- .arg(BaseOfDll, 8, 16, QLatin1Char('0'))
- .arg(mod.LoadedImageName);
+ QString line = QString("%1 0x%2 Image: %3").arg(mod.ModuleName, -14).arg(BaseOfDll, 8, 16, QLatin1Char('0')).arg(mod.LoadedImageName);
// qDebug() << qPrintable(line);
context->stream << line << '\n';
return TRUE;
}
-
#if defined(_M_IX86) && defined(Q_CC_MSVC)
// Disable global optimization and ignore /GS waning caused by
// inline assembly.
// not needed with mingw cause we can tell mingw which registers we use
- #pragma optimize("g", off)
- #pragma warning(push)
- #pragma warning(disable : 4748)
+# pragma optimize("g", off)
+# pragma warning(push)
+# pragma warning(disable : 4748)
#endif
-void Quassel::logBacktrace(const QString &filename)
+void Quassel::logBacktrace(const QString& filename)
{
DWORD MachineType;
CONTEXT Context;
ZeroMemory(&Context, sizeof(CONTEXT));
Context.ContextFlags = CONTEXT_CONTROL;
-#ifdef __MINGW32__
- asm ("Label:\n\t"
- "movl %%ebp,%0;\n\t"
- "movl %%esp,%1;\n\t"
- "movl $Label,%%eax;\n\t"
- "movl %%eax,%2;\n\t"
- : "=r" (Context.Ebp), "=r" (Context.Esp), "=r" (Context.Eip)
- : //no input
- : "eax");
-#else
+# ifdef __MINGW32__
+ asm("Label:\n\t"
+ "movl %%ebp,%0;\n\t"
+ "movl %%esp,%1;\n\t"
+ "movl $Label,%%eax;\n\t"
+ "movl %%eax,%2;\n\t"
+ : "=r"(Context.Ebp), "=r"(Context.Esp), "=r"(Context.Eip)
+ : // no input
+ : "eax");
+# else
_asm {
Label:
mov[Context.Ebp], ebp;
mov eax, [Label];
mov[Context.Eip], eax;
}
-#endif
+# endif
#else
RtlCaptureContext(&Context);
#endif
ZeroMemory(&StackFrame, sizeof(STACKFRAME64));
#ifdef _M_IX86
- MachineType = IMAGE_FILE_MACHINE_I386;
- StackFrame.AddrPC.Offset = Context.Eip;
- StackFrame.AddrPC.Mode = AddrModeFlat;
+ MachineType = IMAGE_FILE_MACHINE_I386;
+ StackFrame.AddrPC.Offset = Context.Eip;
+ StackFrame.AddrPC.Mode = AddrModeFlat;
StackFrame.AddrFrame.Offset = Context.Ebp;
- StackFrame.AddrFrame.Mode = AddrModeFlat;
+ StackFrame.AddrFrame.Mode = AddrModeFlat;
StackFrame.AddrStack.Offset = Context.Esp;
- StackFrame.AddrStack.Mode = AddrModeFlat;
+ StackFrame.AddrStack.Mode = AddrModeFlat;
#elif defined(_M_X64)
- MachineType = IMAGE_FILE_MACHINE_AMD64;
- StackFrame.AddrPC.Offset = Context.Rip;
- StackFrame.AddrPC.Mode = AddrModeFlat;
+ MachineType = IMAGE_FILE_MACHINE_AMD64;
+ StackFrame.AddrPC.Offset = Context.Rip;
+ StackFrame.AddrPC.Mode = AddrModeFlat;
StackFrame.AddrFrame.Offset = Context.Rsp;
- StackFrame.AddrFrame.Mode = AddrModeFlat;
+ StackFrame.AddrFrame.Mode = AddrModeFlat;
StackFrame.AddrStack.Offset = Context.Rsp;
- StackFrame.AddrStack.Mode = AddrModeFlat;
+ StackFrame.AddrStack.Mode = AddrModeFlat;
#elif defined(_M_IA64)
- MachineType = IMAGE_FILE_MACHINE_IA64;
- StackFrame.AddrPC.Offset = Context.StIIP;
- StackFrame.AddrPC.Mode = AddrModeFlat;
+ MachineType = IMAGE_FILE_MACHINE_IA64;
+ StackFrame.AddrPC.Offset = Context.StIIP;
+ StackFrame.AddrPC.Mode = AddrModeFlat;
StackFrame.AddrFrame.Offset = Context.IntSp;
- StackFrame.AddrFrame.Mode = AddrModeFlat;
+ StackFrame.AddrFrame.Mode = AddrModeFlat;
StackFrame.AddrBStore.Offset = Context.RsBSP;
- StackFrame.AddrBStore.Mode = AddrModeFlat;
+ StackFrame.AddrBStore.Mode = AddrModeFlat;
StackFrame.AddrStack.Offset = Context.IntSp;
- StackFrame.AddrStack.Mode = AddrModeFlat;
+ StackFrame.AddrStack.Mode = AddrModeFlat;
#else
- #error "Unsupported platform"
+# error "Unsupported platform"
#endif
- //EnterCriticalSection(&DbgHelpLock);
+ // EnterCriticalSection(&DbgHelpLock);
QFile logFile(filename);
logFile.open(QIODevice::Append);
DWORD64 dwDisplacement;
- ULONG64 buffer[(sizeof(SYMBOL_INFO) +
- MAX_SYM_NAME*sizeof(TCHAR) +
- sizeof(ULONG64) - 1) / sizeof(ULONG64)];
+ ULONG64 buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) + sizeof(ULONG64) - 1) / sizeof(ULONG64)];
PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer;
pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
pSymbol->MaxNameLen = MAX_SYM_NAME;
break;
loadHelpStackFrame(ihsf, StackFrame);
- if (StackFrame.AddrPC.Offset != 0) { // Valid frame.
+ if (StackFrame.AddrPC.Offset != 0) { // Valid frame.
QString fileName("???");
if (SymGetModuleInfo64(hProcess, ihsf.InstructionOffset, &mod)) {
fileName = QString(mod.ImageName);
SymSetContext(hProcess, &ihsf, NULL);
SymEnumSymbols(hProcess, 0, NULL, EnumSymbolsCB, (PVOID)¶ms);
- QString debugLine = QString("#%1 %2 0x%3 %4(%5)").arg(i, 3, 10)
- .arg(fileName, -20)
- .arg(ihsf.InstructionOffset, 8, 16, QLatin1Char('0'))
- .arg(funcName)
- .arg(params.join(", "));
+ QString debugLine = QString("#%1 %2 0x%3 %4(%5)")
+ .arg(i, 3, 10)
+ .arg(fileName, -20)
+ .arg(ihsf.InstructionOffset, 8, 16, QLatin1Char('0'))
+ .arg(funcName)
+ .arg(params.join(", "));
// qDebug() << qPrintable(debugLine);
logStream << debugLine << '\n';
i++;
}
else {
- break; // we're at the end.
+ break; // we're at the end.
}
}
logFile.close();
}
-
#if defined(_M_IX86) && defined(Q_CC_MSVC)
- #pragma warning(pop)
- #pragma optimize("g", on)
+# pragma warning(pop)
+# pragma optimize("g", on)
#endif
#include <iostream>
#ifdef HAVE_SYSLOG
-# include <syslog.h>
+# include <syslog.h>
#endif
#include <QByteArray>
namespace {
-QByteArray msgWithTime(const Logger::LogEntry &msg)
+QByteArray msgWithTime(const Logger::LogEntry& msg)
{
return (msg.timeStamp.toString("yyyy-MM-dd hh:mm:ss ") + msg.message + "\n").toUtf8();
}
-}
-
+} // namespace
-Logger::Logger(QObject *parent)
+Logger::Logger(QObject* parent)
: QObject(parent)
{
static bool registered = []() {
qInstallMessageHandler(Logger::messageHandler);
}
-
Logger::~Logger()
{
// If we're not initialized yet, output pending messages so they don't get lost
if (!_initialized) {
- for (auto &&message : _messages) {
+ for (auto&& message : _messages) {
std::cerr << msgWithTime(message).constData();
}
}
}
-
std::vector<Logger::LogEntry> Logger::messages() const
{
return _messages;
}
-
void Logger::setup(bool keepMessages)
{
_keepMessages = keepMessages;
QString logfilename = Quassel::optionValue("logfile");
if (!logfilename.isEmpty()) {
_logFile.setFileName(logfilename);
- if (!_logFile.open(QFile::Append|QFile::Unbuffered|QFile::Text)) {
+ if (!_logFile.open(QFile::Append | QFile::Unbuffered | QFile::Text)) {
qCritical() << qPrintable(tr("Could not open log file \"%1\": %2").arg(logfilename, _logFile.errorString()));
}
}
if (!_logFile.isOpen()) {
- if (!_logFile.open(stderr, QFile::WriteOnly|QFile::Unbuffered|QFile::Text)) {
+ if (!_logFile.open(stderr, QFile::WriteOnly | QFile::Unbuffered | QFile::Text)) {
qCritical() << qPrintable(tr("Cannot write to stderr: %1").arg(_logFile.errorString()));
}
}
_initialized = true;
// Now that we've setup our logging backends, output pending messages
- for (auto &&message : _messages) {
+ for (auto&& message : _messages) {
outputMessage(message);
}
if (!_keepMessages) {
}
}
-
-void Logger::messageHandler(QtMsgType type, const QMessageLogContext &, const QString &message)
+void Logger::messageHandler(QtMsgType type, const QMessageLogContext&, const QString& message)
{
Quassel::instance()->logger()->handleMessage(type, message);
}
-
-void Logger::handleMessage(QtMsgType type, const QString &msg)
+void Logger::handleMessage(QtMsgType type, const QString& msg)
{
switch (type) {
case QtDebugMsg:
}
}
-
-void Logger::handleMessage(LogLevel level, const QString &msg)
+void Logger::handleMessage(LogLevel level, const QString& msg)
{
QString logString;
emit messageLogged({QDateTime::currentDateTime(), level, logString += msg});
}
-
-void Logger::onMessageLogged(const LogEntry &message)
+void Logger::onMessageLogged(const LogEntry& message)
{
if (_keepMessages) {
_messages.push_back(message);
}
}
-
-void Logger::outputMessage(const LogEntry &message)
+void Logger::outputMessage(const LogEntry& message)
{
if (message.logLevel < _outputLevel) {
return;
case LogLevel::Fatal:
prio = LOG_CRIT;
}
- syslog(prio|LOG_USER, "%s", qPrintable(message.message));
+ syslog(prio | LOG_USER, "%s", qPrintable(message.message));
}
#endif
}
}
#endif
-
}
Q_OBJECT
public:
- Logger(QObject *parent = nullptr);
+ Logger(QObject* parent = nullptr);
~Logger() override;
- enum class LogLevel {
+ enum class LogLevel
+ {
Debug,
Info,
Warning,
Fatal
};
- struct LogEntry {
+ struct LogEntry
+ {
QDateTime timeStamp;
LogLevel logLevel;
QString message;
*/
std::vector<Logger::LogEntry> messages() const;
- static void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message);
+ static void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message);
/**
* Takes the given message with the given log level, formats it and emits the @a messageLogged() signal.
* @param logLevel The log leve of the message
* @param message The message
*/
- void handleMessage(LogLevel logLevel, const QString &message);
+ void handleMessage(LogLevel logLevel, const QString& message);
signals:
/**
*
* @param message The message that was logged
*/
- void messageLogged(const Logger::LogEntry &message);
+ void messageLogged(const Logger::LogEntry& message);
private slots:
- void onMessageLogged(const Logger::LogEntry &message);
+ void onMessageLogged(const Logger::LogEntry& message);
private:
- void handleMessage(QtMsgType type, const QString &message);
- void outputMessage(const LogEntry &message);
+ void handleMessage(QtMsgType type, const QString& message);
+ void outputMessage(const LogEntry& message);
private:
LogLevel _outputLevel{LogLevel::Info};
#include "logmessage.h"
+#include <QDateTime>
#include <QFile>
#include <QTextStream>
-#include <QDateTime>
#include "quassel.h"
LogMessage::LogMessage(Logger::LogLevel level)
: _stream(&_buffer, QIODevice::WriteOnly)
, _logLevel(level)
-{
-}
-
+{}
LogMessage::~LogMessage()
{
Quassel::instance()->logger()->handleMessage(_logLevel, _buffer);
}
-
-LogMessage &LogMessage::operator<<(const QStringList &t)
+LogMessage& LogMessage::operator<<(const QStringList& t)
{
_stream << t.join(" ") << " ";
return *this;
}
-
-LogMessage &LogMessage::operator<<(bool t) {
+LogMessage& LogMessage::operator<<(bool t)
+{
_stream << (t ? "true" : "false") << " ";
return *this;
}
~LogMessage();
template<typename T>
- LogMessage &operator<<(const T &value) {
+ LogMessage& operator<<(const T& value)
+ {
_stream << value << " ";
return *this;
}
- LogMessage &operator<<(const QStringList &t);
- LogMessage &operator<<(bool t);
+ LogMessage& operator<<(const QStringList& t);
+ LogMessage& operator<<(bool t);
private:
QTextStream _stream;
Logger::LogLevel _logLevel;
};
-
// The only reason for LogMessage and the helpers below to exist is the fact that Qt versions
// prior to 5.5 did not support the Info level.
// Once we can rely on Qt 5.5, they will be removed and replaced by the native Qt functions.
class quInfo : public LogMessage
{
public:
- quInfo() : LogMessage(Logger::LogLevel::Info) {}
+ quInfo()
+ : LogMessage(Logger::LogLevel::Info)
+ {}
};
-
/**
* Creates a warning-level log message.
*
class quWarning : public LogMessage
{
public:
- quWarning() : LogMessage(Logger::LogLevel::Warning) {}
+ quWarning()
+ : LogMessage(Logger::LogLevel::Warning)
+ {}
};
-
/**
* Creates an error-level log message.
*
class quError : public LogMessage
{
public:
- quError() : LogMessage(Logger::LogLevel::Error) {}
+ quError()
+ : LogMessage(Logger::LogLevel::Error)
+ {}
};
return QString();
CFIndex length = CFStringGetLength(str);
- const UniChar *chars = CFStringGetCharactersPtr(str);
+ const UniChar* chars = CFStringGetCharactersPtr(str);
if (chars)
- return QString(reinterpret_cast<const QChar *>(chars), length);
+ return QString(reinterpret_cast<const QChar*>(chars), length);
QVarLengthArray<UniChar> buffer(length);
CFStringGetCharacters(str, CFRangeMake(0, length), buffer.data());
- return QString(reinterpret_cast<const QChar *>(buffer.constData()), length);
+ return QString(reinterpret_cast<const QChar*>(buffer.constData()), length);
}
#define MAC_UTILS_H
#include <QString>
+
#include <CoreFoundation/CoreFoundation.h>
QString CFStringToQString(CFStringRef str);
-#endif //MAC_UTILS_H
+#endif // MAC_UTILS_H
#include "message.h"
-#include "util.h"
-#include "peer.h"
-#include "signalproxy.h"
-
-#include <QDataStream>
#include <utility>
-Message::Message(BufferInfo bufferInfo, Type type, QString contents, QString sender,
- QString senderPrefixes, QString realName, QString avatarUrl, Flags flags)
- : _timestamp(QDateTime::currentDateTime().toUTC()),
- _bufferInfo(std::move(bufferInfo)),
- _contents(std::move(contents)),
- _sender(std::move(sender)),
- _senderPrefixes(std::move(senderPrefixes)),
- _realName(std::move(realName)),
- _avatarUrl(std::move(avatarUrl)),
- _type(type),
- _flags(flags)
-{
-}
-
-
-Message::Message(QDateTime ts, BufferInfo bufferInfo, Type type, QString contents,
- QString sender, QString senderPrefixes, QString realName,
- QString avatarUrl, Flags flags)
- : _timestamp(std::move(ts)),
- _bufferInfo(std::move(bufferInfo)),
- _contents(std::move(contents)),
- _sender(std::move(sender)),
- _senderPrefixes(std::move(senderPrefixes)),
- _realName(std::move(realName)),
- _avatarUrl(std::move(avatarUrl)),
- _type(type),
- _flags(flags)
-{
-}
+#include <QDataStream>
+#include "peer.h"
+#include "signalproxy.h"
+#include "util.h"
-QDataStream &operator<<(QDataStream &out, const Message &msg)
+Message::Message(
+ BufferInfo bufferInfo, Type type, QString contents, QString sender, QString senderPrefixes, QString realName, QString avatarUrl, Flags flags)
+ : _timestamp(QDateTime::currentDateTime().toUTC())
+ , _bufferInfo(std::move(bufferInfo))
+ , _contents(std::move(contents))
+ , _sender(std::move(sender))
+ , _senderPrefixes(std::move(senderPrefixes))
+ , _realName(std::move(realName))
+ , _avatarUrl(std::move(avatarUrl))
+ , _type(type)
+ , _flags(flags)
+{}
+
+Message::Message(QDateTime ts,
+ BufferInfo bufferInfo,
+ Type type,
+ QString contents,
+ QString sender,
+ QString senderPrefixes,
+ QString realName,
+ QString avatarUrl,
+ Flags flags)
+ : _timestamp(std::move(ts))
+ , _bufferInfo(std::move(bufferInfo))
+ , _contents(std::move(contents))
+ , _sender(std::move(sender))
+ , _senderPrefixes(std::move(senderPrefixes))
+ , _realName(std::move(realName))
+ , _avatarUrl(std::move(avatarUrl))
+ , _type(type)
+ , _flags(flags)
+{}
+
+QDataStream& operator<<(QDataStream& out, const Message& msg)
{
Q_ASSERT(SignalProxy::current());
Q_ASSERT(SignalProxy::current()->targetPeer());
if (SignalProxy::current()->targetPeer()->hasFeature(Quassel::Feature::LongTime)) {
// toMSecs returns a qint64, signed rather than unsigned
- out << (qint64) msg.timestamp().toMSecsSinceEpoch();
- } else {
- out << (quint32) msg.timestamp().toTime_t();
+ out << (qint64)msg.timestamp().toMSecsSinceEpoch();
+ }
+ else {
+ out << (quint32)msg.timestamp().toTime_t();
}
- out << (quint32) msg.type()
- << (quint8) msg.flags()
- << msg.bufferInfo()
- << msg.sender().toUtf8();
+ out << (quint32)msg.type() << (quint8)msg.flags() << msg.bufferInfo() << msg.sender().toUtf8();
if (SignalProxy::current()->targetPeer()->hasFeature(Quassel::Feature::SenderPrefixes))
out << msg.senderPrefixes().toUtf8();
return out;
}
-
-QDataStream &operator>>(QDataStream &in, Message &msg)
+QDataStream& operator>>(QDataStream& in, Message& msg)
{
Q_ASSERT(SignalProxy::current());
Q_ASSERT(SignalProxy::current()->sourcePeer());
qint64 timeStamp;
in >> timeStamp;
msg._timestamp = QDateTime::fromMSecsSinceEpoch(timeStamp);
- } else {
+ }
+ else {
quint32 timeStamp;
in >> timeStamp;
msg._timestamp = QDateTime::fromTime_t(timeStamp);
return in;
}
-
-QDebug operator<<(QDebug dbg, const Message &msg)
+QDebug operator<<(QDebug dbg, const Message& msg)
{
- dbg.nospace() << qPrintable(QString("Message(MsgId:")) << msg.msgId()
- << qPrintable(QString(",")) << msg.timestamp()
- << qPrintable(QString(", Type:")) << msg.type()
- << qPrintable(QString(", RealName:")) << msg.realName()
- << qPrintable(QString(", AvatarURL:")) << msg.avatarUrl()
- << qPrintable(QString(", Flags:")) << msg.flags() << qPrintable(QString(")"))
- << msg.senderPrefixes() << msg.sender() << ":" << msg.contents();
+ dbg.nospace() << qPrintable(QString("Message(MsgId:")) << msg.msgId() << qPrintable(QString(",")) << msg.timestamp()
+ << qPrintable(QString(", Type:")) << msg.type() << qPrintable(QString(", RealName:")) << msg.realName()
+ << qPrintable(QString(", AvatarURL:")) << msg.avatarUrl() << qPrintable(QString(", Flags:")) << msg.flags()
+ << qPrintable(QString(")")) << msg.senderPrefixes() << msg.sender() << ":" << msg.contents();
return dbg;
}
public:
/** The different types a message can have for display */
- enum Type {
- Plain = 0x00001,
- Notice = 0x00002,
- Action = 0x00004,
- Nick = 0x00008,
- Mode = 0x00010,
- Join = 0x00020,
- Part = 0x00040,
- Quit = 0x00080,
- Kick = 0x00100,
- Kill = 0x00200,
- Server = 0x00400,
- Info = 0x00800,
- Error = 0x01000,
- DayChange = 0x02000,
- Topic = 0x04000,
+ enum Type
+ {
+ Plain = 0x00001,
+ Notice = 0x00002,
+ Action = 0x00004,
+ Nick = 0x00008,
+ Mode = 0x00010,
+ Join = 0x00020,
+ Part = 0x00040,
+ Quit = 0x00080,
+ Kick = 0x00100,
+ Kill = 0x00200,
+ Server = 0x00400,
+ Info = 0x00800,
+ Error = 0x01000,
+ DayChange = 0x02000,
+ Topic = 0x04000,
NetsplitJoin = 0x08000,
NetsplitQuit = 0x10000,
- Invite = 0x20000,
+ Invite = 0x20000,
};
Q_DECLARE_FLAGS(Types, Type)
// DO NOT CHANGE without knowing what you do, some of these flags are stored in the database
- enum Flag {
- None = 0x00,
- Self = 0x01,
- Highlight = 0x02,
+ enum Flag
+ {
+ None = 0x00,
+ Self = 0x01,
+ Highlight = 0x02,
Redirected = 0x04,
- ServerMsg = 0x08,
- StatusMsg = 0x10,
- Backlog = 0x80
+ ServerMsg = 0x08,
+ StatusMsg = 0x10,
+ Backlog = 0x80
};
Q_DECLARE_FLAGS(Flags, Flag)
- Message(BufferInfo bufferInfo = BufferInfo(), Type type = Plain, QString contents = {},
- QString sender = {}, QString senderPrefixes = {}, QString realName = {},
- QString avatarUrl = {}, Flags flags = None);
- Message(QDateTime ts, BufferInfo buffer = BufferInfo(), Type type = Plain,
- QString contents = {}, QString sender = {}, QString senderPrefixes = {},
- QString realName = {}, QString avatarUrl = {}, Flags flags = None);
-
- inline static Message ChangeOfDay(const QDateTime &day) { return Message(day, BufferInfo(), DayChange); }
- inline const MsgId &msgId() const { return _msgId; }
+ Message(BufferInfo bufferInfo = BufferInfo(),
+ Type type = Plain,
+ QString contents = {},
+ QString sender = {},
+ QString senderPrefixes = {},
+ QString realName = {},
+ QString avatarUrl = {},
+ Flags flags = None);
+ Message(QDateTime ts,
+ BufferInfo buffer = BufferInfo(),
+ Type type = Plain,
+ QString contents = {},
+ QString sender = {},
+ QString senderPrefixes = {},
+ QString realName = {},
+ QString avatarUrl = {},
+ Flags flags = None);
+
+ inline static Message ChangeOfDay(const QDateTime& day) { return Message(day, BufferInfo(), DayChange); }
+ inline const MsgId& msgId() const { return _msgId; }
inline void setMsgId(MsgId id) { _msgId = id; }
- inline const BufferInfo &bufferInfo() const { return _bufferInfo; }
- inline const BufferId &bufferId() const { return _bufferInfo.bufferId(); }
+ inline const BufferInfo& bufferInfo() const { return _bufferInfo; }
+ inline const BufferId& bufferId() const { return _bufferInfo.bufferId(); }
inline void setBufferId(BufferId id) { _bufferInfo.setBufferId(id); }
- inline const QString &contents() const { return _contents; }
- inline const QString &sender() const { return _sender; }
- inline const QString &senderPrefixes() const { return _senderPrefixes; }
- inline const QString &realName() const { return _realName; }
- inline const QString &avatarUrl() const { return _avatarUrl; }
+ inline const QString& contents() const { return _contents; }
+ inline const QString& sender() const { return _sender; }
+ inline const QString& senderPrefixes() const { return _senderPrefixes; }
+ inline const QString& realName() const { return _realName; }
+ inline const QString& avatarUrl() const { return _avatarUrl; }
inline Type type() const { return _type; }
inline Flags flags() const { return _flags; }
inline void setFlags(Flags flags) { _flags = flags; }
- inline const QDateTime ×tamp() const { return _timestamp; }
+ inline const QDateTime& timestamp() const { return _timestamp; }
inline bool isValid() const { return _msgId.isValid(); }
- inline bool operator<(const Message &other) const { return _msgId < other._msgId; }
+ inline bool operator<(const Message& other) const { return _msgId < other._msgId; }
private:
QDateTime _timestamp;
Type _type;
Flags _flags;
- friend QDataStream &operator>>(QDataStream &in, Message &msg);
+ friend QDataStream& operator>>(QDataStream& in, Message& msg);
};
-
using MessageList = QList<Message>;
-QDataStream &operator<<(QDataStream &out, const Message &msg);
-QDataStream &operator>>(QDataStream &in, Message &msg);
-QDebug operator<<(QDebug dbg, const Message &msg);
+QDataStream& operator<<(QDataStream& out, const Message& msg);
+QDataStream& operator>>(QDataStream& in, Message& msg);
+QDebug operator<<(QDebug dbg, const Message& msg);
Q_DECLARE_METATYPE(Message)
Q_DECLARE_OPERATORS_FOR_FLAGS(Message::Types)
#include <utility>
-Event *MessageEvent::create(EventManager::EventType type, QVariantMap &map, Network *network)
+Event* MessageEvent::create(EventManager::EventType type, QVariantMap& map, Network* network)
{
if (type == EventManager::MessageEvent)
return new MessageEvent(type, map, network);
return nullptr;
}
-
-MessageEvent::MessageEvent(Message::Type msgType, Network *net, QString msg, const QString &sender, QString target,
- Message::Flags flags, const QDateTime ×tamp)
- : NetworkEvent(EventManager::MessageEvent, net),
- _msgType(msgType),
- _text(std::move(msg)),
- _sender(sender),
- _target(std::move(target)),
- _msgFlags(flags)
+MessageEvent::MessageEvent(
+ Message::Type msgType, Network* net, QString msg, const QString& sender, QString target, Message::Flags flags, const QDateTime& timestamp)
+ : NetworkEvent(EventManager::MessageEvent, net)
+ , _msgType(msgType)
+ , _text(std::move(msg))
+ , _sender(sender)
+ , _target(std::move(target))
+ , _msgFlags(flags)
{
- IrcChannel *channel = network()->ircChannel(_target);
+ IrcChannel* channel = network()->ircChannel(_target);
if (!channel) {
if (!_target.isEmpty() && network()->prefixes().contains(_target.at(0)))
_target = _target.mid(1);
setTimestamp(QDateTime::currentDateTime());
}
-
-MessageEvent::MessageEvent(EventManager::EventType type, QVariantMap &map, Network *network)
+MessageEvent::MessageEvent(EventManager::EventType type, QVariantMap& map, Network* network)
: NetworkEvent(type, map, network)
{
_msgType = static_cast<Message::Type>(map.take("messageType").toInt());
_target = map.take("target").toString();
}
-
-void MessageEvent::toVariantMap(QVariantMap &map) const
+void MessageEvent::toVariantMap(QVariantMap& map) const
{
NetworkEvent::toVariantMap(map);
map["messageType"] = msgType();
map["target"] = target();
}
-
-BufferInfo::Type MessageEvent::bufferTypeByTarget(const QString &target) const
+BufferInfo::Type MessageEvent::bufferTypeByTarget(const QString& target) const
{
if (target.isEmpty())
return BufferInfo::StatusBuffer;
{
public:
explicit MessageEvent(Message::Type msgType,
- Network *network,
- QString msg,
- const QString &sender = QString(),
- QString target = QString(),
- Message::Flags msgFlags = Message::None,
- const QDateTime ×tamp = QDateTime()
- );
+ Network* network,
+ QString msg,
+ const QString& sender = QString(),
+ QString target = QString(),
+ Message::Flags msgFlags = Message::None,
+ const QDateTime& timestamp = QDateTime());
inline Message::Type msgType() const { return _msgType; }
inline void setMsgType(Message::Type type) { _msgType = type; }
inline void setMsgFlag(Message::Flag flag) { _msgFlags |= flag; }
inline void setMsgFlags(Message::Flags flags) { _msgFlags = flags; }
- static Event *create(EventManager::EventType type, QVariantMap &map, Network *network);
+ static Event* create(EventManager::EventType type, QVariantMap& map, Network* network);
protected:
- explicit MessageEvent(EventManager::EventType type, QVariantMap &map, Network *network);
- void toVariantMap(QVariantMap &map) const override;
+ explicit MessageEvent(EventManager::EventType type, QVariantMap& map, Network* network);
+ void toVariantMap(QVariantMap& map) const override;
inline QString className() const override { return "MessageEvent"; }
- inline void debugInfo(QDebug &dbg) const override
+ inline void debugInfo(QDebug& dbg) const override
{
NetworkEvent::debugInfo(dbg);
- dbg.nospace() << ", sender = " << qPrintable(sender())
- << ", target = " << qPrintable(target())
- << ", text = " << text()
+ dbg.nospace() << ", sender = " << qPrintable(sender()) << ", target = " << qPrintable(target()) << ", text = " << text()
<< ", msgtype = " << qPrintable(QString::number(msgType(), 16))
<< ", buffertype = " << qPrintable(QString::number(bufferType(), 16))
<< ", msgflags = " << qPrintable(QString::number(msgFlags(), 16));
}
-
private:
- BufferInfo::Type bufferTypeByTarget(const QString &target) const;
+ BufferInfo::Type bufferTypeByTarget(const QString& target) const;
Message::Type _msgType;
BufferInfo::Type _bufferType;
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "network.h"
+
#include <algorithm>
#include <QTextCodec>
-#include "network.h"
#include "peer.h"
-QTextCodec *Network::_defaultCodecForServer = nullptr;
-QTextCodec *Network::_defaultCodecForEncoding = nullptr;
-QTextCodec *Network::_defaultCodecForDecoding = nullptr;
+QTextCodec* Network::_defaultCodecForServer = nullptr;
+QTextCodec* Network::_defaultCodecForEncoding = nullptr;
+QTextCodec* Network::_defaultCodecForDecoding = nullptr;
// ====================
// Public:
// ====================
-Network::Network(const NetworkId &networkid, QObject *parent)
- : SyncableObject(parent),
- _proxy(nullptr),
- _networkId(networkid),
- _identity(0),
- _myNick(QString()),
- _latency(0),
- _networkName(QString("<not initialized>")),
- _currentServer(QString()),
- _connected(false),
- _connectionState(Disconnected),
- _prefixes(QString()),
- _prefixModes(QString()),
- _useRandomServer(false),
- _useAutoIdentify(false),
- _useSasl(false),
- _useAutoReconnect(false),
- _autoReconnectInterval(60),
- _autoReconnectRetries(10),
- _unlimitedReconnectRetries(false),
- _useCustomMessageRate(false),
- _messageRateBurstSize(5),
- _messageRateDelay(2200),
- _unlimitedMessageRate(false),
- _codecForServer(nullptr),
- _codecForEncoding(nullptr),
- _codecForDecoding(nullptr),
- _autoAwayActive(false)
+Network::Network(const NetworkId& networkid, QObject* parent)
+ : SyncableObject(parent)
+ , _proxy(nullptr)
+ , _networkId(networkid)
+ , _identity(0)
+ , _myNick(QString())
+ , _latency(0)
+ , _networkName(QString("<not initialized>"))
+ , _currentServer(QString())
+ , _connected(false)
+ , _connectionState(Disconnected)
+ , _prefixes(QString())
+ , _prefixModes(QString())
+ , _useRandomServer(false)
+ , _useAutoIdentify(false)
+ , _useSasl(false)
+ , _useAutoReconnect(false)
+ , _autoReconnectInterval(60)
+ , _autoReconnectRetries(10)
+ , _unlimitedReconnectRetries(false)
+ , _useCustomMessageRate(false)
+ , _messageRateBurstSize(5)
+ , _messageRateDelay(2200)
+ , _unlimitedMessageRate(false)
+ , _codecForServer(nullptr)
+ , _codecForEncoding(nullptr)
+ , _codecForDecoding(nullptr)
+ , _autoAwayActive(false)
{
setObjectName(QString::number(networkid.toInt()));
}
-
Network::~Network()
{
emit aboutToBeDestroyed();
}
-
-bool Network::isChannelName(const QString &channelname) const
+bool Network::isChannelName(const QString& channelname) const
{
if (channelname.isEmpty())
return false;
return QString("#&!+").contains(channelname[0]);
}
-
-bool Network::isStatusMsg(const QString &target) const
+bool Network::isStatusMsg(const QString& target) const
{
if (target.isEmpty())
return false;
return QString("@+").contains(target[0]);
}
-
NetworkInfo Network::networkInfo() const
{
NetworkInfo info;
return info;
}
-
-void Network::setNetworkInfo(const NetworkInfo &info)
+void Network::setNetworkInfo(const NetworkInfo& info)
{
// we don't set our ID!
- if (!info.networkName.isEmpty() && info.networkName != networkName()) setNetworkName(info.networkName);
- if (info.identity > 0 && info.identity != identity()) setIdentity(info.identity);
- if (info.codecForServer != codecForServer()) setCodecForServer(QTextCodec::codecForName(info.codecForServer));
- if (info.codecForEncoding != codecForEncoding()) setCodecForEncoding(QTextCodec::codecForName(info.codecForEncoding));
- if (info.codecForDecoding != codecForDecoding()) setCodecForDecoding(QTextCodec::codecForName(info.codecForDecoding));
- if (info.serverList.count()) setServerList(toVariantList(info.serverList)); // FIXME compare components
- if (info.useRandomServer != useRandomServer()) setUseRandomServer(info.useRandomServer);
- if (info.perform != perform()) setPerform(info.perform);
- if (info.useAutoIdentify != useAutoIdentify()) setUseAutoIdentify(info.useAutoIdentify);
- if (info.autoIdentifyService != autoIdentifyService()) setAutoIdentifyService(info.autoIdentifyService);
- if (info.autoIdentifyPassword != autoIdentifyPassword()) setAutoIdentifyPassword(info.autoIdentifyPassword);
- if (info.useSasl != useSasl()) setUseSasl(info.useSasl);
- if (info.saslAccount != saslAccount()) setSaslAccount(info.saslAccount);
- if (info.saslPassword != saslPassword()) setSaslPassword(info.saslPassword);
- if (info.useAutoReconnect != useAutoReconnect()) setUseAutoReconnect(info.useAutoReconnect);
- if (info.autoReconnectInterval != autoReconnectInterval()) setAutoReconnectInterval(info.autoReconnectInterval);
- if (info.autoReconnectRetries != autoReconnectRetries()) setAutoReconnectRetries(info.autoReconnectRetries);
- if (info.unlimitedReconnectRetries != unlimitedReconnectRetries()) setUnlimitedReconnectRetries(info.unlimitedReconnectRetries);
- if (info.rejoinChannels != rejoinChannels()) setRejoinChannels(info.rejoinChannels);
+ if (!info.networkName.isEmpty() && info.networkName != networkName())
+ setNetworkName(info.networkName);
+ if (info.identity > 0 && info.identity != identity())
+ setIdentity(info.identity);
+ if (info.codecForServer != codecForServer())
+ setCodecForServer(QTextCodec::codecForName(info.codecForServer));
+ if (info.codecForEncoding != codecForEncoding())
+ setCodecForEncoding(QTextCodec::codecForName(info.codecForEncoding));
+ if (info.codecForDecoding != codecForDecoding())
+ setCodecForDecoding(QTextCodec::codecForName(info.codecForDecoding));
+ if (info.serverList.count())
+ setServerList(toVariantList(info.serverList)); // FIXME compare components
+ if (info.useRandomServer != useRandomServer())
+ setUseRandomServer(info.useRandomServer);
+ if (info.perform != perform())
+ setPerform(info.perform);
+ if (info.useAutoIdentify != useAutoIdentify())
+ setUseAutoIdentify(info.useAutoIdentify);
+ if (info.autoIdentifyService != autoIdentifyService())
+ setAutoIdentifyService(info.autoIdentifyService);
+ if (info.autoIdentifyPassword != autoIdentifyPassword())
+ setAutoIdentifyPassword(info.autoIdentifyPassword);
+ if (info.useSasl != useSasl())
+ setUseSasl(info.useSasl);
+ if (info.saslAccount != saslAccount())
+ setSaslAccount(info.saslAccount);
+ if (info.saslPassword != saslPassword())
+ setSaslPassword(info.saslPassword);
+ if (info.useAutoReconnect != useAutoReconnect())
+ setUseAutoReconnect(info.useAutoReconnect);
+ if (info.autoReconnectInterval != autoReconnectInterval())
+ setAutoReconnectInterval(info.autoReconnectInterval);
+ if (info.autoReconnectRetries != autoReconnectRetries())
+ setAutoReconnectRetries(info.autoReconnectRetries);
+ if (info.unlimitedReconnectRetries != unlimitedReconnectRetries())
+ setUnlimitedReconnectRetries(info.unlimitedReconnectRetries);
+ if (info.rejoinChannels != rejoinChannels())
+ setRejoinChannels(info.rejoinChannels);
// Custom rate limiting
if (info.useCustomMessageRate != useCustomMessageRate())
setUseCustomMessageRate(info.useCustomMessageRate);
setUnlimitedMessageRate(info.unlimitedMessageRate);
}
-
-QString Network::prefixToMode(const QString &prefix) const
+QString Network::prefixToMode(const QString& prefix) const
{
if (prefixes().contains(prefix))
return QString(prefixModes()[prefixes().indexOf(prefix)]);
return QString();
}
-
-QString Network::modeToPrefix(const QString &mode) const
+QString Network::modeToPrefix(const QString& mode) const
{
if (prefixModes().contains(mode))
return QString(prefixes()[prefixModes().indexOf(mode)]);
return QString();
}
-
-QString Network::sortPrefixModes(const QString &modes) const
+QString Network::sortPrefixModes(const QString& modes) const
{
// If modes is empty or we don't have any modes, nothing can be sorted, bail out early
if (modes.isEmpty() || prefixModes().isEmpty()) {
// Sort modes as if a QChar array
// See https://en.cppreference.com/w/cpp/algorithm/sort
// Defining lambda with [&] implicitly captures variables by reference
- std::sort(sortedModes.begin(), sortedModes.end(), [&](const QChar &lmode, const QChar &rmode) {
+ std::sort(sortedModes.begin(), sortedModes.end(), [&](const QChar& lmode, const QChar& rmode) {
// Compare characters according to prefix modes
// Return true if lmode comes before rmode (is "less than")
if (!prefixModes().contains(lmode)) {
// Left mode not in prefix list, send to end
return false;
- } else if (!prefixModes().contains(rmode)) {
+ }
+ else if (!prefixModes().contains(rmode)) {
// Right mode not in prefix list, send to end
return true;
- } else {
+ }
+ else {
// Both characters known, sort according to index in prefixModes()
return (prefixModes().indexOf(lmode) < prefixModes().indexOf(rmode));
}
return sortedModes;
}
-
QStringList Network::nicks() const
{
// we don't use _ircUsers.keys() since the keys may be
// not up to date after a nick change
QStringList nicks;
- foreach(IrcUser *ircuser, _ircUsers.values()) {
+ foreach (IrcUser* ircuser, _ircUsers.values()) {
nicks << ircuser->nick();
}
return nicks;
}
-
QString Network::prefixes() const
{
if (_prefixes.isNull())
return _prefixes;
}
-
QString Network::prefixModes() const
{
if (_prefixModes.isNull())
return _prefixModes;
}
-
// example Unreal IRCD: CHANMODES=beI,kfL,lj,psmntirRcOAQKVCuzNSMTG
-Network::ChannelModeType Network::channelModeType(const QString &mode)
+Network::ChannelModeType Network::channelModeType(const QString& mode)
{
if (mode.isEmpty())
return NOT_A_CHANMODE;
return modeType;
}
-
-QString Network::support(const QString ¶m) const
+QString Network::support(const QString& param) const
{
QString support_ = param.toUpper();
if (_supports.contains(support_))
return QString();
}
-
-bool Network::saslMaybeSupports(const QString &saslMechanism) const
+bool Network::saslMaybeSupports(const QString& saslMechanism) const
{
if (!capAvailable(IrcCap::SASL)) {
// If SASL's not advertised at all, it's likely the mechanism isn't supported, as per specs.
// reduce the risk of breaking existing setups.
// See: http://ircv3.net/specs/extensions/sasl-3.1.html
// And: http://ircv3.net/specs/extensions/sasl-3.2.html
- return (saslCapValue.length() == 0)
- || (saslCapValue.contains(saslMechanism, Qt::CaseInsensitive));
+ return (saslCapValue.length() == 0) || (saslCapValue.contains(saslMechanism, Qt::CaseInsensitive));
}
-
-IrcUser *Network::newIrcUser(const QString &hostmask, const QVariantMap &initData)
+IrcUser* Network::newIrcUser(const QString& hostmask, const QVariantMap& initData)
{
QString nick(nickFromMask(hostmask).toLower());
if (!_ircUsers.contains(nick)) {
- IrcUser *ircuser = ircUserFactory(hostmask);
+ IrcUser* ircuser = ircUserFactory(hostmask);
if (!initData.isEmpty()) {
ircuser->fromVariantMap(initData);
ircuser->setInitialized();
return _ircUsers[nick];
}
-
-IrcUser *Network::ircUser(QString nickname) const
+IrcUser* Network::ircUser(QString nickname) const
{
nickname = nickname.toLower();
if (_ircUsers.contains(nickname))
return nullptr;
}
-
-void Network::removeIrcUser(IrcUser *ircuser)
+void Network::removeIrcUser(IrcUser* ircuser)
{
QString nick = _ircUsers.key(ircuser);
if (nick.isNull())
ircuser->deleteLater();
}
-
-void Network::removeIrcChannel(IrcChannel *channel)
+void Network::removeIrcChannel(IrcChannel* channel)
{
QString chanName = _ircChannels.key(channel);
if (chanName.isNull())
channel->deleteLater();
}
-
void Network::removeChansAndUsers()
{
- QList<IrcUser *> users = ircUsers();
+ QList<IrcUser*> users = ircUsers();
_ircUsers.clear();
- QList<IrcChannel *> channels = ircChannels();
+ QList<IrcChannel*> channels = ircChannels();
_ircChannels.clear();
qDeleteAll(users);
qDeleteAll(channels);
}
-
-IrcChannel *Network::newIrcChannel(const QString &channelname, const QVariantMap &initData)
+IrcChannel* Network::newIrcChannel(const QString& channelname, const QVariantMap& initData)
{
if (!_ircChannels.contains(channelname.toLower())) {
- IrcChannel *channel = ircChannelFactory(channelname);
+ IrcChannel* channel = ircChannelFactory(channelname);
if (!initData.isEmpty()) {
channel->fromVariantMap(initData);
channel->setInitialized();
return _ircChannels[channelname.toLower()];
}
-
-IrcChannel *Network::ircChannel(QString channelname) const
+IrcChannel* Network::ircChannel(QString channelname) const
{
channelname = channelname.toLower();
if (_ircChannels.contains(channelname))
return nullptr;
}
-
QByteArray Network::defaultCodecForServer()
{
if (_defaultCodecForServer)
return QByteArray();
}
-
-void Network::setDefaultCodecForServer(const QByteArray &name)
+void Network::setDefaultCodecForServer(const QByteArray& name)
{
_defaultCodecForServer = QTextCodec::codecForName(name);
}
-
QByteArray Network::defaultCodecForEncoding()
{
if (_defaultCodecForEncoding)
return QByteArray();
}
-
-void Network::setDefaultCodecForEncoding(const QByteArray &name)
+void Network::setDefaultCodecForEncoding(const QByteArray& name)
{
_defaultCodecForEncoding = QTextCodec::codecForName(name);
}
-
QByteArray Network::defaultCodecForDecoding()
{
if (_defaultCodecForDecoding)
return QByteArray();
}
-
-void Network::setDefaultCodecForDecoding(const QByteArray &name)
+void Network::setDefaultCodecForDecoding(const QByteArray& name)
{
_defaultCodecForDecoding = QTextCodec::codecForName(name);
}
-
QByteArray Network::codecForServer() const
{
if (_codecForServer)
return QByteArray();
}
-
-void Network::setCodecForServer(const QByteArray &name)
+void Network::setCodecForServer(const QByteArray& name)
{
setCodecForServer(QTextCodec::codecForName(name));
}
-
-void Network::setCodecForServer(QTextCodec *codec)
+void Network::setCodecForServer(QTextCodec* codec)
{
_codecForServer = codec;
QByteArray codecName = codecForServer();
emit configChanged();
}
-
QByteArray Network::codecForEncoding() const
{
if (_codecForEncoding)
return QByteArray();
}
-
-void Network::setCodecForEncoding(const QByteArray &name)
+void Network::setCodecForEncoding(const QByteArray& name)
{
setCodecForEncoding(QTextCodec::codecForName(name));
}
-
-void Network::setCodecForEncoding(QTextCodec *codec)
+void Network::setCodecForEncoding(QTextCodec* codec)
{
_codecForEncoding = codec;
QByteArray codecName = codecForEncoding();
emit configChanged();
}
-
QByteArray Network::codecForDecoding() const
{
if (_codecForDecoding)
return _codecForDecoding->name();
- else return QByteArray();
+ else
+ return QByteArray();
}
-
-void Network::setCodecForDecoding(const QByteArray &name)
+void Network::setCodecForDecoding(const QByteArray& name)
{
setCodecForDecoding(QTextCodec::codecForName(name));
}
-
-void Network::setCodecForDecoding(QTextCodec *codec)
+void Network::setCodecForDecoding(QTextCodec* codec)
{
_codecForDecoding = codec;
QByteArray codecName = codecForDecoding();
emit configChanged();
}
-
// FIXME use server encoding if appropriate
-QString Network::decodeString(const QByteArray &text) const
+QString Network::decodeString(const QByteArray& text) const
{
if (_codecForDecoding)
return ::decodeString(text, _codecForDecoding);
- else return ::decodeString(text, _defaultCodecForDecoding);
+ else
+ return ::decodeString(text, _defaultCodecForDecoding);
}
-
-QByteArray Network::encodeString(const QString &string) const
+QByteArray Network::encodeString(const QString& string) const
{
if (_codecForEncoding) {
return _codecForEncoding->fromUnicode(string);
return string.toLatin1();
}
-
-QString Network::decodeServerString(const QByteArray &text) const
+QString Network::decodeServerString(const QByteArray& text) const
{
if (_codecForServer)
return ::decodeString(text, _codecForServer);
return ::decodeString(text, _defaultCodecForServer);
}
-
-QByteArray Network::encodeServerString(const QString &string) const
+QByteArray Network::encodeServerString(const QString& string) const
{
if (_codecForServer) {
return _codecForServer->fromUnicode(string);
return string.toLatin1();
}
-
// ====================
// Public Slots:
// ====================
-void Network::setNetworkName(const QString &networkName)
+void Network::setNetworkName(const QString& networkName)
{
_networkName = networkName;
SYNC(ARG(networkName))
emit configChanged();
}
-
-void Network::setCurrentServer(const QString ¤tServer)
+void Network::setCurrentServer(const QString& currentServer)
{
_currentServer = currentServer;
SYNC(ARG(currentServer))
emit currentServerSet(currentServer);
}
-
void Network::setConnected(bool connected)
{
if (_connected == connected)
emit connectedSet(connected);
}
-
-//void Network::setConnectionState(ConnectionState state) {
+// void Network::setConnectionState(ConnectionState state) {
void Network::setConnectionState(int state)
{
_connectionState = (ConnectionState)state;
- //qDebug() << "netstate" << networkId() << networkName() << state;
+ // qDebug() << "netstate" << networkId() << networkName() << state;
SYNC(ARG(state))
emit connectionStateSet(_connectionState);
}
-
-void Network::setMyNick(const QString &nickname)
+void Network::setMyNick(const QString& nickname)
{
_myNick = nickname;
if (!_myNick.isEmpty() && !ircUser(myNick())) {
emit myNickSet(nickname);
}
-
void Network::setLatency(int latency)
{
if (_latency == latency)
SYNC(ARG(latency))
}
-
void Network::setIdentity(IdentityId id)
{
_identity = id;
emit configChanged();
}
-
-void Network::setServerList(const QVariantList &serverList)
+void Network::setServerList(const QVariantList& serverList)
{
_serverList = fromVariantList<Server>(serverList);
SYNC(ARG(serverList))
emit configChanged();
}
-
void Network::setUseRandomServer(bool use)
{
_useRandomServer = use;
emit configChanged();
}
-
-void Network::setPerform(const QStringList &perform)
+void Network::setPerform(const QStringList& perform)
{
_perform = perform;
SYNC(ARG(perform))
emit configChanged();
}
-
void Network::setUseAutoIdentify(bool use)
{
_useAutoIdentify = use;
emit configChanged();
}
-
-void Network::setAutoIdentifyService(const QString &service)
+void Network::setAutoIdentifyService(const QString& service)
{
_autoIdentifyService = service;
SYNC(ARG(service))
emit configChanged();
}
-
-void Network::setAutoIdentifyPassword(const QString &password)
+void Network::setAutoIdentifyPassword(const QString& password)
{
_autoIdentifyPassword = password;
SYNC(ARG(password))
emit configChanged();
}
-
void Network::setUseSasl(bool use)
{
_useSasl = use;
emit configChanged();
}
-
-void Network::setSaslAccount(const QString &account)
+void Network::setSaslAccount(const QString& account)
{
_saslAccount = account;
SYNC(ARG(account))
emit configChanged();
}
-
-void Network::setSaslPassword(const QString &password)
+void Network::setSaslPassword(const QString& password)
{
_saslPassword = password;
SYNC(ARG(password))
emit configChanged();
}
-
void Network::setUseAutoReconnect(bool use)
{
_useAutoReconnect = use;
emit configChanged();
}
-
void Network::setAutoReconnectInterval(quint32 interval)
{
_autoReconnectInterval = interval;
emit configChanged();
}
-
void Network::setAutoReconnectRetries(quint16 retries)
{
_autoReconnectRetries = retries;
emit configChanged();
}
-
void Network::setUnlimitedReconnectRetries(bool unlimited)
{
_unlimitedReconnectRetries = unlimited;
emit configChanged();
}
-
void Network::setRejoinChannels(bool rejoin)
{
_rejoinChannels = rejoin;
emit configChanged();
}
-
void Network::setUseCustomMessageRate(bool useCustomRate)
{
if (_useCustomMessageRate != useCustomRate) {
}
}
-
void Network::setMessageRateBurstSize(quint32 burstSize)
{
if (burstSize < 1) {
// Can't go slower than one message at a time. Also blocks old clients from trying to set
// this to 0.
qDebug() << "Received invalid setMessageRateBurstSize data - message burst size must be "
- "non-zero positive, given" << burstSize;
+ "non-zero positive, given"
+ << burstSize;
return;
}
if (_messageRateBurstSize != burstSize) {
}
}
-
void Network::setMessageRateDelay(quint32 messageDelay)
{
if (messageDelay == 0) {
// Nonsensical to have no delay - just check the Unlimited box instead. Also blocks old
// clients from trying to set this to 0.
qDebug() << "Received invalid setMessageRateDelay data - message delay must be non-zero "
- "positive, given" << messageDelay;
+ "positive, given"
+ << messageDelay;
return;
}
if (_messageRateDelay != messageDelay) {
}
}
-
void Network::setUnlimitedMessageRate(bool unlimitedRate)
{
if (_unlimitedMessageRate != unlimitedRate) {
}
}
-
-void Network::addSupport(const QString ¶m, const QString &value)
+void Network::addSupport(const QString& param, const QString& value)
{
if (!_supports.contains(param)) {
_supports[param] = value;
}
}
-
-void Network::removeSupport(const QString ¶m)
+void Network::removeSupport(const QString& param)
{
if (_supports.contains(param)) {
_supports.remove(param);
}
}
-
QVariantMap Network::initSupports() const
{
QVariantMap supports;
return supports;
}
-void Network::addCap(const QString &capability, const QString &value)
+void Network::addCap(const QString& capability, const QString& value)
{
// IRCv3 specs all use lowercase capability names
QString _capLowercase = capability.toLower();
}
}
-void Network::acknowledgeCap(const QString &capability)
+void Network::acknowledgeCap(const QString& capability)
{
// IRCv3 specs all use lowercase capability names
QString _capLowercase = capability.toLower();
}
}
-void Network::removeCap(const QString &capability)
+void Network::removeCap(const QString& capability)
{
// IRCv3 specs all use lowercase capability names
QString _capLowercase = capability.toLower();
// If performance issues arise, this can be converted to a more-efficient setup without breaking
// protocol (in theory).
QString _capLowercase;
- foreach (const QString &capability, _caps) {
+ foreach (const QString& capability, _caps) {
_capLowercase = capability.toLower();
emit capRemoved(_capLowercase);
}
return caps;
}
-
// There's potentially a lot of users and channels, so it makes sense to optimize the format of this.
// Rather than sending a thousand maps with identical keys, we convert this into one map containing lists
// where each list index corresponds to a particular IrcUser. This saves sending the key names a thousand times.
if (_ircUsers.count()) {
QHash<QString, QVariantList> users;
- QHash<QString, IrcUser *>::const_iterator it = _ircUsers.begin();
- QHash<QString, IrcUser *>::const_iterator end = _ircUsers.end();
+ QHash<QString, IrcUser*>::const_iterator it = _ircUsers.begin();
+ QHash<QString, IrcUser*>::const_iterator end = _ircUsers.end();
while (it != end) {
QVariantMap map = it.value()->toVariantMap();
// If the peer doesn't support LongTime, replace the lastAwayMessageTime field
// Can't have a container with a value type != QVariant in a QVariant :(
// However, working directly on a QVariantMap is awkward for appending, thus the detour via the hash above.
QVariantMap userMap;
- foreach(const QString &key, users.keys())
+ foreach (const QString& key, users.keys())
userMap[key] = users[key];
usersAndChannels["Users"] = userMap;
}
if (_ircChannels.count()) {
QHash<QString, QVariantList> channels;
- QHash<QString, IrcChannel *>::const_iterator it = _ircChannels.begin();
- QHash<QString, IrcChannel *>::const_iterator end = _ircChannels.end();
+ QHash<QString, IrcChannel*>::const_iterator it = _ircChannels.begin();
+ QHash<QString, IrcChannel*>::const_iterator end = _ircChannels.end();
while (it != end) {
- const QVariantMap &map = it.value()->toVariantMap();
+ const QVariantMap& map = it.value()->toVariantMap();
QVariantMap::const_iterator mapiter = map.begin();
while (mapiter != map.end()) {
channels[mapiter.key()] << mapiter.value();
++it;
}
QVariantMap channelMap;
- foreach(const QString &key, channels.keys())
+ foreach (const QString& key, channels.keys())
channelMap[key] = channels[key];
usersAndChannels["Channels"] = channelMap;
}
return usersAndChannels;
}
-
-void Network::initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels)
+void Network::initSetIrcUsersAndChannels(const QVariantMap& usersAndChannels)
{
Q_ASSERT(proxy());
Q_ASSERT(proxy()->sourcePeer());
if (isInitialized()) {
- qWarning() << "Network" << networkId() << "received init data for users and channels although there already are known users or channels!";
+ qWarning() << "Network" << networkId()
+ << "received init data for users and channels although there already are known users or channels!";
return;
}
// toMap() and toList() are cheap, so we can avoid copying to lists...
// However, we really have to make sure to never accidentally detach from the shared data!
- const QVariantMap &users = usersAndChannels["Users"].toMap();
+ const QVariantMap& users = usersAndChannels["Users"].toMap();
// sanity check
int count = users["nick"].toList().count();
- foreach(const QString &key, users.keys()) {
+ foreach (const QString& key, users.keys()) {
if (users[key].toList().count() != count) {
qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
return;
}
// now create the individual IrcUsers
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
QVariantMap map;
- foreach(const QString &key, users.keys())
+ foreach (const QString& key, users.keys())
map[key] = users[key].toList().at(i);
// If the peer doesn't support LongTime, upconvert the lastAwayMessageTime field
map["lastAwayMessageTime"] = lastAwayMessageTime;
}
- newIrcUser(map["nick"].toString(), map); // newIrcUser() properly handles the hostmask being just the nick
+ newIrcUser(map["nick"].toString(), map); // newIrcUser() properly handles the hostmask being just the nick
}
// same thing for IrcChannels
- const QVariantMap &channels = usersAndChannels["Channels"].toMap();
+ const QVariantMap& channels = usersAndChannels["Channels"].toMap();
// sanity check
count = channels["name"].toList().count();
- foreach(const QString &key, channels.keys()) {
+ foreach (const QString& key, channels.keys()) {
if (channels[key].toList().count() != count) {
qWarning() << "Received invalid usersAndChannels init data, sizes of attribute lists don't match!";
return;
}
}
// now create the individual IrcChannels
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
QVariantMap map;
- foreach(const QString &key, channels.keys())
+ foreach (const QString& key, channels.keys())
map[key] = channels[key].toList().at(i);
newIrcChannel(map["name"].toString(), map);
}
}
-
-void Network::initSetSupports(const QVariantMap &supports)
+void Network::initSetSupports(const QVariantMap& supports)
{
QMapIterator<QString, QVariant> iter(supports);
while (iter.hasNext()) {
}
}
-
-void Network::initSetCaps(const QVariantMap &caps)
+void Network::initSetCaps(const QVariantMap& caps)
{
QMapIterator<QString, QVariant> iter(caps);
while (iter.hasNext()) {
}
}
-
-IrcUser *Network::updateNickFromMask(const QString &mask)
+IrcUser* Network::updateNickFromMask(const QString& mask)
{
QString nick(nickFromMask(mask).toLower());
- IrcUser *ircuser;
+ IrcUser* ircuser;
if (_ircUsers.contains(nick)) {
ircuser = _ircUsers[nick];
return ircuser;
}
-
void Network::ircUserNickChanged(QString newnick)
{
- QString oldnick = _ircUsers.key(qobject_cast<IrcUser *>(sender()));
+ QString oldnick = _ircUsers.key(qobject_cast<IrcUser*>(sender()));
if (oldnick.isNull())
return;
- if (newnick.toLower() != oldnick) _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
+ if (newnick.toLower() != oldnick)
+ _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
if (myNick().toLower() == oldnick)
setMyNick(newnick);
}
-
-void Network::emitConnectionError(const QString &errorMsg)
+void Network::emitConnectionError(const QString& errorMsg)
{
emit connectionError(errorMsg);
}
-
// ====================
// Private:
// ====================
}
}
-
/************************************************************************
* NetworkInfo
************************************************************************/
-
-bool NetworkInfo::operator==(const NetworkInfo &other) const
+bool NetworkInfo::operator==(const NetworkInfo& other) const
{
return networkName == other.networkName
&& serverList == other.serverList
;
}
-
-bool NetworkInfo::operator!=(const NetworkInfo &other) const
+bool NetworkInfo::operator!=(const NetworkInfo& other) const
{
return !(*this == other);
}
-
-QDataStream &operator<<(QDataStream &out, const NetworkInfo &info)
+QDataStream& operator<<(QDataStream& out, const NetworkInfo& info)
{
QVariantMap i;
i["NetworkName"] = info.networkName;
return out;
}
-
-QDataStream &operator>>(QDataStream &in, NetworkInfo &info)
+QDataStream& operator>>(QDataStream& in, NetworkInfo& info)
{
QVariantMap i;
in >> i;
return in;
}
-
-QDebug operator<<(QDebug dbg, const NetworkInfo &i)
+QDebug operator<<(QDebug dbg, const NetworkInfo& i)
{
dbg.nospace() << "(id = " << i.networkId << " name = " << i.networkName << " identity = " << i.identity
- << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding << " codecForDecoding = " << i.codecForDecoding
- << " serverList = " << i.serverList << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform
- << " useAutoIdentify = " << i.useAutoIdentify << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword
- << " useSasl = " << i.useSasl << " saslAccount = " << i.saslAccount << " saslPassword = " << i.saslPassword
- << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval
- << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries
- << " rejoinChannels = " << i.rejoinChannels
- << " useCustomMessageRate = " << i.useCustomMessageRate
- << " messageRateBurstSize = " << i.messageRateBurstSize
- << " messageRateDelay = " << i.messageRateDelay
- << " unlimitedMessageRate = " << i.unlimitedMessageRate
- << ")";
+ << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding
+ << " codecForDecoding = " << i.codecForDecoding << " serverList = " << i.serverList
+ << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform << " useAutoIdentify = " << i.useAutoIdentify
+ << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword
+ << " useSasl = " << i.useSasl << " saslAccount = " << i.saslAccount << " saslPassword = " << i.saslPassword
+ << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval
+ << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries
+ << " rejoinChannels = " << i.rejoinChannels << " useCustomMessageRate = " << i.useCustomMessageRate
+ << " messageRateBurstSize = " << i.messageRateBurstSize << " messageRateDelay = " << i.messageRateDelay
+ << " unlimitedMessageRate = " << i.unlimitedMessageRate << ")";
return dbg.space();
}
-
-QDataStream &operator<<(QDataStream &out, const Network::Server &server)
+QDataStream& operator<<(QDataStream& out, const Network::Server& server)
{
QVariantMap serverMap;
serverMap["Host"] = server.host;
return out;
}
-
-QDataStream &operator>>(QDataStream &in, Network::Server &server)
+QDataStream& operator>>(QDataStream& in, Network::Server& server)
{
QVariantMap serverMap;
in >> serverMap;
return in;
}
-
-bool Network::Server::operator==(const Server &other) const
+bool Network::Server::operator==(const Server& other) const
{
- if (host != other.host) return false;
- if (port != other.port) return false;
- if (password != other.password) return false;
- if (useSsl != other.useSsl) return false;
- if (sslVerify != other.sslVerify) return false;
- if (sslVersion != other.sslVersion) return false;
- if (useProxy != other.useProxy) return false;
- if (proxyType != other.proxyType) return false;
- if (proxyHost != other.proxyHost) return false;
- if (proxyPort != other.proxyPort) return false;
- if (proxyUser != other.proxyUser) return false;
- if (proxyPass != other.proxyPass) return false;
+ if (host != other.host)
+ return false;
+ if (port != other.port)
+ return false;
+ if (password != other.password)
+ return false;
+ if (useSsl != other.useSsl)
+ return false;
+ if (sslVerify != other.sslVerify)
+ return false;
+ if (sslVersion != other.sslVersion)
+ return false;
+ if (useProxy != other.useProxy)
+ return false;
+ if (proxyType != other.proxyType)
+ return false;
+ if (proxyHost != other.proxyHost)
+ return false;
+ if (proxyPort != other.proxyPort)
+ return false;
+ if (proxyUser != other.proxyUser)
+ return false;
+ if (proxyPass != other.proxyPass)
+ return false;
return true;
}
-
-bool Network::Server::operator!=(const Server &other) const
+bool Network::Server::operator!=(const Server& other) const
{
return !(*this == other);
}
-
-QDebug operator<<(QDebug dbg, const Network::Server &server)
+QDebug operator<<(QDebug dbg, const Network::Server& server)
{
- dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " <<
- server.useSsl << ", sslVerify = " << server.sslVerify << ")";
+ dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " << server.useSsl
+ << ", sslVerify = " << server.sslVerify << ")";
return dbg.space();
}
#include "common-export.h"
-#include <QString>
-#include <QStringList>
+#include <utility>
+
+#include <QByteArray>
+#include <QHash>
#include <QList>
+#include <QMutex>
#include <QNetworkProxy>
-#include <QHash>
-#include <QVariantMap>
#include <QPointer>
-#include <QMutex>
-#include <QByteArray>
-#include <utility>
+#include <QString>
+#include <QStringList>
+#include <QVariantMap>
+#include "ircchannel.h"
+#include "ircuser.h"
+#include "signalproxy.h"
+#include "syncableobject.h"
#include "types.h"
#include "util.h"
-#include "syncableobject.h"
-
-#include "signalproxy.h"
-#include "ircuser.h"
-#include "ircchannel.h"
// IRCv3 capabilities
#include "irccap.h"
Q_PROPERTY(QByteArray codecForDecoding READ codecForDecoding WRITE setCodecForDecoding)
Q_PROPERTY(IdentityId identityId READ identity WRITE setIdentity)
Q_PROPERTY(bool isConnected READ isConnected WRITE setConnected)
- //Q_PROPERTY(Network::ConnectionState connectionState READ connectionState WRITE setConnectionState)
+ // Q_PROPERTY(Network::ConnectionState connectionState READ connectionState WRITE setConnectionState)
Q_PROPERTY(int connectionState READ connectionState WRITE setConnectionState)
Q_PROPERTY(bool useRandomServer READ useRandomServer WRITE setUseRandomServer)
Q_PROPERTY(QStringList perform READ perform WRITE setPerform)
Q_PROPERTY(quint32 msgRateMessageDelay READ messageRateDelay WRITE setMessageRateDelay)
Q_PROPERTY(bool unlimitedMessageRate READ unlimitedMessageRate WRITE setUnlimitedMessageRate)
-public :
- enum ConnectionState {
+public:
+ enum ConnectionState
+ {
Disconnected,
Connecting,
Initializing,
// see:
// http://www.irc.org/tech_docs/005.html
// http://www.irc.org/tech_docs/draft-brocklesby-irc-isupport-03.txt
- enum ChannelModeType {
+ enum ChannelModeType
+ {
NOT_A_CHANMODE = 0x00,
A_CHANMODE = 0x01,
B_CHANMODE = 0x02,
// Default port assignments according to what many IRC networks have settled on.
// Technically not a standard, but it's fairly widespread.
// See https://freenode.net/news/port-6697-irc-via-tlsssl
- enum PortDefaults {
- PORT_PLAINTEXT = 6667, /// Default port for unencrypted connections
- PORT_SSL = 6697 /// Default port for encrypted connections
+ enum PortDefaults
+ {
+ PORT_PLAINTEXT = 6667, /// Default port for unencrypted connections
+ PORT_SSL = 6697 /// Default port for encrypted connections
};
- struct Server {
+ struct Server
+ {
QString host;
uint port{6667};
QString password;
bool useSsl{false};
- bool sslVerify{true}; /// If true, validate SSL certificates
+ bool sslVerify{true}; /// If true, validate SSL certificates
int sslVersion{0};
bool useProxy{false};
// sslVerify only applies when useSsl is true. sslVerify should be enabled by default,
// so enabling useSsl offers a more secure default.
- Server() : proxyHost("localhost") {}
-
- Server(QString host, uint port, QString password, bool useSsl,
- bool sslVerify)
- : host(std::move(host)), port(port), password(std::move(password)), useSsl(useSsl), sslVerify(sslVerify),
- proxyType(QNetworkProxy::Socks5Proxy),
- proxyHost("localhost"), proxyPort(8080) {}
-
- bool operator==(const Server &other) const;
- bool operator!=(const Server &other) const;
+ Server()
+ : proxyHost("localhost")
+ {}
+
+ Server(QString host, uint port, QString password, bool useSsl, bool sslVerify)
+ : host(std::move(host))
+ , port(port)
+ , password(std::move(password))
+ , useSsl(useSsl)
+ , sslVerify(sslVerify)
+ , proxyType(QNetworkProxy::Socks5Proxy)
+ , proxyHost("localhost")
+ , proxyPort(8080)
+ {}
+
+ bool operator==(const Server& other) const;
+ bool operator!=(const Server& other) const;
};
using ServerList = QList<Server>;
- Network(const NetworkId &networkid, QObject *parent = nullptr);
+ Network(const NetworkId& networkid, QObject* parent = nullptr);
~Network() override;
inline NetworkId networkId() const { return _networkId; }
- inline SignalProxy *proxy() const { return _proxy; }
- inline void setProxy(SignalProxy *proxy) { _proxy = proxy; }
+ inline SignalProxy* proxy() const { return _proxy; }
+ inline void setProxy(SignalProxy* proxy) { _proxy = proxy; }
- inline bool isMyNick(const QString &nick) const { return (myNick().toLower() == nick.toLower()); }
- inline bool isMe(IrcUser *ircuser) const { return (ircuser->nick().toLower() == myNick().toLower()); }
+ inline bool isMyNick(const QString& nick) const { return (myNick().toLower() == nick.toLower()); }
+ inline bool isMe(IrcUser* ircuser) const { return (ircuser->nick().toLower() == myNick().toLower()); }
- bool isChannelName(const QString &channelname) const;
+ bool isChannelName(const QString& channelname) const;
/**
* Checks if the target counts as a STATUSMSG
* @param[in] target Name of destination, e.g. a channel or query
* @returns True if a STATUSMSG, otherwise false
*/
- bool isStatusMsg(const QString &target) const;
+ bool isStatusMsg(const QString& target) const;
inline bool isConnected() const { return _connected; }
- //Network::ConnectionState connectionState() const;
+ // Network::ConnectionState connectionState() const;
inline int connectionState() const { return _connectionState; }
/**@{*/
* Translates a user’s prefix to the channelmode associated with it.
* @param prefix Prefix to be translated.
*/
- QString prefixToMode(const QString &prefix) const;
- inline QString prefixToMode(const QCharRef &prefix) const { return prefixToMode(QString(prefix)); }
- inline QString prefixesToModes(const QString &prefix) const {
+ QString prefixToMode(const QString& prefix) const;
+ inline QString prefixToMode(const QCharRef& prefix) const { return prefixToMode(QString(prefix)); }
+ inline QString prefixesToModes(const QString& prefix) const
+ {
QString modes;
for (QChar c : prefix) {
modes += prefixToMode(c);
* Translates a user’s prefix to the channelmode associated with it.
* @param prefix Prefix to be translated.
*/
- QString modeToPrefix(const QString &mode) const;
- inline QString modeToPrefix(const QCharRef &mode) const { return modeToPrefix(QString(mode)); }
- inline QString modesToPrefixes(const QString &mode) const {
+ QString modeToPrefix(const QString& mode) const;
+ inline QString modeToPrefix(const QCharRef& mode) const { return modeToPrefix(QString(mode)); }
+ inline QString modesToPrefixes(const QString& mode) const
+ {
QString prefixes;
for (QChar c : mode) {
prefixes += modeToPrefix(c);
* @param modes User channelmodes
* @return Priority-sorted user channelmodes
*/
- QString sortPrefixModes(const QString &modes) const;
+ QString sortPrefixModes(const QString& modes) const;
/**@{*/
/**
* @param modesList List of users' channel modes
* @return Priority-sorted list of users' channel modes
*/
- inline QStringList sortPrefixModes(const QStringList &modesList) const {
+ inline QStringList sortPrefixModes(const QStringList& modesList) const
+ {
QStringList sortedModesList;
// Sort each individual mode string, appending back
// Must maintain the order received!
}
/**@}*/
- ChannelModeType channelModeType(const QString &mode);
- inline ChannelModeType channelModeType(const QCharRef &mode) { return channelModeType(QString(mode)); }
+ ChannelModeType channelModeType(const QString& mode);
+ inline ChannelModeType channelModeType(const QCharRef& mode) { return channelModeType(QString(mode)); }
- inline const QString &networkName() const { return _networkName; }
- inline const QString ¤tServer() const { return _currentServer; }
- inline const QString &myNick() const { return _myNick; }
+ inline const QString& networkName() const { return _networkName; }
+ inline const QString& currentServer() const { return _currentServer; }
+ inline const QString& myNick() const { return _myNick; }
inline int latency() const { return _latency; }
- inline IrcUser *me() const { return ircUser(myNick()); }
+ inline IrcUser* me() const { return ircUser(myNick()); }
inline IdentityId identity() const { return _identity; }
QStringList nicks() const;
inline QStringList channels() const { return _ircChannels.keys(); }
* @returns QStringList of enabled (acknowledged) capabilities
*/
inline const QStringList capsEnabled() const { return _capsEnabled; }
- inline const ServerList &serverList() const { return _serverList; }
+ inline const ServerList& serverList() const { return _serverList; }
inline bool useRandomServer() const { return _useRandomServer; }
- inline const QStringList &perform() const { return _perform; }
+ inline const QStringList& perform() const { return _perform; }
inline bool useAutoIdentify() const { return _useAutoIdentify; }
- inline const QString &autoIdentifyService() const { return _autoIdentifyService; }
- inline const QString &autoIdentifyPassword() const { return _autoIdentifyPassword; }
+ inline const QString& autoIdentifyService() const { return _autoIdentifyService; }
+ inline const QString& autoIdentifyPassword() const { return _autoIdentifyPassword; }
inline bool useSasl() const { return _useSasl; }
- inline const QString &saslAccount() const { return _saslAccount; }
- inline const QString &saslPassword() const { return _saslPassword; }
+ inline const QString& saslAccount() const { return _saslAccount; }
+ inline const QString& saslPassword() const { return _saslPassword; }
inline bool useAutoReconnect() const { return _useAutoReconnect; }
inline quint32 autoReconnectInterval() const { return _autoReconnectInterval; }
inline quint16 autoReconnectRetries() const { return _autoReconnectRetries; }
inline bool unlimitedMessageRate() const { return _unlimitedMessageRate; }
NetworkInfo networkInfo() const;
- void setNetworkInfo(const NetworkInfo &);
+ void setNetworkInfo(const NetworkInfo&);
QString prefixes() const;
QString prefixModes() const;
void determinePrefixes() const;
- bool supports(const QString ¶m) const { return _supports.contains(param); }
- QString support(const QString ¶m) const;
+ bool supports(const QString& param) const { return _supports.contains(param); }
+ QString support(const QString& param) const;
/**
* Checks if a given capability is advertised by the server.
* @param[in] capability Name of capability
* @returns True if connected and advertised by the server, otherwise false
*/
- inline bool capAvailable(const QString &capability) const { return _caps.contains(capability.toLower()); }
+ inline bool capAvailable(const QString& capability) const { return _caps.contains(capability.toLower()); }
// IRCv3 specs all use lowercase capability names
/**
* @param[in] capability Name of capability
* @returns True if acknowledged (active), otherwise false
*/
- inline bool capEnabled(const QString &capability) const { return _capsEnabled.contains(capability.toLower()); }
+ inline bool capEnabled(const QString& capability) const { return _capsEnabled.contains(capability.toLower()); }
// IRCv3 specs all use lowercase capability names
/**
* @param[in] capability Name of capability
* @returns Value of capability if one was specified, otherwise empty string
*/
- QString capValue(const QString &capability) const { return _caps.value(capability.toLower()); }
+ QString capValue(const QString& capability) const { return _caps.value(capability.toLower()); }
// IRCv3 specs all use lowercase capability names
// QHash returns the default constructed value if not found, in this case, empty string
// See: https://doc.qt.io/qt-4.8/qhash.html#value
* @param[in] saslMechanism Desired SASL mechanism
* @return True if mechanism supported or unknown, otherwise false
*/
- bool saslMaybeSupports(const QString &saslMechanism) const;
+ bool saslMaybeSupports(const QString& saslMechanism) const;
- IrcUser *newIrcUser(const QString &hostmask, const QVariantMap &initData = QVariantMap());
- inline IrcUser *newIrcUser(const QByteArray &hostmask) { return newIrcUser(decodeServerString(hostmask)); }
- IrcUser *ircUser(QString nickname) const;
- inline IrcUser *ircUser(const QByteArray &nickname) const { return ircUser(decodeServerString(nickname)); }
- inline QList<IrcUser *> ircUsers() const { return _ircUsers.values(); }
+ IrcUser* newIrcUser(const QString& hostmask, const QVariantMap& initData = QVariantMap());
+ inline IrcUser* newIrcUser(const QByteArray& hostmask) { return newIrcUser(decodeServerString(hostmask)); }
+ IrcUser* ircUser(QString nickname) const;
+ inline IrcUser* ircUser(const QByteArray& nickname) const { return ircUser(decodeServerString(nickname)); }
+ inline QList<IrcUser*> ircUsers() const { return _ircUsers.values(); }
inline quint32 ircUserCount() const { return _ircUsers.count(); }
- IrcChannel *newIrcChannel(const QString &channelname, const QVariantMap &initData = QVariantMap());
- inline IrcChannel *newIrcChannel(const QByteArray &channelname) { return newIrcChannel(decodeServerString(channelname)); }
- IrcChannel *ircChannel(QString channelname) const;
- inline IrcChannel *ircChannel(const QByteArray &channelname) const { return ircChannel(decodeServerString(channelname)); }
- inline QList<IrcChannel *> ircChannels() const { return _ircChannels.values(); }
+ IrcChannel* newIrcChannel(const QString& channelname, const QVariantMap& initData = QVariantMap());
+ inline IrcChannel* newIrcChannel(const QByteArray& channelname) { return newIrcChannel(decodeServerString(channelname)); }
+ IrcChannel* ircChannel(QString channelname) const;
+ inline IrcChannel* ircChannel(const QByteArray& channelname) const { return ircChannel(decodeServerString(channelname)); }
+ inline QList<IrcChannel*> ircChannels() const { return _ircChannels.values(); }
inline quint32 ircChannelCount() const { return _ircChannels.count(); }
QByteArray codecForServer() const;
QByteArray codecForEncoding() const;
QByteArray codecForDecoding() const;
- void setCodecForServer(QTextCodec *codec);
- void setCodecForEncoding(QTextCodec *codec);
- void setCodecForDecoding(QTextCodec *codec);
+ void setCodecForServer(QTextCodec* codec);
+ void setCodecForEncoding(QTextCodec* codec);
+ void setCodecForDecoding(QTextCodec* codec);
- QString decodeString(const QByteArray &text) const;
- QByteArray encodeString(const QString &string) const;
- QString decodeServerString(const QByteArray &text) const;
- QByteArray encodeServerString(const QString &string) const;
+ QString decodeString(const QByteArray& text) const;
+ QByteArray encodeString(const QString& string) const;
+ QString decodeServerString(const QByteArray& text) const;
+ QByteArray encodeServerString(const QString& string) const;
static QByteArray defaultCodecForServer();
static QByteArray defaultCodecForEncoding();
static QByteArray defaultCodecForDecoding();
- static void setDefaultCodecForServer(const QByteArray &name);
- static void setDefaultCodecForEncoding(const QByteArray &name);
- static void setDefaultCodecForDecoding(const QByteArray &name);
+ static void setDefaultCodecForServer(const QByteArray& name);
+ static void setDefaultCodecForEncoding(const QByteArray& name);
+ static void setDefaultCodecForDecoding(const QByteArray& name);
inline bool autoAwayActive() const { return _autoAwayActive; }
inline void setAutoAwayActive(bool active) { _autoAwayActive = active; }
public slots:
- void setNetworkName(const QString &networkName);
- void setCurrentServer(const QString ¤tServer);
+ void setNetworkName(const QString& networkName);
+ void setCurrentServer(const QString& currentServer);
void setConnected(bool isConnected);
void setConnectionState(int state);
- virtual void setMyNick(const QString &mynick);
+ virtual void setMyNick(const QString& mynick);
void setLatency(int latency);
void setIdentity(IdentityId);
- void setServerList(const QVariantList &serverList);
+ void setServerList(const QVariantList& serverList);
void setUseRandomServer(bool);
- void setPerform(const QStringList &);
+ void setPerform(const QStringList&);
void setUseAutoIdentify(bool);
- void setAutoIdentifyService(const QString &);
- void setAutoIdentifyPassword(const QString &);
+ void setAutoIdentifyService(const QString&);
+ void setAutoIdentifyPassword(const QString&);
void setUseSasl(bool);
- void setSaslAccount(const QString &);
- void setSaslPassword(const QString &);
+ void setSaslAccount(const QString&);
+ void setSaslPassword(const QString&);
virtual void setUseAutoReconnect(bool);
virtual void setAutoReconnectInterval(quint32);
virtual void setAutoReconnectRetries(quint16);
*/
void setUnlimitedMessageRate(bool unlimitedRate);
- void setCodecForServer(const QByteArray &codecName);
- void setCodecForEncoding(const QByteArray &codecName);
- void setCodecForDecoding(const QByteArray &codecName);
+ void setCodecForServer(const QByteArray& codecName);
+ void setCodecForEncoding(const QByteArray& codecName);
+ void setCodecForDecoding(const QByteArray& codecName);
- void addSupport(const QString ¶m, const QString &value = QString());
- void removeSupport(const QString ¶m);
+ void addSupport(const QString& param, const QString& value = QString());
+ void removeSupport(const QString& param);
// IRCv3 capability negotiation (can be connected to signals)
* Optional value of the capability, e.g. sasl=plain.
* @endparblock
*/
- void addCap(const QString &capability, const QString &value = QString());
+ void addCap(const QString& capability, const QString& value = QString());
/**
* Marks a capability as acknowledged (enabled by the IRC server).
*
* @param[in] capability Name of the capability
*/
- void acknowledgeCap(const QString &capability);
+ void acknowledgeCap(const QString& capability);
/**
* Removes a capability from the list of available capabilities.
*
* @param[in] capability Name of the capability
*/
- void removeCap(const QString &capability);
+ void removeCap(const QString& capability);
/**
* Clears all capabilities from the list of available capabilities.
*/
void clearCaps();
- inline void addIrcUser(const QString &hostmask) { newIrcUser(hostmask); }
- inline void addIrcChannel(const QString &channel) { newIrcChannel(channel); }
+ inline void addIrcUser(const QString& hostmask) { newIrcUser(hostmask); }
+ inline void addIrcChannel(const QString& channel) { newIrcChannel(channel); }
- //init geters
+ // init geters
QVariantMap initSupports() const;
/**
* Get the initial list of available capabilities.
inline QVariantList initServerList() const { return toVariantList(serverList()); }
virtual QVariantMap initIrcUsersAndChannels() const;
- //init seters
- void initSetSupports(const QVariantMap &supports);
+ // init seters
+ void initSetSupports(const QVariantMap& supports);
/**
* Initialize the list of available capabilities.
*
* @param[in] caps QVariantMap of <QString, QString> indicating available capabilities and values
*/
- void initSetCaps(const QVariantMap &caps);
+ void initSetCaps(const QVariantMap& caps);
/**
* Initialize the list of enabled (acknowledged) capabilities.
*
* @param[in] caps QVariantList of QString indicating enabled (acknowledged) capabilities and values
*/
- inline void initSetCapsEnabled(const QVariantList &capsEnabled) { _capsEnabled = fromVariantList<QString>(capsEnabled); }
- inline void initSetServerList(const QVariantList &serverList) { _serverList = fromVariantList<Server>(serverList); }
- virtual void initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels);
+ inline void initSetCapsEnabled(const QVariantList& capsEnabled) { _capsEnabled = fromVariantList<QString>(capsEnabled); }
+ inline void initSetServerList(const QVariantList& serverList) { _serverList = fromVariantList<Server>(serverList); }
+ virtual void initSetIrcUsersAndChannels(const QVariantMap& usersAndChannels);
/**
* Update IrcUser hostmask and username from mask, creating an IrcUser if one does not exist.
* @param[in] mask Full nick!user@hostmask string
* @return IrcUser of the matching nick if exists, otherwise a new IrcUser
*/
- IrcUser *updateNickFromMask(const QString &mask);
+ IrcUser* updateNickFromMask(const QString& mask);
// these slots are to keep the hashlists of all users and the
// channel lists up to date
virtual inline void requestConnect() const { REQUEST(NO_ARG) }
virtual inline void requestDisconnect() const { REQUEST(NO_ARG) }
- virtual inline void requestSetNetworkInfo(const NetworkInfo &info) { REQUEST(ARG(info)) }
+ virtual inline void requestSetNetworkInfo(const NetworkInfo& info) { REQUEST(ARG(info)) }
- void emitConnectionError(const QString &);
+ void emitConnectionError(const QString&);
protected slots:
- virtual void removeIrcUser(IrcUser *ircuser);
- virtual void removeIrcChannel(IrcChannel *ircChannel);
+ virtual void removeIrcUser(IrcUser* ircuser);
+ virtual void removeIrcChannel(IrcChannel* ircChannel);
virtual void removeChansAndUsers();
signals:
void aboutToBeDestroyed();
- void networkNameSet(const QString &networkName);
- void currentServerSet(const QString ¤tServer);
+ void networkNameSet(const QString& networkName);
+ void currentServerSet(const QString& currentServer);
void connectedSet(bool isConnected);
void connectionStateSet(Network::ConnectionState);
-// void connectionStateSet(int);
- void connectionError(const QString &errorMsg);
- void myNickSet(const QString &mynick);
-// void latencySet(int latency);
+ // void connectionStateSet(int);
+ void connectionError(const QString& errorMsg);
+ void myNickSet(const QString& mynick);
+ // void latencySet(int latency);
void identitySet(IdentityId);
void configChanged();
// void serverListSet(QVariantList serverList);
-// void useRandomServerSet(bool);
-// void performSet(const QStringList &);
-// void useAutoIdentifySet(bool);
-// void autoIdentifyServiceSet(const QString &);
-// void autoIdentifyPasswordSet(const QString &);
-// void useAutoReconnectSet(bool);
-// void autoReconnectIntervalSet(quint32);
-// void autoReconnectRetriesSet(quint16);
-// void unlimitedReconnectRetriesSet(bool);
-// void rejoinChannelsSet(bool);
+ // void useRandomServerSet(bool);
+ // void performSet(const QStringList &);
+ // void useAutoIdentifySet(bool);
+ // void autoIdentifyServiceSet(const QString &);
+ // void autoIdentifyPasswordSet(const QString &);
+ // void useAutoReconnectSet(bool);
+ // void autoReconnectIntervalSet(quint32);
+ // void autoReconnectRetriesSet(quint16);
+ // void unlimitedReconnectRetriesSet(bool);
+ // void rejoinChannelsSet(bool);
// Custom rate limiting (can drive other slots)
*/
void unlimitedMessageRateSet(const bool unlimitedRate);
-// void codecForServerSet(const QByteArray &codecName);
-// void codecForEncodingSet(const QByteArray &codecName);
-// void codecForDecodingSet(const QByteArray &codecName);
+ // void codecForServerSet(const QByteArray &codecName);
+ // void codecForEncodingSet(const QByteArray &codecName);
+ // void codecForDecodingSet(const QByteArray &codecName);
-// void supportAdded(const QString ¶m, const QString &value);
-// void supportRemoved(const QString ¶m);
+ // void supportAdded(const QString ¶m, const QString &value);
+ // void supportRemoved(const QString ¶m);
// IRCv3 capability negotiation (can drive other slots)
/**
*
* @param[in] capability Name of the capability
*/
- void capAdded (const QString &capability);
+ void capAdded(const QString& capability);
/**
* Indicates a capability was acknowledged (enabled by the IRC server).
*
* @param[in] capability Name of the capability
*/
- void capAcknowledged(const QString &capability);
+ void capAcknowledged(const QString& capability);
/**
* Indicates a capability was removed from the list of available capabilities.
*
* @param[in] capability Name of the capability
*/
- void capRemoved(const QString &capability);
+ void capRemoved(const QString& capability);
-// void ircUserAdded(const QString &hostmask);
- void ircUserAdded(IrcUser *);
-// void ircChannelAdded(const QString &channelname);
- void ircChannelAdded(IrcChannel *);
+ // void ircUserAdded(const QString &hostmask);
+ void ircUserAdded(IrcUser*);
+ // void ircChannelAdded(const QString &channelname);
+ void ircChannelAdded(IrcChannel*);
-// void connectRequested() const;
-// void disconnectRequested() const;
-// void setNetworkInfoRequested(const NetworkInfo &) const;
+ // void connectRequested() const;
+ // void disconnectRequested() const;
+ // void setNetworkInfoRequested(const NetworkInfo &) const;
protected:
- inline virtual IrcChannel *ircChannelFactory(const QString &channelname) { return new IrcChannel(channelname, this); }
- inline virtual IrcUser *ircUserFactory(const QString &hostmask) { return new IrcUser(hostmask, this); }
+ inline virtual IrcChannel* ircChannelFactory(const QString& channelname) { return new IrcChannel(channelname, this); }
+ inline virtual IrcUser* ircUserFactory(const QString& hostmask) { return new IrcUser(hostmask, this); }
private:
QPointer<SignalProxy> _proxy;
mutable QString _prefixes;
mutable QString _prefixModes;
- QHash<QString, IrcUser *> _ircUsers; // stores all known nicks for the server
- QHash<QString, IrcChannel *> _ircChannels; // stores all known channels
- QHash<QString, QString> _supports; // stores results from RPL_ISUPPORT
+ QHash<QString, IrcUser*> _ircUsers; // stores all known nicks for the server
+ QHash<QString, IrcChannel*> _ircChannels; // stores all known channels
+ QHash<QString, QString> _supports; // stores results from RPL_ISUPPORT
QHash<QString, QString> _caps; /// Capabilities supported by the IRC server
// By synchronizing the supported capabilities, the client could suggest certain behaviors, e.g.
// in the Network settings dialog, recommending SASL instead of using NickServ, or warning if
// SASL EXTERNAL isn't available.
- QStringList _capsEnabled; /// Enabled capabilities that received 'CAP ACK'
+ QStringList _capsEnabled; /// Enabled capabilities that received 'CAP ACK'
// _capsEnabled uses the same values from the <name>=<value> pairs stored in _caps
ServerList _serverList;
bool _rejoinChannels;
// Custom rate limiting
- bool _useCustomMessageRate; /// If true, use custom rate limits, otherwise use defaults
- quint32 _messageRateBurstSize; /// Maximum number of messages to send without any delays
- quint32 _messageRateDelay; /// Delay in ms. for messages when max. burst messages sent
- bool _unlimitedMessageRate; /// If true, disable rate limiting, otherwise apply limits
+ bool _useCustomMessageRate; /// If true, use custom rate limits, otherwise use defaults
+ quint32 _messageRateBurstSize; /// Maximum number of messages to send without any delays
+ quint32 _messageRateDelay; /// Delay in ms. for messages when max. burst messages sent
+ bool _unlimitedMessageRate; /// If true, disable rate limiting, otherwise apply limits
- QTextCodec *_codecForServer;
- QTextCodec *_codecForEncoding;
- QTextCodec *_codecForDecoding;
+ QTextCodec* _codecForServer;
+ QTextCodec* _codecForEncoding;
+ QTextCodec* _codecForDecoding;
- static QTextCodec *_defaultCodecForServer;
- static QTextCodec *_defaultCodecForEncoding;
- static QTextCodec *_defaultCodecForDecoding;
+ static QTextCodec* _defaultCodecForServer;
+ static QTextCodec* _defaultCodecForEncoding;
+ static QTextCodec* _defaultCodecForDecoding;
- bool _autoAwayActive; // when this is active handle305 and handle306 don't trigger any output
+ bool _autoAwayActive; // when this is active handle305 and handle306 don't trigger any output
friend class IrcUser;
friend class IrcChannel;
};
-
//! Stores all editable information about a network (as opposed to runtime state).
struct COMMON_EXPORT NetworkInfo
{
QByteArray codecForEncoding;
QByteArray codecForDecoding;
- NetworkId networkId {0};
- IdentityId identity {1};
+ NetworkId networkId{0};
+ IdentityId identity{1};
- quint32 messageRateBurstSize {5}; ///< Maximum number of messages to send without any delays
- quint32 messageRateDelay {2200}; ///< Delay in ms. for messages when max. burst messages sent
+ quint32 messageRateBurstSize{5}; ///< Maximum number of messages to send without any delays
+ quint32 messageRateDelay{2200}; ///< Delay in ms. for messages when max. burst messages sent
- quint32 autoReconnectInterval {60};
- quint16 autoReconnectRetries {20};
+ quint32 autoReconnectInterval{60};
+ quint16 autoReconnectRetries{20};
- bool rejoinChannels {true};
- bool useRandomServer {false};
- bool useAutoIdentify {false};
- bool useSasl {false};
- bool useAutoReconnect {true};
- bool unlimitedReconnectRetries {false};
- bool useCustomMessageRate {false}; ///< If true, use custom rate limits, otherwise use defaults
- bool unlimitedMessageRate {false}; ///< If true, disable rate limiting, otherwise apply limits
+ bool rejoinChannels{true};
+ bool useRandomServer{false};
+ bool useAutoIdentify{false};
+ bool useSasl{false};
+ bool useAutoReconnect{true};
+ bool unlimitedReconnectRetries{false};
+ bool useCustomMessageRate{false}; ///< If true, use custom rate limits, otherwise use defaults
+ bool unlimitedMessageRate{false}; ///< If true, disable rate limiting, otherwise apply limits
public:
- bool operator==(const NetworkInfo &other) const;
- bool operator!=(const NetworkInfo &other) const;
+ bool operator==(const NetworkInfo& other) const;
+ bool operator!=(const NetworkInfo& other) const;
};
-COMMON_EXPORT QDataStream &operator<<(QDataStream &out, const NetworkInfo &info);
-COMMON_EXPORT QDataStream &operator>>(QDataStream &in, NetworkInfo &info);
-COMMON_EXPORT QDebug operator<<(QDebug dbg, const NetworkInfo &i);
+COMMON_EXPORT QDataStream& operator<<(QDataStream& out, const NetworkInfo& info);
+COMMON_EXPORT QDataStream& operator>>(QDataStream& in, NetworkInfo& info);
+COMMON_EXPORT QDebug operator<<(QDebug dbg, const NetworkInfo& i);
Q_DECLARE_METATYPE(NetworkInfo)
-COMMON_EXPORT QDataStream &operator<<(QDataStream &out, const Network::Server &server);
-COMMON_EXPORT QDataStream &operator>>(QDataStream &in, Network::Server &server);
-COMMON_EXPORT QDebug operator<<(QDebug dbg, const Network::Server &server);
+COMMON_EXPORT QDataStream& operator<<(QDataStream& out, const Network::Server& server);
+COMMON_EXPORT QDataStream& operator>>(QDataStream& in, Network::Server& server);
+COMMON_EXPORT QDebug operator<<(QDebug dbg, const Network::Server& server);
Q_DECLARE_METATYPE(Network::Server)
#include "networkconfig.h"
-NetworkConfig::NetworkConfig(const QString &objectName, QObject *parent)
+NetworkConfig::NetworkConfig(const QString& objectName, QObject* parent)
: SyncableObject(objectName, parent)
-{
-}
-
+{}
void NetworkConfig::setPingTimeoutEnabled(bool enabled)
{
emit pingTimeoutEnabledSet(enabled);
}
-
void NetworkConfig::setPingInterval(int interval)
{
if (_pingInterval == interval)
emit pingIntervalSet(interval);
}
-
void NetworkConfig::setMaxPingCount(int count)
{
if (_maxPingCount == count)
SYNC(ARG(count))
}
-
void NetworkConfig::setAutoWhoEnabled(bool enabled)
{
if (_autoWhoEnabled == enabled)
emit autoWhoEnabledSet(enabled);
}
-
void NetworkConfig::setAutoWhoInterval(int interval)
{
if (_autoWhoInterval == interval)
emit autoWhoIntervalSet(interval);
}
-
void NetworkConfig::setAutoWhoNickLimit(int nickLimit)
{
if (_autoWhoNickLimit == nickLimit)
SYNC(ARG(nickLimit))
}
-
void NetworkConfig::setAutoWhoDelay(int delay)
{
if (_autoWhoDelay == delay)
emit autoWhoDelaySet(delay);
}
-
void NetworkConfig::setStandardCtcp(bool enabled)
{
if (_standardCtcp == enabled)
Q_PROPERTY(int autoWhoDelay READ autoWhoDelay WRITE setAutoWhoDelay)
Q_PROPERTY(bool standardCtcp READ standardCtcp WRITE setStandardCtcp)
-public :
- NetworkConfig(const QString &objectName = "GlobalNetworkConfig", QObject *parent = nullptr);
+public:
+ NetworkConfig(const QString& objectName = "GlobalNetworkConfig", QObject* parent = nullptr);
public slots:
inline bool pingTimeoutEnabled() const { return _pingTimeoutEnabled; }
inline bool standardCtcp() const { return _standardCtcp; }
void setStandardCtcp(bool);
- virtual inline void requestSetStandardCtcp(bool b) { REQUEST(ARG(b)) }
+ virtual inline void requestSetStandardCtcp(bool b){REQUEST(ARG(b))}
-signals:
- void pingTimeoutEnabledSet(bool);
+ signals : void pingTimeoutEnabledSet(bool);
void pingIntervalSet(int);
-// void maxPingCountSet(int);
+ // void maxPingCountSet(int);
void autoWhoEnabledSet(bool);
void autoWhoIntervalSet(int);
-// void autoWhoNickLimitSet(int);
+ // void autoWhoNickLimitSet(int);
void autoWhoDelaySet(int);
void standardCtcpSet(bool);
-// void setPingTimeoutEnabledRequested(bool);
-// void setPingIntervalRequested(int);
-// void setMaxPingCountRequested(int);
-// void setAutoWhoEnabledRequested(bool);
-// void setAutoWhoIntervalRequested(int);
-// void setAutoWhoNickLimitRequested(int);
-// void setAutoWhoDelayRequested(int);
+ // void setPingTimeoutEnabledRequested(bool);
+ // void setPingIntervalRequested(int);
+ // void setMaxPingCountRequested(int);
+ // void setAutoWhoEnabledRequested(bool);
+ // void setAutoWhoIntervalRequested(int);
+ // void setAutoWhoNickLimitRequested(int);
+ // void setAutoWhoDelayRequested(int);
private:
bool _pingTimeoutEnabled{true};
#include "networkevent.h"
-Event *NetworkEvent::create(EventManager::EventType type, QVariantMap &map, Network *network)
+Event* NetworkEvent::create(EventManager::EventType type, QVariantMap& map, Network* network)
{
switch (type) {
case EventManager::NetworkIncoming:
}
}
-
-NetworkEvent::NetworkEvent(EventManager::EventType type, QVariantMap &map, Network *network)
+NetworkEvent::NetworkEvent(EventManager::EventType type, QVariantMap& map, Network* network)
: Event(type, map)
, _network(network)
-{
-}
+{}
-
-void NetworkEvent::toVariantMap(QVariantMap &map) const
+void NetworkEvent::toVariantMap(QVariantMap& map) const
{
Event::toVariantMap(map);
map["network"] = networkId().toInt();
}
-
-NetworkDataEvent::NetworkDataEvent(EventManager::EventType type, QVariantMap &map, Network *network)
+NetworkDataEvent::NetworkDataEvent(EventManager::EventType type, QVariantMap& map, Network* network)
: NetworkEvent(type, map, network)
{
_data = map.take("data").toByteArray();
}
-
-void NetworkDataEvent::toVariantMap(QVariantMap &map) const
+void NetworkDataEvent::toVariantMap(QVariantMap& map) const
{
NetworkEvent::toVariantMap(map);
map["data"] = data();
}
-
-NetworkConnectionEvent::NetworkConnectionEvent(EventManager::EventType type, QVariantMap &map, Network *network)
+NetworkConnectionEvent::NetworkConnectionEvent(EventManager::EventType type, QVariantMap& map, Network* network)
: NetworkEvent(type, map, network)
{
- _state = static_cast<Network::ConnectionState>(map.take("state").toInt()); // FIXME: check enum plausibility
+ _state = static_cast<Network::ConnectionState>(map.take("state").toInt()); // FIXME: check enum plausibility
}
-
-void NetworkConnectionEvent::toVariantMap(QVariantMap &map) const
+void NetworkConnectionEvent::toVariantMap(QVariantMap& map) const
{
NetworkEvent::toVariantMap(map);
map["state"] = connectionState();
}
-
-NetworkSplitEvent::NetworkSplitEvent(EventManager::EventType type, QVariantMap &map, Network *network)
+NetworkSplitEvent::NetworkSplitEvent(EventManager::EventType type, QVariantMap& map, Network* network)
: NetworkEvent(type, map, network)
{
_channel = map.take("channel").toString();
_quitMsg = map.take("quitMessage").toString();
}
-
-void NetworkSplitEvent::toVariantMap(QVariantMap &map) const
+void NetworkSplitEvent::toVariantMap(QVariantMap& map) const
{
NetworkEvent::toVariantMap(map);
map["channel"] = channel();
#pragma once
+#include <utility>
+
#include <QStringList>
#include <QVariantList>
-#include <utility>
#include "event.h"
#include "network.h"
class COMMON_EXPORT NetworkEvent : public Event
{
public:
- explicit NetworkEvent(EventManager::EventType type, Network *network)
- : Event(type),
- _network(network)
+ explicit NetworkEvent(EventManager::EventType type, Network* network)
+ : Event(type)
+ , _network(network)
{}
inline NetworkId networkId() const { return network() ? network()->networkId() : NetworkId(); }
- inline Network *network() const { return _network; }
+ inline Network* network() const { return _network; }
- static Event *create(EventManager::EventType type, QVariantMap &map, Network *network);
+ static Event* create(EventManager::EventType type, QVariantMap& map, Network* network);
protected:
- explicit NetworkEvent(EventManager::EventType type, QVariantMap &map, Network *network);
- void toVariantMap(QVariantMap &map) const override;
+ explicit NetworkEvent(EventManager::EventType type, QVariantMap& map, Network* network);
+ void toVariantMap(QVariantMap& map) const override;
inline QString className() const override { return "NetworkEvent"; }
- inline void debugInfo(QDebug &dbg) const override { dbg.nospace() << ", net = " << qPrintable(_network->networkName()); }
+ inline void debugInfo(QDebug& dbg) const override { dbg.nospace() << ", net = " << qPrintable(_network->networkName()); }
private:
- Network *_network;
+ Network* _network;
};
-
/*****************************************************************************/
class COMMON_EXPORT NetworkConnectionEvent : public NetworkEvent
{
public:
- explicit NetworkConnectionEvent(EventManager::EventType type, Network *network, Network::ConnectionState state)
- : NetworkEvent(type, network),
- _state(state)
+ explicit NetworkConnectionEvent(EventManager::EventType type, Network* network, Network::ConnectionState state)
+ : NetworkEvent(type, network)
+ , _state(state)
{}
inline Network::ConnectionState connectionState() const { return _state; }
inline void setConnectionState(Network::ConnectionState state) { _state = state; }
protected:
- explicit NetworkConnectionEvent(EventManager::EventType type, QVariantMap &map, Network *network);
- void toVariantMap(QVariantMap &map) const override;
+ explicit NetworkConnectionEvent(EventManager::EventType type, QVariantMap& map, Network* network);
+ void toVariantMap(QVariantMap& map) const override;
inline QString className() const override { return "NetworkConnectionEvent"; }
- inline void debugInfo(QDebug &dbg) const override
+ inline void debugInfo(QDebug& dbg) const override
{
NetworkEvent::debugInfo(dbg);
dbg.nospace() << ", state = " << qPrintable(QString::number(_state));
}
-
private:
Network::ConnectionState _state;
friend class NetworkEvent;
};
-
class COMMON_EXPORT NetworkDataEvent : public NetworkEvent
{
public:
- explicit NetworkDataEvent(EventManager::EventType type, Network *network, QByteArray data)
- : NetworkEvent(type, network),
- _data(std::move(data))
+ explicit NetworkDataEvent(EventManager::EventType type, Network* network, QByteArray data)
+ : NetworkEvent(type, network)
+ , _data(std::move(data))
{}
inline QByteArray data() const { return _data; }
- inline void setData(const QByteArray &data) { _data = data; }
+ inline void setData(const QByteArray& data) { _data = data; }
protected:
- explicit NetworkDataEvent(EventManager::EventType type, QVariantMap &map, Network *network);
- void toVariantMap(QVariantMap &map) const override;
+ explicit NetworkDataEvent(EventManager::EventType type, QVariantMap& map, Network* network);
+ void toVariantMap(QVariantMap& map) const override;
inline QString className() const override { return "NetworkDataEvent"; }
- inline void debugInfo(QDebug &dbg) const override
+ inline void debugInfo(QDebug& dbg) const override
{
NetworkEvent::debugInfo(dbg);
dbg.nospace() << ", data = " << data();
}
-
private:
QByteArray _data;
friend class NetworkEvent;
};
-
class COMMON_EXPORT NetworkSplitEvent : public NetworkEvent
{
public:
- explicit NetworkSplitEvent(EventManager::EventType type,
- Network *network,
- QString channel,
- QStringList users,
- QString quitMsg)
- : NetworkEvent(type, network),
- _channel(std::move(channel)),
- _users(std::move(users)),
- _quitMsg(std::move(quitMsg))
+ explicit NetworkSplitEvent(EventManager::EventType type, Network* network, QString channel, QStringList users, QString quitMsg)
+ : NetworkEvent(type, network)
+ , _channel(std::move(channel))
+ , _users(std::move(users))
+ , _quitMsg(std::move(quitMsg))
{}
inline QString channel() const { return _channel; }
inline QString quitMessage() const { return _quitMsg; }
protected:
- explicit NetworkSplitEvent(EventManager::EventType type, QVariantMap &map, Network *network);
- void toVariantMap(QVariantMap &map) const override;
+ explicit NetworkSplitEvent(EventManager::EventType type, QVariantMap& map, Network* network);
+ void toVariantMap(QVariantMap& map) const override;
inline QString className() const override { return "NetworkSplitEvent"; }
- inline void debugInfo(QDebug &dbg) const override
+ inline void debugInfo(QDebug& dbg) const override
{
NetworkEvent::debugInfo(dbg);
- dbg.nospace() << ", channel = " << qPrintable(channel())
- << ", users = " << users()
- << ", quitmsg = " << quitMessage();
+ dbg.nospace() << ", channel = " << qPrintable(channel()) << ", users = " << users() << ", quitmsg = " << quitMessage();
}
-
private:
QString _channel;
QStringList _users;
#include <QString>
#include <QStringList>
-bool NickHighlightMatcher::match(const QString &string, const NetworkId &netId,
- const QString ¤tNick, const QStringList &identityNicks) const
+bool NickHighlightMatcher::match(const QString& string, const NetworkId& netId, const QString& currentNick, const QStringList& identityNicks) const
{
// Never match for no nicknames
if (_highlightMode == HighlightNickType::NoNick) {
determineExpressions(netId, currentNick, identityNicks);
// Check for a match
- if (_nickMatchCache[netId].matcher.isValid()
- && _nickMatchCache[netId].matcher.match(string)) {
+ if (_nickMatchCache[netId].matcher.isValid() && _nickMatchCache[netId].matcher.match(string)) {
// Nick matcher is valid and match found
return true;
}
return false;
}
-
-void NickHighlightMatcher::determineExpressions(const NetworkId &netId, const QString ¤tNick,
- const QStringList &identityNicks) const
+void NickHighlightMatcher::determineExpressions(const NetworkId& netId, const QString& currentNick, const QStringList& identityNicks) const
{
// Don't do anything for no nicknames
if (_highlightMode == HighlightNickType::NoNick) {
}
// Only update if needed (check nickname config, current nick, identity nicks for change)
- if (_nickMatchCache.contains(netId)
- && _nickMatchCache[netId].nickCurrent == currentNick
- && _nickMatchCache[netId].identityNicks == identityNicks) {
+ if (_nickMatchCache.contains(netId) && _nickMatchCache[netId].nickCurrent == currentNick
+ && _nickMatchCache[netId].identityNicks == identityNicks) {
return;
}
}
// Set up phrase matcher, joining with newlines
- _nickMatchCache[netId].matcher =
- ExpressionMatch(nickList.join("\n"), ExpressionMatch::MatchMode::MatchMultiPhrase,
- _isCaseSensitive);
+ _nickMatchCache[netId].matcher = ExpressionMatch(nickList.join("\n"), ExpressionMatch::MatchMode::MatchMultiPhrase, _isCaseSensitive);
_nickMatchCache[netId].nickCurrent = currentNick;
_nickMatchCache[netId].identityNicks = identityNicks;
{
public:
/// Nickname highlighting mode
- enum class HighlightNickType {
- NoNick = 0x00, ///< Don't match any nickname
- CurrentNick = 0x01, ///< Match the current nickname
- AllNicks = 0x02 ///< Match all configured nicknames in the chosen identity
+ enum class HighlightNickType
+ {
+ NoNick = 0x00, ///< Don't match any nickname
+ CurrentNick = 0x01, ///< Match the current nickname
+ AllNicks = 0x02 ///< Match all configured nicknames in the chosen identity
};
// NOTE: Keep this in sync with HighlightRuleManager::HighlightNickType and
// NotificationSettings::HighlightNickType!
* @param isCaseSensitive If true, nick matching is case-sensitive, otherwise case-insensitive
*/
NickHighlightMatcher(HighlightNickType highlightMode, bool isCaseSensitive)
- : _highlightMode(highlightMode),
- _isCaseSensitive(isCaseSensitive) {}
+ : _highlightMode(highlightMode)
+ , _isCaseSensitive(isCaseSensitive)
+ {}
/**
* Gets the nickname highlighting policy
*
* @param highlightMode Nickname highlighting mode
*/
- void setHighlightMode(HighlightNickType highlightMode) {
+ void setHighlightMode(HighlightNickType highlightMode)
+ {
if (_highlightMode != highlightMode) {
_highlightMode = highlightMode;
invalidateNickCache();
*
* @param isCaseSensitive If true, nick matching is case-sensitive, otherwise case-insensitive
*/
- void setCaseSensitive(bool isCaseSensitive) {
+ void setCaseSensitive(bool isCaseSensitive)
+ {
if (_isCaseSensitive != isCaseSensitive) {
_isCaseSensitive = isCaseSensitive;
invalidateNickCache();
* @param identityNicks All nicknames configured for the current identity
* @return True if match found, otherwise false
*/
- bool match(const QString &string, const NetworkId &netId, const QString ¤tNick,
- const QStringList &identityNicks) const;
+ bool match(const QString& string, const NetworkId& netId, const QString& currentNick, const QStringList& identityNicks) const;
public slots:
/**
*
* @param netId Network ID of source network
*/
- void removeNetwork(const NetworkId &netId) {
+ void removeNetwork(const NetworkId& netId)
+ {
// Remove the network from the cache list
if (_nickMatchCache.remove(netId) > 0) {
qDebug() << "Cleared nickname matching cache for removed network ID" << netId;
}
private:
- struct NickMatchCache {
+ struct NickMatchCache
+ {
// These represent internal cache and should be safe to mutate in 'const' functions
QString nickCurrent = {}; ///< Last cached current nick
QStringList identityNicks = {}; ///< Last cached identity nicks
* @param currentNick Current nickname
* @param identityNicks All nicknames configured for the current identity
*/
- void determineExpressions(const NetworkId &netId, const QString ¤tNick,
- const QStringList &identityNicks) const;
+ void determineExpressions(const NetworkId& netId, const QString& currentNick, const QStringList& identityNicks) const;
/**
* Invalidate all nickname match caches
*
* Use this after changing global configuration.
*/
- inline void invalidateNickCache() {
+ inline void invalidateNickCache()
+ {
// Mark all as invalid
if (_nickMatchCache.size() > 0) {
_nickMatchCache.clear();
bool _isCaseSensitive = false; ///< If true, match nicknames with exact case
// These represent internal cache and should be safe to mutate in 'const' functions
- mutable QHash<NetworkId, NickMatchCache> _nickMatchCache; ///< Per-network nick matching cache
-
+ mutable QHash<NetworkId, NickMatchCache> _nickMatchCache; ///< Per-network nick matching cache
};
#include "peer.h"
-Peer::Peer(AuthHandler *authHandler, QObject *parent)
+Peer::Peer(AuthHandler* authHandler, QObject* parent)
: QObject(parent)
, _authHandler(authHandler)
-{
-
-}
-
+{}
-AuthHandler *Peer::authHandler() const
+AuthHandler* Peer::authHandler() const
{
return _authHandler;
}
-QDateTime Peer::connectedSince() const {
+QDateTime Peer::connectedSince() const
+{
return _connectedSince;
}
-void Peer::setConnectedSince(const QDateTime &connectedSince) {
+void Peer::setConnectedSince(const QDateTime& connectedSince)
+{
_connectedSince = connectedSince;
}
-QString Peer::buildDate() const {
+QString Peer::buildDate() const
+{
return _buildDate;
}
-void Peer::setBuildDate(const QString &buildDate) {
+void Peer::setBuildDate(const QString& buildDate)
+{
_buildDate = buildDate;
}
-QString Peer::clientVersion() const {
+QString Peer::clientVersion() const
+{
return _clientVersion;
}
-void Peer::setClientVersion(const QString &clientVersion) {
+void Peer::setClientVersion(const QString& clientVersion)
+{
_clientVersion = clientVersion;
}
-bool Peer::hasFeature(Quassel::Feature feature) const {
+bool Peer::hasFeature(Quassel::Feature feature) const
+{
return _features.isEnabled(feature);
}
return _features;
}
-void Peer::setFeatures(Quassel::Features features) {
+void Peer::setFeatures(Quassel::Features features)
+{
_features = std::move(features);
}
-int Peer::id() const {
+int Peer::id() const
+{
return _id;
}
-void Peer::setId(int id) {
+void Peer::setId(int id)
+{
_id = id;
}
// received over the network with the actual address of the local Peer
// instance. Because the actual value isn't needed on the wire, it is
// serialized as null.
-QDataStream &operator<<(QDataStream &out, PeerPtr ptr)
+QDataStream& operator<<(QDataStream& out, PeerPtr ptr)
{
Q_UNUSED(ptr);
out << static_cast<quint64>(0); // 64 bit for historic reasons
return out;
}
-QDataStream &operator>>(QDataStream &in, PeerPtr &ptr)
+QDataStream& operator>>(QDataStream& in, PeerPtr& ptr)
{
ptr = nullptr;
quint64 value;
Q_OBJECT
public:
- explicit Peer(AuthHandler *authHandler, QObject *parent = nullptr);
+ explicit Peer(AuthHandler* authHandler, QObject* parent = nullptr);
virtual Protocol::Type protocol() const = 0;
virtual QString description() const = 0;
- virtual SignalProxy *signalProxy() const = 0;
- virtual void setSignalProxy(SignalProxy *proxy) = 0;
+ virtual SignalProxy* signalProxy() const = 0;
+ virtual void setSignalProxy(SignalProxy* proxy) = 0;
QDateTime connectedSince() const;
- void setConnectedSince(const QDateTime &connectedSince);
+ void setConnectedSince(const QDateTime& connectedSince);
QString buildDate() const;
- void setBuildDate(const QString &buildDate);
+ void setBuildDate(const QString& buildDate);
QString clientVersion() const;
- void setClientVersion(const QString &clientVersion);
+ void setClientVersion(const QString& clientVersion);
bool hasFeature(Quassel::Feature feature) const;
Quassel::Features features() const;
int id() const;
void setId(int id);
- AuthHandler *authHandler() const;
+ AuthHandler* authHandler() const;
virtual bool isOpen() const = 0;
virtual bool isSecure() const = 0;
public slots:
/* Handshake messages */
- virtual void dispatch(const Protocol::RegisterClient &) = 0;
- virtual void dispatch(const Protocol::ClientDenied &) = 0;
- virtual void dispatch(const Protocol::ClientRegistered &) = 0;
- virtual void dispatch(const Protocol::SetupData &) = 0;
- virtual void dispatch(const Protocol::SetupFailed &) = 0;
- virtual void dispatch(const Protocol::SetupDone &) = 0;
- virtual void dispatch(const Protocol::Login &) = 0;
- virtual void dispatch(const Protocol::LoginFailed &) = 0;
- virtual void dispatch(const Protocol::LoginSuccess &) = 0;
- virtual void dispatch(const Protocol::SessionState &) = 0;
+ virtual void dispatch(const Protocol::RegisterClient&) = 0;
+ virtual void dispatch(const Protocol::ClientDenied&) = 0;
+ virtual void dispatch(const Protocol::ClientRegistered&) = 0;
+ virtual void dispatch(const Protocol::SetupData&) = 0;
+ virtual void dispatch(const Protocol::SetupFailed&) = 0;
+ virtual void dispatch(const Protocol::SetupDone&) = 0;
+ virtual void dispatch(const Protocol::Login&) = 0;
+ virtual void dispatch(const Protocol::LoginFailed&) = 0;
+ virtual void dispatch(const Protocol::LoginSuccess&) = 0;
+ virtual void dispatch(const Protocol::SessionState&) = 0;
/* Sigproxy messages */
- virtual void dispatch(const Protocol::SyncMessage &) = 0;
- virtual void dispatch(const Protocol::RpcCall &) = 0;
- virtual void dispatch(const Protocol::InitRequest &) = 0;
- virtual void dispatch(const Protocol::InitData &) = 0;
+ virtual void dispatch(const Protocol::SyncMessage&) = 0;
+ virtual void dispatch(const Protocol::RpcCall&) = 0;
+ virtual void dispatch(const Protocol::InitRequest&) = 0;
+ virtual void dispatch(const Protocol::InitData&) = 0;
- virtual void close(const QString &reason = QString()) = 0;
+ virtual void close(const QString& reason = QString()) = 0;
signals:
void disconnected();
protected:
template<typename T>
- void handle(const T &protoMessage);
+ void handle(const T& protoMessage);
private:
QPointer<AuthHandler> _authHandler;
};
// We need to special-case Peer* in attached signals/slots, so typedef it for the meta type system
-using PeerPtr = Peer *;
+using PeerPtr = Peer*;
Q_DECLARE_METATYPE(PeerPtr)
-QDataStream &operator<<(QDataStream &out, PeerPtr ptr);
-QDataStream &operator>>(QDataStream &in, PeerPtr &ptr);
-
+QDataStream& operator<<(QDataStream& out, PeerPtr ptr);
+QDataStream& operator>>(QDataStream& in, PeerPtr& ptr);
// Template method needed in the header
-template<typename T> inline
-void Peer::handle(const T &protoMessage)
+template<typename T>
+inline void Peer::handle(const T& protoMessage)
{
- switch(protoMessage.handler()) {
- case Protocol::Handler::SignalProxy:
- if (!signalProxy()) {
- qWarning() << Q_FUNC_INFO << "Cannot handle message without a SignalProxy!";
- return;
- }
- signalProxy()->handle(this, protoMessage);
- break;
-
- case Protocol::Handler::AuthHandler:
- if (!authHandler()) {
- qWarning() << Q_FUNC_INFO << "Cannot handle auth messages without an active AuthHandler!";
- return;
- }
- authHandler()->handle(protoMessage);
- break;
-
- default:
- qWarning() << Q_FUNC_INFO << "Unknown handler for protocol message!";
+ switch (protoMessage.handler()) {
+ case Protocol::Handler::SignalProxy:
+ if (!signalProxy()) {
+ qWarning() << Q_FUNC_INFO << "Cannot handle message without a SignalProxy!";
+ return;
+ }
+ signalProxy()->handle(this, protoMessage);
+ break;
+
+ case Protocol::Handler::AuthHandler:
+ if (!authHandler()) {
+ qWarning() << Q_FUNC_INFO << "Cannot handle auth messages without an active AuthHandler!";
return;
+ }
+ authHandler()->handle(protoMessage);
+ break;
+
+ default:
+ qWarning() << Q_FUNC_INFO << "Unknown handler for protocol message!";
+ return;
}
}
#include "protocols/datastream/datastreampeer.h"
#include "protocols/legacy/legacypeer.h"
-
PeerFactory::ProtoList PeerFactory::supportedProtocols()
{
ProtoList result;
return result;
}
-
-RemotePeer *PeerFactory::createPeer(const ProtoDescriptor &protocol, AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent)
+RemotePeer* PeerFactory::createPeer(
+ const ProtoDescriptor& protocol, AuthHandler* authHandler, QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent)
{
return createPeer(ProtoList() << protocol, authHandler, socket, level, parent);
}
-
-RemotePeer *PeerFactory::createPeer(const ProtoList &protocols, AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent)
+RemotePeer* PeerFactory::createPeer(
+ const ProtoList& protocols, AuthHandler* authHandler, QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent)
{
- foreach(const ProtoDescriptor &protodesc, protocols) {
+ foreach (const ProtoDescriptor& protodesc, protocols) {
Protocol::Type proto = protodesc.first;
quint16 features = protodesc.second;
- switch(proto) {
- case Protocol::LegacyProtocol:
- return new LegacyPeer(authHandler, socket, level, parent);
- case Protocol::DataStreamProtocol:
- if (DataStreamPeer::acceptsFeatures(features))
- return new DataStreamPeer(authHandler, socket, features, level, parent);
- break;
- default:
- break;
+ switch (proto) {
+ case Protocol::LegacyProtocol:
+ return new LegacyPeer(authHandler, socket, level, parent);
+ case Protocol::DataStreamProtocol:
+ if (DataStreamPeer::acceptsFeatures(features))
+ return new DataStreamPeer(authHandler, socket, features, level, parent);
+ break;
+ default:
+ break;
}
}
class COMMON_EXPORT PeerFactory
{
-
public:
// second value is the protocol-specific features
using ProtoDescriptor = QPair<Protocol::Type, quint16>;
static ProtoList supportedProtocols();
- static RemotePeer *createPeer(const ProtoDescriptor &protocol, AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent = nullptr);
- static RemotePeer *createPeer(const ProtoList &protocols, AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent = nullptr);
-
+ static RemotePeer* createPeer(const ProtoDescriptor& protocol,
+ AuthHandler* authHandler,
+ QTcpSocket* socket,
+ Compressor::CompressionLevel level,
+ QObject* parent = nullptr);
+ static RemotePeer* createPeer(const ProtoList& protocols,
+ AuthHandler* authHandler,
+ QTcpSocket* socket,
+ Compressor::CompressionLevel level,
+ QObject* parent = nullptr);
};
#include "posixsignalwatcher.h"
+#include <sys/resource.h>
#include <sys/socket.h>
-#include <sys/types.h>
#include <sys/time.h>
-#include <sys/resource.h>
+#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
int PosixSignalWatcher::_sockpair[2];
-PosixSignalWatcher::PosixSignalWatcher(QObject *parent)
+PosixSignalWatcher::PosixSignalWatcher(QObject* parent)
: AbstractSignalWatcher{parent}
{
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, _sockpair)) {
#ifdef HAVE_BACKTRACE
// we only handle crashes ourselves if coredumps are disabled
- struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit));
+ struct rlimit* limit = (rlimit*)malloc(sizeof(struct rlimit));
int rc = getrlimit(RLIMIT_CORE, limit);
if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
registerSignal(SIGABRT);
Q_OBJECT
public:
- PosixSignalWatcher(QObject *parent = nullptr);
+ PosixSignalWatcher(QObject* parent = nullptr);
private:
static void signalHandler(int signal);
private:
static int _sockpair[2];
- QSocketNotifier *_notifier{nullptr};
+ QSocketNotifier* _notifier{nullptr};
};
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "presetnetworks.h"
+
#include <QSettings>
-#include "presetnetworks.h"
#include "quassel.h"
QString PresetNetworks::_networksIniPath = QString();
if (_networksIniPath.isNull()) {
_networksIniPath = Quassel::findDataFilePath("networks.ini");
if (_networksIniPath.isNull()) {
- _networksIniPath = ""; // now we won't check again, as it's not null anymore
+ _networksIniPath = ""; // now we won't check again, as it's not null anymore
return QStringList();
}
}
if (!networks.isEmpty()) {
// we sort the list case-insensitive
QMap<QString, QString> sorted;
- foreach(QString net, networks) {
+ foreach (QString net, networks) {
if (onlyDefault && !s.value(QString("%1/Default").arg(net)).toBool())
continue;
sorted[net.toLower()] = net;
return QStringList();
}
-
-QStringList PresetNetworks::defaultChannels(const QString &networkName)
+QStringList PresetNetworks::defaultChannels(const QString& networkName)
{
- if (_networksIniPath.isEmpty()) // be sure to have called presetNetworks() first, else this always fails
+ if (_networksIniPath.isEmpty()) // be sure to have called presetNetworks() first, else this always fails
return QStringList();
QSettings s(_networksIniPath, QSettings::IniFormat);
return s.value(QString("%1/DefaultChannels").arg(networkName)).toStringList();
}
-
-NetworkInfo PresetNetworks::networkInfo(const QString &networkName)
+NetworkInfo PresetNetworks::networkInfo(const QString& networkName)
{
NetworkInfo info;
if (!_networksIniPath.isEmpty()) {
info.networkName = networkName;
QSettings s(_networksIniPath, QSettings::IniFormat);
s.beginGroup(info.networkName);
- foreach(QString server, s.value("Servers").toStringList()) {
+ foreach (QString server, s.value("Servers").toStringList()) {
bool ssl = false;
QStringList splitserver = server.split(':', QString::SkipEmptyParts);
if (splitserver.count() != 2) {
{
public:
static QStringList names(bool onlyDefault = false);
- static QStringList defaultChannels(const QString &networkName);
- static NetworkInfo networkInfo(const QString &networkName);
+ static QStringList defaultChannels(const QString& networkName);
+ static NetworkInfo networkInfo(const QString& networkName);
private:
static QString _networksIniPath;
#pragma once
+#include <utility>
+
#include <QByteArray>
#include <QDateTime>
#include <QVariantList>
-#include <utility>
#include "quassel.h"
const quint32 magic = 0x42b33f00;
-enum Type {
+enum Type
+{
InternalProtocol = 0x00,
LegacyProtocol = 0x01,
DataStreamProtocol = 0x02
};
-
-enum Feature {
+enum Feature
+{
Encryption = 0x01,
Compression = 0x02
};
-
-enum class Handler {
+enum class Handler
+{
SignalProxy,
AuthHandler
};
-
/*** Handshake, handled by AuthHandler ***/
-struct HandshakeMessage {
+struct HandshakeMessage
+{
inline Handler handler() const { return Handler::AuthHandler; }
};
-
struct RegisterClient : public HandshakeMessage
{
inline RegisterClient(Quassel::Features clientFeatures, QString clientVersion, QString buildDate, bool sslSupported = false)
bool sslSupported;
};
-
struct ClientDenied : public HandshakeMessage
{
inline ClientDenied(QString errorString)
- : errorString(std::move(errorString)) {}
+ : errorString(std::move(errorString))
+ {}
QString errorString;
};
-
struct ClientRegistered : public HandshakeMessage
{
- inline ClientRegistered(Quassel::Features coreFeatures, bool coreConfigured, QVariantList backendInfo, QVariantList authenticatorInfo, bool sslSupported)
+ inline ClientRegistered(
+ Quassel::Features coreFeatures, bool coreConfigured, QVariantList backendInfo, QVariantList authenticatorInfo, bool sslSupported)
: features(std::move(coreFeatures))
, coreConfigured(coreConfigured)
, backendInfo(std::move(backendInfo))
Quassel::Features features;
bool coreConfigured;
- QVariantList backendInfo; // TODO: abstract this better
+ QVariantList backendInfo; // TODO: abstract this better
// The authenticatorInfo should be optional!
QVariantList authenticatorInfo;
bool sslSupported;
};
-
struct SetupData : public HandshakeMessage
{
- inline SetupData(QString adminUser, QString adminPassword, QString backend,
- QVariantMap setupData, QString authenticator = QString(),
+ inline SetupData(QString adminUser,
+ QString adminPassword,
+ QString backend,
+ QVariantMap setupData,
+ QString authenticator = QString(),
QVariantMap authSetupData = QVariantMap())
- : adminUser(std::move(adminUser))
- , adminPassword(std::move(adminPassword))
- , backend(std::move(backend))
- , setupData(std::move(setupData))
- , authenticator(std::move(authenticator))
- , authSetupData(std::move(authSetupData))
+ : adminUser(std::move(adminUser))
+ , adminPassword(std::move(adminPassword))
+ , backend(std::move(backend))
+ , setupData(std::move(setupData))
+ , authenticator(std::move(authenticator))
+ , authSetupData(std::move(authSetupData))
{}
QString adminUser;
QVariantMap authSetupData;
};
-
struct SetupFailed : public HandshakeMessage
{
inline SetupFailed(QString errorString)
- : errorString(std::move(errorString)) {}
+ : errorString(std::move(errorString))
+ {}
QString errorString;
};
-
struct SetupDone : public HandshakeMessage
-{
-};
-
+{};
struct Login : public HandshakeMessage
{
inline Login(QString user, QString password)
- : user(std::move(user)), password(std::move(password)) {}
+ : user(std::move(user))
+ , password(std::move(password))
+ {}
QString user;
QString password;
};
-
struct LoginFailed : public HandshakeMessage
{
inline LoginFailed(QString errorString)
- : errorString(std::move(errorString)) {}
+ : errorString(std::move(errorString))
+ {}
QString errorString;
};
-
struct LoginSuccess : public HandshakeMessage
-{
-};
-
+{};
// TODO: more generic format
struct SessionState : public HandshakeMessage
{
- inline SessionState() = default; // needed for QMetaType (for the mono client)
+ inline SessionState() = default; // needed for QMetaType (for the mono client)
inline SessionState(QVariantList identities, QVariantList bufferInfos, QVariantList networkIds)
- : identities(std::move(identities)), bufferInfos(std::move(bufferInfos)), networkIds(std::move(networkIds)) {}
+ : identities(std::move(identities))
+ , bufferInfos(std::move(bufferInfos))
+ , networkIds(std::move(networkIds))
+ {}
QVariantList identities;
QVariantList bufferInfos;
inline Handler handler() const { return Handler::SignalProxy; }
};
-
struct SyncMessage : public SignalProxyMessage
{
SyncMessage() = default;
SyncMessage(QByteArray className, QString objectName, QByteArray slotName, QVariantList params)
- : className(std::move(className)), objectName(std::move(objectName)), slotName(std::move(slotName)), params(std::move(params)) {}
+ : className(std::move(className))
+ , objectName(std::move(objectName))
+ , slotName(std::move(slotName))
+ , params(std::move(params))
+ {}
QByteArray className;
QString objectName;
QVariantList params;
};
-
struct RpcCall : public SignalProxyMessage
{
RpcCall() = default;
RpcCall(QByteArray slotName, QVariantList params)
- : slotName(std::move(slotName)), params(std::move(params)) {}
+ : slotName(std::move(slotName))
+ , params(std::move(params))
+ {}
QByteArray slotName;
QVariantList params;
};
-
struct InitRequest : public SignalProxyMessage
{
InitRequest() = default;
InitRequest(QByteArray className, QString objectName)
- : className(std::move(className)), objectName(std::move(objectName)) {}
+ : className(std::move(className))
+ , objectName(std::move(objectName))
+ {}
QByteArray className;
QString objectName;
};
-
struct InitData : public SignalProxyMessage
{
InitData() = default;
InitData(QByteArray className, QString objectName, QVariantMap initData)
- : className(std::move(className)), objectName(std::move(objectName)), initData(std::move(initData)) {}
+ : className(std::move(className))
+ , objectName(std::move(objectName))
+ , initData(std::move(initData))
+ {}
QByteArray className;
QString objectName;
QVariantMap initData;
};
-
/*** handled by RemoteConnection ***/
struct HeartBeat
{
- inline HeartBeat(QDateTime timestamp) : timestamp(std::move(timestamp)) {}
+ inline HeartBeat(QDateTime timestamp)
+ : timestamp(std::move(timestamp))
+ {}
QDateTime timestamp;
};
-
struct HeartBeatReply
{
- inline HeartBeatReply(QDateTime timestamp) : timestamp(std::move(timestamp)) {}
+ inline HeartBeatReply(QDateTime timestamp)
+ : timestamp(std::move(timestamp))
+ {}
QDateTime timestamp;
};
-
-}
+} // namespace Protocol
// Required for InternalPeer
Q_DECLARE_METATYPE(Protocol::SyncMessage)
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include <QtEndian>
+#include "datastreampeer.h"
+
#include <QDataStream>
#include <QHostAddress>
#include <QTcpSocket>
+#include <QtEndian>
-#include "datastreampeer.h"
#include "quassel.h"
+
#include "serializers/serializers.h"
using namespace Protocol;
-DataStreamPeer::DataStreamPeer(::AuthHandler *authHandler, QTcpSocket *socket, quint16 features, Compressor::CompressionLevel level, QObject *parent)
+DataStreamPeer::DataStreamPeer(
+ ::AuthHandler* authHandler, QTcpSocket* socket, quint16 features, Compressor::CompressionLevel level, QObject* parent)
: RemotePeer(authHandler, socket, level, parent)
{
Q_UNUSED(features);
}
-
quint16 DataStreamPeer::supportedFeatures()
{
return 0;
}
-
bool DataStreamPeer::acceptsFeatures(quint16 peerFeatures)
{
Q_UNUSED(peerFeatures);
return true;
}
-
quint16 DataStreamPeer::enabledFeatures() const
{
return 0;
}
-
-void DataStreamPeer::processMessage(const QByteArray &msg)
+void DataStreamPeer::processMessage(const QByteArray& msg)
{
QDataStream stream(msg);
stream.setVersion(QDataStream::Qt_4_2);
handlePackedFunc(list);
}
-
-void DataStreamPeer::writeMessage(const QVariantMap &handshakeMsg)
+void DataStreamPeer::writeMessage(const QVariantMap& handshakeMsg)
{
QVariantList list;
QVariantMap::const_iterator it = handshakeMsg.begin();
writeMessage(list);
}
-
-void DataStreamPeer::writeMessage(const QVariantList &sigProxyMsg)
+void DataStreamPeer::writeMessage(const QVariantList& sigProxyMsg)
{
QByteArray data;
QDataStream msgStream(&data, QIODevice::WriteOnly);
writeMessage(data);
}
-
/*** Handshake messages ***/
/* These messages are transmitted during handshake phase, which in case of the legacy protocol means they have
* Also, the legacy handshake does not fully match the redesigned one, so we'll have to do various mappings here.
*/
-void DataStreamPeer::handleHandshakeMessage(const QVariantList &mapData)
+void DataStreamPeer::handleHandshakeMessage(const QVariantList& mapData)
{
QVariantMap m;
- for (int i = 0; i < mapData.count()/2; ++i)
- m[QString::fromUtf8(mapData[2*i].toByteArray())] = mapData[2*i+1];
+ for (int i = 0; i < mapData.count() / 2; ++i)
+ m[QString::fromUtf8(mapData[2 * i].toByteArray())] = mapData[2 * i + 1];
QString msgType = m["MsgType"].toString();
if (msgType.isEmpty()) {
}
if (msgType == "ClientInit") {
- handle(RegisterClient{Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["Features"].toUInt())},
- m["ClientVersion"].toString(),
- m["ClientDate"].toString(),
- false // UseSsl obsolete
- });
+ handle(RegisterClient{
+ Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["Features"].toUInt())},
+ m["ClientVersion"].toString(),
+ m["ClientDate"].toString(),
+ false // UseSsl obsolete
+ });
}
else if (msgType == "ClientInitReject") {
}
else if (msgType == "ClientInitAck") {
- handle(ClientRegistered{Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["CoreFeatures"].toUInt())},
- m["Configured"].toBool(),
- m["StorageBackends"].toList(),
- m["Authenticators"].toList(),
- false // SupportsSsl obsolete
- });
+ handle(ClientRegistered{
+ Quassel::Features{m["FeatureList"].toStringList(), Quassel::LegacyFeatures(m["CoreFeatures"].toUInt())},
+ m["Configured"].toBool(),
+ m["StorageBackends"].toList(),
+ m["Authenticators"].toList(),
+ false // SupportsSsl obsolete
+ });
}
else if (msgType == "CoreSetupData") {
QVariantMap map = m["SetupData"].toMap();
- handle(SetupData(map["AdminUser"].toString(), map["AdminPasswd"].toString(), map["Backend"].toString(), map["ConnectionProperties"].toMap(), map["Authenticator"].toString(), map["AuthProperties"].toMap()));
+ handle(SetupData(map["AdminUser"].toString(),
+ map["AdminPasswd"].toString(),
+ map["Backend"].toString(),
+ map["ConnectionProperties"].toMap(),
+ map["Authenticator"].toString(),
+ map["AuthProperties"].toMap()));
}
else if (msgType == "CoreSetupReject") {
}
}
-
-void DataStreamPeer::dispatch(const RegisterClient &msg) {
+void DataStreamPeer::dispatch(const RegisterClient& msg)
+{
QVariantMap m;
m["MsgType"] = "ClientInit";
m["Features"] = static_cast<quint32>(msg.features.toLegacyFeatures());
writeMessage(m);
}
-
-void DataStreamPeer::dispatch(const ClientDenied &msg) {
+void DataStreamPeer::dispatch(const ClientDenied& msg)
+{
QVariantMap m;
m["MsgType"] = "ClientInitReject";
m["Error"] = msg.errorString;
writeMessage(m);
}
-
-void DataStreamPeer::dispatch(const ClientRegistered &msg) {
+void DataStreamPeer::dispatch(const ClientRegistered& msg)
+{
QVariantMap m;
m["MsgType"] = "ClientInitAck";
if (hasFeature(Quassel::Feature::ExtendedFeatures)) {
writeMessage(m);
}
-
-void DataStreamPeer::dispatch(const SetupData &msg)
+void DataStreamPeer::dispatch(const SetupData& msg)
{
QVariantMap map;
map["AdminUser"] = msg.adminUser;
writeMessage(m);
}
-
-void DataStreamPeer::dispatch(const SetupFailed &msg)
+void DataStreamPeer::dispatch(const SetupFailed& msg)
{
QVariantMap m;
m["MsgType"] = "CoreSetupReject";
writeMessage(m);
}
-
-void DataStreamPeer::dispatch(const SetupDone &msg)
+void DataStreamPeer::dispatch(const SetupDone& msg)
{
Q_UNUSED(msg)
writeMessage(m);
}
-
-void DataStreamPeer::dispatch(const Login &msg)
+void DataStreamPeer::dispatch(const Login& msg)
{
QVariantMap m;
m["MsgType"] = "ClientLogin";
writeMessage(m);
}
-
-void DataStreamPeer::dispatch(const LoginFailed &msg)
+void DataStreamPeer::dispatch(const LoginFailed& msg)
{
QVariantMap m;
m["MsgType"] = "ClientLoginReject";
writeMessage(m);
}
-
-void DataStreamPeer::dispatch(const LoginSuccess &msg)
+void DataStreamPeer::dispatch(const LoginSuccess& msg)
{
Q_UNUSED(msg)
writeMessage(m);
}
-
-void DataStreamPeer::dispatch(const SessionState &msg)
+void DataStreamPeer::dispatch(const SessionState& msg)
{
QVariantMap m;
m["MsgType"] = "SessionInit";
writeMessage(m);
}
-
/*** Standard messages ***/
-void DataStreamPeer::handlePackedFunc(const QVariantList &packedFunc)
+void DataStreamPeer::handlePackedFunc(const QVariantList& packedFunc)
{
QVariantList params(packedFunc);
// TODO: make sure that this is a valid request type
RequestType requestType = (RequestType)params.takeFirst().value<qint16>();
switch (requestType) {
- case Sync: {
- if (params.count() < 3) {
- qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params;
- return;
- }
- QByteArray className = params.takeFirst().toByteArray();
- QString objectName = QString::fromUtf8(params.takeFirst().toByteArray());
- QByteArray slotName = params.takeFirst().toByteArray();
- handle(Protocol::SyncMessage(className, objectName, slotName, params));
- break;
+ case Sync: {
+ if (params.count() < 3) {
+ qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params;
+ return;
}
- case RpcCall: {
- if (params.empty()) {
- qWarning() << Q_FUNC_INFO << "Received empty RPC call!";
- return;
- }
- QByteArray slotName = params.takeFirst().toByteArray();
- handle(Protocol::RpcCall(slotName, params));
- break;
+ QByteArray className = params.takeFirst().toByteArray();
+ QString objectName = QString::fromUtf8(params.takeFirst().toByteArray());
+ QByteArray slotName = params.takeFirst().toByteArray();
+ handle(Protocol::SyncMessage(className, objectName, slotName, params));
+ break;
+ }
+ case RpcCall: {
+ if (params.empty()) {
+ qWarning() << Q_FUNC_INFO << "Received empty RPC call!";
+ return;
}
- case InitRequest: {
- if (params.count() != 2) {
- qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params;
- return;
- }
- QByteArray className = params[0].toByteArray();
- QString objectName = QString::fromUtf8(params[1].toByteArray());
- handle(Protocol::InitRequest(className, objectName));
- break;
+ QByteArray slotName = params.takeFirst().toByteArray();
+ handle(Protocol::RpcCall(slotName, params));
+ break;
+ }
+ case InitRequest: {
+ if (params.count() != 2) {
+ qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params;
+ return;
}
- case InitData: {
- if (params.count() < 2) {
- qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params;
- return;
- }
- QByteArray className = params.takeFirst().toByteArray();
- QString objectName = QString::fromUtf8(params.takeFirst().toByteArray());
- QVariantMap initData;
- for (int i = 0; i < params.count()/2; ++i)
- initData[QString::fromUtf8(params[2*i].toByteArray())] = params[2*i+1];
- handle(Protocol::InitData(className, objectName, initData));
- break;
+ QByteArray className = params[0].toByteArray();
+ QString objectName = QString::fromUtf8(params[1].toByteArray());
+ handle(Protocol::InitRequest(className, objectName));
+ break;
+ }
+ case InitData: {
+ if (params.count() < 2) {
+ qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params;
+ return;
}
- case HeartBeat: {
- if (params.count() != 1) {
- qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
- return;
- }
- // Note: QDateTime instead of QTime as in the legacy protocol!
- handle(Protocol::HeartBeat(params[0].toDateTime()));
- break;
+ QByteArray className = params.takeFirst().toByteArray();
+ QString objectName = QString::fromUtf8(params.takeFirst().toByteArray());
+ QVariantMap initData;
+ for (int i = 0; i < params.count() / 2; ++i)
+ initData[QString::fromUtf8(params[2 * i].toByteArray())] = params[2 * i + 1];
+ handle(Protocol::InitData(className, objectName, initData));
+ break;
+ }
+ case HeartBeat: {
+ if (params.count() != 1) {
+ qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
+ return;
}
- case HeartBeatReply: {
- if (params.count() != 1) {
- qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
- return;
- }
- // Note: QDateTime instead of QTime as in the legacy protocol!
- handle(Protocol::HeartBeatReply(params[0].toDateTime()));
- break;
+ // Note: QDateTime instead of QTime as in the legacy protocol!
+ handle(Protocol::HeartBeat(params[0].toDateTime()));
+ break;
+ }
+ case HeartBeatReply: {
+ if (params.count() != 1) {
+ qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
+ return;
}
-
+ // Note: QDateTime instead of QTime as in the legacy protocol!
+ handle(Protocol::HeartBeatReply(params[0].toDateTime()));
+ break;
+ }
}
}
-
-void DataStreamPeer::dispatch(const Protocol::SyncMessage &msg)
+void DataStreamPeer::dispatch(const Protocol::SyncMessage& msg)
{
dispatchPackedFunc(QVariantList() << (qint16)Sync << msg.className << msg.objectName.toUtf8() << msg.slotName << msg.params);
}
-
-void DataStreamPeer::dispatch(const Protocol::RpcCall &msg)
+void DataStreamPeer::dispatch(const Protocol::RpcCall& msg)
{
dispatchPackedFunc(QVariantList() << (qint16)RpcCall << msg.slotName << msg.params);
}
-
-void DataStreamPeer::dispatch(const Protocol::InitRequest &msg)
+void DataStreamPeer::dispatch(const Protocol::InitRequest& msg)
{
dispatchPackedFunc(QVariantList() << (qint16)InitRequest << msg.className << msg.objectName.toUtf8());
}
-
-void DataStreamPeer::dispatch(const Protocol::InitData &msg)
+void DataStreamPeer::dispatch(const Protocol::InitData& msg)
{
QVariantList initData;
QVariantMap::const_iterator it = msg.initData.begin();
dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName.toUtf8() << initData);
}
-
-void DataStreamPeer::dispatch(const Protocol::HeartBeat &msg)
+void DataStreamPeer::dispatch(const Protocol::HeartBeat& msg)
{
dispatchPackedFunc(QVariantList() << (qint16)HeartBeat << msg.timestamp);
}
-
-void DataStreamPeer::dispatch(const Protocol::HeartBeatReply &msg)
+void DataStreamPeer::dispatch(const Protocol::HeartBeatReply& msg)
{
dispatchPackedFunc(QVariantList() << (qint16)HeartBeatReply << msg.timestamp);
}
-
-void DataStreamPeer::dispatchPackedFunc(const QVariantList &packedFunc)
+void DataStreamPeer::dispatchPackedFunc(const QVariantList& packedFunc)
{
writeMessage(packedFunc);
}
Q_OBJECT
public:
- enum RequestType {
+ enum RequestType
+ {
Sync = 1,
RpcCall,
InitRequest,
HeartBeatReply
};
- DataStreamPeer(AuthHandler *authHandler, QTcpSocket *socket, quint16 features, Compressor::CompressionLevel level, QObject *parent = nullptr);
+ DataStreamPeer(AuthHandler* authHandler, QTcpSocket* socket, quint16 features, Compressor::CompressionLevel level, QObject* parent = nullptr);
Protocol::Type protocol() const override { return Protocol::DataStreamProtocol; }
QString protocolName() const override { return "the DataStream protocol"; }
static bool acceptsFeatures(quint16 peerFeatures);
quint16 enabledFeatures() const override;
- void dispatch(const Protocol::RegisterClient &msg) override;
- void dispatch(const Protocol::ClientDenied &msg) override;
- void dispatch(const Protocol::ClientRegistered &msg) override;
- void dispatch(const Protocol::SetupData &msg) override;
- void dispatch(const Protocol::SetupFailed &msg) override;
- void dispatch(const Protocol::SetupDone &msg) override;
- void dispatch(const Protocol::Login &msg) override;
- void dispatch(const Protocol::LoginFailed &msg) override;
- void dispatch(const Protocol::LoginSuccess &msg) override;
- void dispatch(const Protocol::SessionState &msg) override;
+ void dispatch(const Protocol::RegisterClient& msg) override;
+ void dispatch(const Protocol::ClientDenied& msg) override;
+ void dispatch(const Protocol::ClientRegistered& msg) override;
+ void dispatch(const Protocol::SetupData& msg) override;
+ void dispatch(const Protocol::SetupFailed& msg) override;
+ void dispatch(const Protocol::SetupDone& msg) override;
+ void dispatch(const Protocol::Login& msg) override;
+ void dispatch(const Protocol::LoginFailed& msg) override;
+ void dispatch(const Protocol::LoginSuccess& msg) override;
+ void dispatch(const Protocol::SessionState& msg) override;
- void dispatch(const Protocol::SyncMessage &msg) override;
- void dispatch(const Protocol::RpcCall &msg) override;
- void dispatch(const Protocol::InitRequest &msg) override;
- void dispatch(const Protocol::InitData &msg) override;
+ void dispatch(const Protocol::SyncMessage& msg) override;
+ void dispatch(const Protocol::RpcCall& msg) override;
+ void dispatch(const Protocol::InitRequest& msg) override;
+ void dispatch(const Protocol::InitData& msg) override;
- void dispatch(const Protocol::HeartBeat &msg) override;
- void dispatch(const Protocol::HeartBeatReply &msg) override;
+ void dispatch(const Protocol::HeartBeat& msg) override;
+ void dispatch(const Protocol::HeartBeatReply& msg) override;
signals:
- void protocolError(const QString &errorString);
+ void protocolError(const QString& errorString);
private:
using RemotePeer::writeMessage;
- void writeMessage(const QVariantMap &handshakeMsg);
- void writeMessage(const QVariantList &sigProxyMsg);
- void processMessage(const QByteArray &msg) override;
+ void writeMessage(const QVariantMap& handshakeMsg);
+ void writeMessage(const QVariantList& sigProxyMsg);
+ void processMessage(const QByteArray& msg) override;
- void handleHandshakeMessage(const QVariantList &mapData);
- void handlePackedFunc(const QVariantList &packedFunc);
- void dispatchPackedFunc(const QVariantList &packedFunc);
+ void handleHandshakeMessage(const QVariantList& mapData);
+ void handlePackedFunc(const QVariantList& packedFunc);
+ void dispatchPackedFunc(const QVariantList& packedFunc);
};
#endif
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include <QHostAddress>
+#include "legacypeer.h"
+
#include <QDataStream>
+#include <QHostAddress>
#include <QTcpSocket>
-#include "legacypeer.h"
#include "quassel.h"
+
#include "serializers/serializers.h"
/* version.inc is no longer used for this */
using namespace Protocol;
-LegacyPeer::LegacyPeer(::AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent)
- : RemotePeer(authHandler, socket, level, parent),
- _useCompression(false)
-{
-
-}
-
+LegacyPeer::LegacyPeer(::AuthHandler* authHandler, QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent)
+ : RemotePeer(authHandler, socket, level, parent)
+ , _useCompression(false)
+{}
-void LegacyPeer::setSignalProxy(::SignalProxy *proxy)
+void LegacyPeer::setSignalProxy(::SignalProxy* proxy)
{
RemotePeer::setSignalProxy(proxy);
if (_useCompression)
qDebug() << "Using compression for peer:" << qPrintable(socket()->peerAddress().toString());
}
-
}
-
-void LegacyPeer::processMessage(const QByteArray &msg)
+void LegacyPeer::processMessage(const QByteArray& msg)
{
QDataStream stream(msg);
stream.setVersion(QDataStream::Qt_4_2);
int nbytes = rawItem.size();
if (nbytes <= 4) {
- const char *data = rawItem.constData();
+ const char* data = rawItem.constData();
if (nbytes < 4 || (data[0] != 0 || data[1] != 0 || data[2] != 0 || data[3] != 0)) {
close("Peer sent corrupted compressed data!");
return;
close("Peer sent corrupt data: unable to load QVariant!");
return;
}
- } else {
+ }
+ else {
if (!Serializers::deserialize(stream, features(), item)) {
close("Peer sent corrupt data: unable to load QVariant!");
return;
handlePackedFunc(item);
}
-
-void LegacyPeer::writeMessage(const QVariant &item)
+void LegacyPeer::writeMessage(const QVariant& item)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
writeMessage(block);
}
-
/*** Handshake messages ***/
/* These messages are transmitted during handshake phase, which in case of the legacy protocol means they have
* Also, the legacy handshake does not fully match the redesigned one, so we'll have to do various mappings here.
*/
-void LegacyPeer::handleHandshakeMessage(const QVariant &msg)
+void LegacyPeer::handleHandshakeMessage(const QVariant& msg)
{
QVariantMap m = msg.toMap();
else if (msgType == "ClientInitAck") {
// FIXME only in compat mode
- uint ver = m["ProtocolVersion"].toUInt(); // actually an UInt
+ uint ver = m["ProtocolVersion"].toUInt(); // actually an UInt
if (ver < clientNeedsProtocol) {
emit protocolVersionMismatch((int)ver, (int)clientNeedsProtocol);
return;
else if (msgType == "CoreSetupData") {
QVariantMap map = m["SetupData"].toMap();
- handle(SetupData(map["AdminUser"].toString(), map["AdminPasswd"].toString(), map["Backend"].toString(), map["ConnectionProperties"].toMap(), map["Authenticator"].toString(), map["AuthProperties"].toMap()));
+ handle(SetupData(map["AdminUser"].toString(),
+ map["AdminPasswd"].toString(),
+ map["Backend"].toString(),
+ map["ConnectionProperties"].toMap(),
+ map["Authenticator"].toString(),
+ map["AuthProperties"].toMap()));
}
else if (msgType == "CoreSetupReject") {
}
}
-
-void LegacyPeer::dispatch(const RegisterClient &msg) {
+void LegacyPeer::dispatch(const RegisterClient& msg)
+{
QVariantMap m;
m["MsgType"] = "ClientInit";
m["Features"] = static_cast<quint32>(msg.features.toLegacyFeatures());
writeMessage(m);
}
-
-void LegacyPeer::dispatch(const ClientDenied &msg) {
+void LegacyPeer::dispatch(const ClientDenied& msg)
+{
QVariantMap m;
m["MsgType"] = "ClientInitReject";
m["Error"] = msg.errorString;
writeMessage(m);
}
-
-void LegacyPeer::dispatch(const ClientRegistered &msg) {
+void LegacyPeer::dispatch(const ClientRegistered& msg)
+{
QVariantMap m;
m["MsgType"] = "ClientInitAck";
if (hasFeature(Quassel::Feature::ExtendedFeatures)) {
// FIXME only in compat mode
m["ProtocolVersion"] = protocolVersion;
m["SupportSsl"] = msg.sslSupported;
- m["SupportsCompression"] = socket()->property("UseCompression").toBool(); // this property gets already set in the ClientInit handler
+ m["SupportsCompression"] = socket()->property("UseCompression").toBool(); // this property gets already set in the ClientInit handler
// This is only used for display by really old v10 clients (pre-0.5), and we no longer set this
m["CoreInfo"] = QString();
writeMessage(m);
}
-
-void LegacyPeer::dispatch(const SetupData &msg)
+void LegacyPeer::dispatch(const SetupData& msg)
{
QVariantMap map;
map["AdminUser"] = msg.adminUser;
writeMessage(m);
}
-
-void LegacyPeer::dispatch(const SetupFailed &msg)
+void LegacyPeer::dispatch(const SetupFailed& msg)
{
QVariantMap m;
m["MsgType"] = "CoreSetupReject";
writeMessage(m);
}
-
-void LegacyPeer::dispatch(const SetupDone &msg)
+void LegacyPeer::dispatch(const SetupDone& msg)
{
Q_UNUSED(msg)
writeMessage(m);
}
-
-void LegacyPeer::dispatch(const Login &msg)
+void LegacyPeer::dispatch(const Login& msg)
{
QVariantMap m;
m["MsgType"] = "ClientLogin";
writeMessage(m);
}
-
-void LegacyPeer::dispatch(const LoginFailed &msg)
+void LegacyPeer::dispatch(const LoginFailed& msg)
{
QVariantMap m;
m["MsgType"] = "ClientLoginReject";
writeMessage(m);
}
-
-void LegacyPeer::dispatch(const LoginSuccess &msg)
+void LegacyPeer::dispatch(const LoginSuccess& msg)
{
Q_UNUSED(msg)
writeMessage(m);
}
-
-void LegacyPeer::dispatch(const SessionState &msg)
+void LegacyPeer::dispatch(const SessionState& msg)
{
QVariantMap m;
m["MsgType"] = "SessionInit";
writeMessage(m);
}
-
/*** Standard messages ***/
-void LegacyPeer::handlePackedFunc(const QVariant &packedFunc)
+void LegacyPeer::handlePackedFunc(const QVariant& packedFunc)
{
QVariantList params(packedFunc.toList());
// TODO: make sure that this is a valid request type
RequestType requestType = (RequestType)params.takeFirst().value<int>();
switch (requestType) {
- case Sync: {
- if (params.count() < 3) {
- qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params;
- return;
- }
- QByteArray className = params.takeFirst().toByteArray();
- QString objectName = params.takeFirst().toString();
- QByteArray slotName = params.takeFirst().toByteArray();
- handle(Protocol::SyncMessage(className, objectName, slotName, params));
- break;
+ case Sync: {
+ if (params.count() < 3) {
+ qWarning() << Q_FUNC_INFO << "Received invalid sync call:" << params;
+ return;
}
- case RpcCall: {
- if (params.empty()) {
- qWarning() << Q_FUNC_INFO << "Received empty RPC call!";
- return;
- }
- QByteArray slotName = params.takeFirst().toByteArray();
- handle(Protocol::RpcCall(slotName, params));
- break;
+ QByteArray className = params.takeFirst().toByteArray();
+ QString objectName = params.takeFirst().toString();
+ QByteArray slotName = params.takeFirst().toByteArray();
+ handle(Protocol::SyncMessage(className, objectName, slotName, params));
+ break;
+ }
+ case RpcCall: {
+ if (params.empty()) {
+ qWarning() << Q_FUNC_INFO << "Received empty RPC call!";
+ return;
}
- case InitRequest: {
- if (params.count() != 2) {
- qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params;
- return;
- }
- QByteArray className = params[0].toByteArray();
- QString objectName = params[1].toString();
- handle(Protocol::InitRequest(className, objectName));
- break;
+ QByteArray slotName = params.takeFirst().toByteArray();
+ handle(Protocol::RpcCall(slotName, params));
+ break;
+ }
+ case InitRequest: {
+ if (params.count() != 2) {
+ qWarning() << Q_FUNC_INFO << "Received invalid InitRequest:" << params;
+ return;
}
- case InitData: {
- if (params.count() != 3) {
- qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params;
- return;
- }
- QByteArray className = params[0].toByteArray();
- QString objectName = params[1].toString();
- QVariantMap initData = params[2].toMap();
-
- // we need to special-case IrcUsersAndChannels here, since the format changed
- if (className == "Network")
- fromLegacyIrcUsersAndChannels(initData);
- handle(Protocol::InitData(className, objectName, initData));
- break;
+ QByteArray className = params[0].toByteArray();
+ QString objectName = params[1].toString();
+ handle(Protocol::InitRequest(className, objectName));
+ break;
+ }
+ case InitData: {
+ if (params.count() != 3) {
+ qWarning() << Q_FUNC_INFO << "Received invalid InitData:" << params;
+ return;
}
- case HeartBeat: {
- if (params.count() != 1) {
- qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
- return;
- }
- // The legacy protocol would only send a QTime, no QDateTime
- // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
- QDateTime dateTime = QDateTime::currentDateTime().toUTC();
- dateTime.setTime(params[0].toTime());
- handle(Protocol::HeartBeat(dateTime));
- break;
+ QByteArray className = params[0].toByteArray();
+ QString objectName = params[1].toString();
+ QVariantMap initData = params[2].toMap();
+
+ // we need to special-case IrcUsersAndChannels here, since the format changed
+ if (className == "Network")
+ fromLegacyIrcUsersAndChannels(initData);
+ handle(Protocol::InitData(className, objectName, initData));
+ break;
+ }
+ case HeartBeat: {
+ if (params.count() != 1) {
+ qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
+ return;
}
- case HeartBeatReply: {
- if (params.count() != 1) {
- qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
- return;
- }
- // The legacy protocol would only send a QTime, no QDateTime
- // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
- QDateTime dateTime = QDateTime::currentDateTime().toUTC();
- dateTime.setTime(params[0].toTime());
- handle(Protocol::HeartBeatReply(dateTime));
- break;
+ // The legacy protocol would only send a QTime, no QDateTime
+ // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
+ QDateTime dateTime = QDateTime::currentDateTime().toUTC();
+ dateTime.setTime(params[0].toTime());
+ handle(Protocol::HeartBeat(dateTime));
+ break;
+ }
+ case HeartBeatReply: {
+ if (params.count() != 1) {
+ qWarning() << Q_FUNC_INFO << "Received invalid HeartBeat:" << params;
+ return;
}
-
+ // The legacy protocol would only send a QTime, no QDateTime
+ // so we assume it's sent today, which works in exactly the same cases as it did in the old implementation
+ QDateTime dateTime = QDateTime::currentDateTime().toUTC();
+ dateTime.setTime(params[0].toTime());
+ handle(Protocol::HeartBeatReply(dateTime));
+ break;
+ }
}
}
-
-void LegacyPeer::dispatch(const Protocol::SyncMessage &msg)
+void LegacyPeer::dispatch(const Protocol::SyncMessage& msg)
{
dispatchPackedFunc(QVariantList() << (qint16)Sync << msg.className << msg.objectName << msg.slotName << msg.params);
}
-
-void LegacyPeer::dispatch(const Protocol::RpcCall &msg)
+void LegacyPeer::dispatch(const Protocol::RpcCall& msg)
{
dispatchPackedFunc(QVariantList() << (qint16)RpcCall << msg.slotName << msg.params);
}
-
-void LegacyPeer::dispatch(const Protocol::InitRequest &msg)
+void LegacyPeer::dispatch(const Protocol::InitRequest& msg)
{
dispatchPackedFunc(QVariantList() << (qint16)InitRequest << msg.className << msg.objectName);
}
-
-void LegacyPeer::dispatch(const Protocol::InitData &msg)
+void LegacyPeer::dispatch(const Protocol::InitData& msg)
{
// We need to special-case IrcUsersAndChannels, as the format changed
if (msg.className == "Network") {
dispatchPackedFunc(QVariantList() << (qint16)InitData << msg.className << msg.objectName << msg.initData);
}
-
-void LegacyPeer::dispatch(const Protocol::HeartBeat &msg)
+void LegacyPeer::dispatch(const Protocol::HeartBeat& msg)
{
dispatchPackedFunc(QVariantList() << (qint16)HeartBeat << msg.timestamp.time());
}
-
-void LegacyPeer::dispatch(const Protocol::HeartBeatReply &msg)
+void LegacyPeer::dispatch(const Protocol::HeartBeatReply& msg)
{
dispatchPackedFunc(QVariantList() << (qint16)HeartBeatReply << msg.timestamp.time());
}
-
-void LegacyPeer::dispatchPackedFunc(const QVariantList &packedFunc)
+void LegacyPeer::dispatchPackedFunc(const QVariantList& packedFunc)
{
writeMessage(QVariant(packedFunc));
}
-
// Handle the changed format for Network's initData
// cf. Network::initIrcUsersAndChannels()
-void LegacyPeer::fromLegacyIrcUsersAndChannels(QVariantMap &initData)
+void LegacyPeer::fromLegacyIrcUsersAndChannels(QVariantMap& initData)
{
- const QVariantMap &legacyMap = initData["IrcUsersAndChannels"].toMap();
+ const QVariantMap& legacyMap = initData["IrcUsersAndChannels"].toMap();
QVariantMap newMap;
QHash<QString, QVariantList> users;
- foreach(const QVariant &v, legacyMap["users"].toMap().values()) {
- const QVariantMap &map = v.toMap();
- foreach(const QString &key, map.keys())
+ foreach (const QVariant& v, legacyMap["users"].toMap().values()) {
+ const QVariantMap& map = v.toMap();
+ foreach (const QString& key, map.keys())
users[key] << map[key];
}
QVariantMap userMap;
- foreach(const QString &key, users.keys())
+ foreach (const QString& key, users.keys())
userMap[key] = users[key];
newMap["Users"] = userMap;
QHash<QString, QVariantList> channels;
- foreach(const QVariant &v, legacyMap["channels"].toMap().values()) {
- const QVariantMap &map = v.toMap();
- foreach(const QString &key, map.keys())
+ foreach (const QVariant& v, legacyMap["channels"].toMap().values()) {
+ const QVariantMap& map = v.toMap();
+ foreach (const QString& key, map.keys())
channels[key] << map[key];
}
QVariantMap channelMap;
- foreach(const QString &key, channels.keys())
+ foreach (const QString& key, channels.keys())
channelMap[key] = channels[key];
newMap["Channels"] = channelMap;
initData["IrcUsersAndChannels"] = newMap;
}
-
-void LegacyPeer::toLegacyIrcUsersAndChannels(QVariantMap &initData)
+void LegacyPeer::toLegacyIrcUsersAndChannels(QVariantMap& initData)
{
- const QVariantMap &usersAndChannels = initData["IrcUsersAndChannels"].toMap();
+ const QVariantMap& usersAndChannels = initData["IrcUsersAndChannels"].toMap();
QVariantMap legacyMap;
// toMap() and toList() are cheap, so no need to copy to a hash
QVariantMap userMap;
- const QVariantMap &users = usersAndChannels["Users"].toMap();
+ const QVariantMap& users = usersAndChannels["Users"].toMap();
- int size = users["nick"].toList().size(); // we know this key exists
- for(int i = 0; i < size; i++) {
+ int size = users["nick"].toList().size(); // we know this key exists
+ for (int i = 0; i < size; i++) {
QVariantMap map;
- foreach(const QString &key, users.keys())
+ foreach (const QString& key, users.keys())
map[key] = users[key].toList().at(i);
QString hostmask = QString("%1!%2@%3").arg(map["nick"].toString(), map["user"].toString(), map["host"].toString());
userMap[hostmask.toLower()] = map;
legacyMap["users"] = userMap;
QVariantMap channelMap;
- const QVariantMap &channels = usersAndChannels["Channels"].toMap();
+ const QVariantMap& channels = usersAndChannels["Channels"].toMap();
size = channels["name"].toList().size();
- for(int i = 0; i < size; i++) {
+ for (int i = 0; i < size; i++) {
QVariantMap map;
- foreach(const QString &key, channels.keys())
+ foreach (const QString& key, channels.keys())
map[key] = channels[key].toList().at(i);
channelMap[map["name"].toString().toLower()] = map;
}
Q_OBJECT
public:
- enum RequestType {
+ enum RequestType
+ {
Sync = 1,
RpcCall,
InitRequest,
HeartBeatReply
};
- LegacyPeer(AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent = nullptr);
+ LegacyPeer(AuthHandler* authHandler, QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent = nullptr);
Protocol::Type protocol() const override { return Protocol::LegacyProtocol; }
QString protocolName() const override { return "the legacy protocol"; }
- void setSignalProxy(SignalProxy *proxy) override;
+ void setSignalProxy(SignalProxy* proxy) override;
- void dispatch(const Protocol::RegisterClient &msg) override;
- void dispatch(const Protocol::ClientDenied &msg) override;
- void dispatch(const Protocol::ClientRegistered &msg) override;
- void dispatch(const Protocol::SetupData &msg) override;
- void dispatch(const Protocol::SetupFailed &msg) override;
- void dispatch(const Protocol::SetupDone &msg) override;
- void dispatch(const Protocol::Login &msg) override;
- void dispatch(const Protocol::LoginFailed &msg) override;
- void dispatch(const Protocol::LoginSuccess &msg) override;
- void dispatch(const Protocol::SessionState &msg) override;
+ void dispatch(const Protocol::RegisterClient& msg) override;
+ void dispatch(const Protocol::ClientDenied& msg) override;
+ void dispatch(const Protocol::ClientRegistered& msg) override;
+ void dispatch(const Protocol::SetupData& msg) override;
+ void dispatch(const Protocol::SetupFailed& msg) override;
+ void dispatch(const Protocol::SetupDone& msg) override;
+ void dispatch(const Protocol::Login& msg) override;
+ void dispatch(const Protocol::LoginFailed& msg) override;
+ void dispatch(const Protocol::LoginSuccess& msg) override;
+ void dispatch(const Protocol::SessionState& msg) override;
- void dispatch(const Protocol::SyncMessage &msg) override;
- void dispatch(const Protocol::RpcCall &msg) override;
- void dispatch(const Protocol::InitRequest &msg) override;
- void dispatch(const Protocol::InitData &msg) override;
+ void dispatch(const Protocol::SyncMessage& msg) override;
+ void dispatch(const Protocol::RpcCall& msg) override;
+ void dispatch(const Protocol::InitRequest& msg) override;
+ void dispatch(const Protocol::InitData& msg) override;
- void dispatch(const Protocol::HeartBeat &msg) override;
- void dispatch(const Protocol::HeartBeatReply &msg) override;
+ void dispatch(const Protocol::HeartBeat& msg) override;
+ void dispatch(const Protocol::HeartBeatReply& msg) override;
signals:
- void protocolError(const QString &errorString);
+ void protocolError(const QString& errorString);
private:
using RemotePeer::writeMessage;
- void writeMessage(const QVariant &item);
- void processMessage(const QByteArray &msg) override;
+ void writeMessage(const QVariant& item);
+ void processMessage(const QByteArray& msg) override;
- void handleHandshakeMessage(const QVariant &msg);
- void handlePackedFunc(const QVariant &packedFunc);
- void dispatchPackedFunc(const QVariantList &packedFunc);
+ void handleHandshakeMessage(const QVariant& msg);
+ void handlePackedFunc(const QVariant& packedFunc);
+ void dispatchPackedFunc(const QVariantList& packedFunc);
- void toLegacyIrcUsersAndChannels(QVariantMap &initData);
- void fromLegacyIrcUsersAndChannels(QVariantMap &initData);
+ void toLegacyIrcUsersAndChannels(QVariantMap& initData);
+ void fromLegacyIrcUsersAndChannels(QVariantMap& initData);
bool _useCompression;
};
#endif
}
-
void Quassel::init(RunMode runMode)
{
_runMode = runMode;
Network::setDefaultCodecForDecoding("ISO-8859-15");
}
-
-Logger *Quassel::logger() const
+Logger* Quassel::logger() const
{
return _logger;
}
-
void Quassel::registerQuitHandler(QuitHandler handler)
{
instance()->_quitHandlers.emplace_back(std::move(handler));
}
else {
// Note: We expect one of the registered handlers to call QCoreApplication::quit()
- for (auto &&handler : _quitHandlers) {
+ for (auto&& handler : _quitHandlers) {
handler();
}
}
}
}
-
void Quassel::registerReloadHandler(ReloadHandler handler)
{
instance()->_reloadHandlers.emplace_back(std::move(handler));
}
-
bool Quassel::reloadConfig()
{
bool result{true};
- for (auto &&handler : _reloadHandlers) {
+ for (auto&& handler : _reloadHandlers) {
result = result && handler();
}
return result;
}
-
//! Register our custom types with Qt's Meta Object System.
/** This makes them available for QVariant and in signals/slots, among other things.
-*
-*/
+ *
+ */
void Quassel::registerMetaTypes()
{
// Complex types
}
}
-
void Quassel::setupEnvironment()
{
// On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This
#ifdef Q_OS_UNIX
QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
if (xdgDataVar.isEmpty())
- xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
+ xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
xdgDirs.append(appDir);
// Also append apps/quassel, this is only for QIconLoader to find icons there
xdgDirs.append(appDir + "/apps/quassel");
- } else
+ }
+ else
xdgDirs.append(appDir); // build directory is always the last fallback
xdgDirs.removeDuplicates();
#endif
}
-
void Quassel::setupBuildInfo()
{
BuildInfo buildInfo;
buildInfo.organizationName = "Quassel Project";
buildInfo.organizationDomain = "quassel-irc.org";
- buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
+ buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
buildInfo.baseVersion = QUASSEL_VERSION_STRING;
buildInfo.generatedVersion = GIT_DESCRIBE;
if (buildInfo.generatedVersion.isEmpty()) {
if (!buildInfo.commitHash.isEmpty()) {
// dist version
- buildInfo.plainVersionString = QString{"v%1 (dist-%2)"}
- .arg(buildInfo.baseVersion)
- .arg(buildInfo.commitHash.left(7));
+ buildInfo.plainVersionString = QString{"v%1 (dist-%2)"}.arg(buildInfo.baseVersion).arg(buildInfo.commitHash.left(7));
buildInfo.fancyVersionString = QString{"v%1 (dist-<a href=\"https://github.com/quassel/quassel/commit/%3\">%2</a>)"}
.arg(buildInfo.baseVersion)
.arg(buildInfo.commitHash.left(7))
instance()->_buildInfo = std::move(buildInfo);
}
-
-const Quassel::BuildInfo &Quassel::buildInfo()
+const Quassel::BuildInfo& Quassel::buildInfo()
{
return instance()->_buildInfo;
}
-
void Quassel::setupSignalHandling()
{
#ifndef Q_OS_WIN
connect(_signalWatcher, &AbstractSignalWatcher::handleSignal, this, &Quassel::handleSignal);
}
-
void Quassel::handleSignal(AbstractSignalWatcher::Action action)
{
switch (action) {
}
}
-
-Quassel::RunMode Quassel::runMode() {
+Quassel::RunMode Quassel::runMode()
+{
return instance()->_runMode;
}
-
void Quassel::setupCliParser()
{
QList<QCommandLineOption> options;
options += {{"c", "configdir"}, tr("Specify the directory holding the client configuration."), tr("path")};
}
else {
- options += {{"c", "configdir"}, tr("Specify the directory holding configuration files, the SQlite database and the SSL certificate."), tr("path")};
+ options += {{"c", "configdir"},
+ tr("Specify the directory holding configuration files, the SQlite database and the SSL certificate."),
+ tr("path")};
}
// Client options
{"select-backend", tr("Switch storage backend (migrating data if possible)."), tr("backendidentifier")},
{"select-authenticator", tr("Select authentication backend."), tr("authidentifier")},
{"add-user", tr("Starts an interactive session to add a new core user.")},
- {"change-userpass", tr("Starts an interactive session to change the password of the user identified by <username>."), tr("username")},
+ {"change-userpass",
+ tr("Starts an interactive session to change the password of the user identified by <username>."),
+ tr("username")},
{"strict-ident", tr("Use users' quasselcore username as ident reply. Ignores each user's configured ident setting.")},
{"ident-daemon", tr("Enable internal ident daemon.")},
- {"ident-port", tr("The port quasselcore will listen at for ident requests. Only meaningful with --ident-daemon."), tr("port"), "10113"},
+ {"ident-port",
+ tr("The port quasselcore will listen at for ident requests. Only meaningful with --ident-daemon."),
+ tr("port"),
+ "10113"},
{"oidentd", tr("Enable oidentd integration. In most cases you should also enable --strict-ident.")},
{"oidentd-conffile", tr("Set path to oidentd configuration file."), tr("file")},
#ifdef HAVE_SSL
_cliParser.process(*QCoreApplication::instance());
}
-
-QString Quassel::optionValue(const QString &key)
+QString Quassel::optionValue(const QString& key)
{
return instance()->_cliParser.value(key);
}
-
-bool Quassel::isOptionSet(const QString &key)
+bool Quassel::isOptionSet(const QString& key)
{
return instance()->_cliParser.isSet(key);
}
-
-const QString &Quassel::coreDumpFileName()
+const QString& Quassel::coreDumpFileName()
{
if (_coreDumpFileName.isEmpty()) {
QDir configDir(configDirPath());
- _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
+ _coreDumpFileName = configDir.absoluteFilePath(
+ QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
QFile dumpFile(_coreDumpFileName);
dumpFile.open(QIODevice::Append);
QTextStream dumpStream(&dumpFile);
return _coreDumpFileName;
}
-
QString Quassel::configDirPath()
{
if (!instance()->_configDirPath.isEmpty())
path = QDir::homePath() + "/Library/Application Support/Quassel/";
#else
// We abuse QSettings to find us a sensible path on the other platforms
-# ifdef Q_OS_WIN
+# ifdef Q_OS_WIN
// don't use the registry
QSettings::Format format = QSettings::IniFormat;
-# else
+# else
QSettings::Format format = QSettings::NativeFormat;
-# endif
+# endif
QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
QFileInfo fileInfo(s.fileName());
path = fileInfo.dir().absolutePath();
return path;
}
-
QStringList Quassel::dataDirPaths()
{
if (!instance()->_dataDirPaths.isEmpty())
QStringList dataDirNames;
#ifdef Q_OS_WIN
dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
- << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
- << QCoreApplication::applicationDirPath();
+ << qgetenv("APPDATA") + QCoreApplication::organizationDomain() << QCoreApplication::applicationDirPath();
#elif defined Q_OS_MAC
- dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
- << QCoreApplication::applicationDirPath();
+ dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/" << QCoreApplication::applicationDirPath();
#else
// Linux et al
// Now whatever is configured through XDG_DATA_DIRS
QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
if (xdgDataDirs.isEmpty())
- dataDirNames << "/usr/local/share" << "/usr/share";
+ dataDirNames << "/usr/local/share"
+ << "/usr/share";
else
dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
return dataDirNames;
}
-
-QString Quassel::findDataFilePath(const QString &fileName)
+QString Quassel::findDataFilePath(const QString& fileName)
{
QStringList dataDirs = dataDirPaths();
- foreach(QString dataDir, dataDirs) {
+ foreach (QString dataDir, dataDirs) {
QString path = dataDir + fileName;
if (QFile::exists(path))
return path;
return QString();
}
-
QStringList Quassel::scriptDirPaths()
{
QStringList res(configDirPath() + "scripts/");
- foreach(QString path, dataDirPaths())
- res << path + "scripts/";
+ foreach (QString path, dataDirPaths())
+ res << path + "scripts/";
return res;
}
-
QString Quassel::translationDirPath()
{
if (instance()->_translationDirPath.isEmpty()) {
// We support only one translation dir; fallback mechanisms wouldn't work else.
// This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
- foreach(const QString &dir, dataDirPaths()) {
+ foreach (const QString& dir, dataDirPaths()) {
if (QFile::exists(dir + "translations/")) {
instance()->_translationDirPath = dir + "translations/";
break;
return instance()->_translationDirPath;
}
-
-void Quassel::loadTranslation(const QLocale &locale)
+void Quassel::loadTranslation(const QLocale& locale)
{
- auto *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
- auto *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
+ auto* qtTranslator = QCoreApplication::instance()->findChild<QTranslator*>("QtTr");
+ auto* quasselTranslator = QCoreApplication::instance()->findChild<QTranslator*>("QuasselTr");
if (qtTranslator)
qApp->removeTranslator(qtTranslator);
qApp->installTranslator(qtTranslator);
}
-
// ---- Quassel::Features ---------------------------------------------------------------------------------------------
Quassel::Features::Features()
_features.resize(featureEnum.keyCount(), true); // enable all known features to true
}
-
-Quassel::Features::Features(const QStringList &features, LegacyFeatures legacyFeatures)
+Quassel::Features::Features(const QStringList& features, LegacyFeatures legacyFeatures)
{
// TODO Qt5: Use QMetaEnum::fromType()
auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
_features.resize(featureEnum.keyCount(), false);
- for (auto &&feature : features) {
+ for (auto&& feature : features) {
int i = featureEnum.keyToValue(qPrintable(feature));
if (i >= 0) {
_features[i] = true;
if (legacyFeatures) {
// TODO Qt5: Use QMetaEnum::fromType()
auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
- for (quint32 mask = 0x0001; mask <= 0x8000; mask <<=1) {
+ for (quint32 mask = 0x0001; mask <= 0x8000; mask <<= 1) {
if (static_cast<quint32>(legacyFeatures) & mask) {
int i = featureEnum.keyToValue(legacyFeatureEnum.valueToKey(mask));
if (i >= 0) {
}
}
-
bool Quassel::Features::isEnabled(Feature feature) const
{
auto i = static_cast<size_t>(feature);
return i < _features.size() ? _features[i] : false;
}
-
QStringList Quassel::Features::toStringList(bool enabled) const
{
// Check if any feature is enabled
return result;
}
-
Quassel::LegacyFeatures Quassel::Features::toLegacyFeatures() const
{
// TODO Qt5: Use LegacyFeatures (flag operators for enum classes not supported in Qt4)
return static_cast<LegacyFeatures>(result);
}
-
QStringList Quassel::Features::unknownFeatures() const
{
return _unknownFeatures;
Q_OBJECT
public:
- enum RunMode {
+ enum RunMode
+ {
Monolithic,
ClientOnly,
CoreOnly
};
- struct BuildInfo {
- QString fancyVersionString; // clickable rev
- QString plainVersionString; // no <a> tag
+ struct BuildInfo
+ {
+ QString fancyVersionString; // clickable rev
+ QString plainVersionString; // no <a> tag
QString baseVersion;
QString generatedVersion;
QString commitHash;
QString commitDate;
- uint protocolVersion; // deprecated
+ uint protocolVersion; // deprecated
QString applicationName;
QString coreApplicationName;
*
* @sa Feature
*/
- enum class LegacyFeature : quint32 {
+ enum class LegacyFeature : quint32
+ {
SynchronizedMarkerLine = 0x0001,
SaslAuthentication = 0x0002,
SaslExternal = 0x0004,
*
* This list should be cleaned up after every protocol break, as we can assume them to be present then.
*/
- enum class Feature : uint32_t {
+ enum class Feature : uint32_t
+ {
SynchronizedMarkerLine,
SaslAuthentication,
SaslExternal,
HideInactiveNetworks,
- PasswordChange, ///< Remote password change
- CapNegotiation, ///< IRCv3 capability negotiation, account tracking
- VerifyServerSSL, ///< IRC server SSL validation
- CustomRateLimits, ///< IRC server custom message rate limits
- AwayFormatTimestamp, ///< Timestamp formatting in away (e.g. %%hh:mm%%)
- Authenticators, ///< Whether or not the core supports auth backends
- BufferActivitySync, ///< Sync buffer activity status
- CoreSideHighlights, ///< Core-Side highlight configuration and matching
- SenderPrefixes, ///< Show prefixes for senders in backlog
- RemoteDisconnect, ///< Allow this peer to be remotely disconnected
- ExtendedFeatures, ///< Extended features
- LongTime, ///< Serialize time as 64-bit values
- RichMessages, ///< Real Name and Avatar URL in backlog
- BacklogFilterType, ///< BacklogManager supports filtering backlog by MessageType
- EcdsaCertfpKeys, ///< ECDSA keys for CertFP in identities
- LongMessageId, ///< 64-bit IDs for messages
- SyncedCoreInfo, ///< CoreInfo dynamically updated using signals
+ PasswordChange, ///< Remote password change
+ CapNegotiation, ///< IRCv3 capability negotiation, account tracking
+ VerifyServerSSL, ///< IRC server SSL validation
+ CustomRateLimits, ///< IRC server custom message rate limits
+ AwayFormatTimestamp, ///< Timestamp formatting in away (e.g. %%hh:mm%%)
+ Authenticators, ///< Whether or not the core supports auth backends
+ BufferActivitySync, ///< Sync buffer activity status
+ CoreSideHighlights, ///< Core-Side highlight configuration and matching
+ SenderPrefixes, ///< Show prefixes for senders in backlog
+ RemoteDisconnect, ///< Allow this peer to be remotely disconnected
+ ExtendedFeatures, ///< Extended features
+ LongTime, ///< Serialize time as 64-bit values
+ RichMessages, ///< Real Name and Avatar URL in backlog
+ BacklogFilterType, ///< BacklogManager supports filtering backlog by MessageType
+ EcdsaCertfpKeys, ///< ECDSA keys for CertFP in identities
+ LongMessageId, ///< 64-bit IDs for messages
+ SyncedCoreInfo, ///< CoreInfo dynamically updated using signals
};
Q_ENUMS(Feature)
*
* @returns The Logger instance
*/
- Logger *logger() const;
+ Logger* logger() const;
static void setupBuildInfo();
- static const BuildInfo &buildInfo();
+ static const BuildInfo& buildInfo();
static RunMode runMode();
static QString configDirPath();
//! Returns a list of data directory paths
/** There are several locations for applications to install their data files in. On Unix,
- * a common location is /usr/share; others include $PREFIX/share and additional directories
- * specified in the env variable XDG_DATA_DIRS.
- * \return A list of directory paths to look for data files in
- */
+ * a common location is /usr/share; others include $PREFIX/share and additional directories
+ * specified in the env variable XDG_DATA_DIRS.
+ * \return A list of directory paths to look for data files in
+ */
static QStringList dataDirPaths();
//! Searches for a data file in the possible data directories
/** Data files can reside in $DATA_DIR/apps/quassel, where $DATA_DIR is one of the directories
- * returned by \sa dataDirPaths().
- * \Note With KDE integration enabled, files are searched (only) in KDE's appdata dirs.
- * \return The full path to the data file if found; a null QString else
- */
- static QString findDataFilePath(const QString &filename);
+ * returned by \sa dataDirPaths().
+ * \Note With KDE integration enabled, files are searched (only) in KDE's appdata dirs.
+ * \return The full path to the data file if found; a null QString else
+ */
+ static QString findDataFilePath(const QString& filename);
static QString translationDirPath();
//! Returns a list of directories we look for scripts in
/** We look for a subdirectory named "scripts" in the configdir and in all datadir paths.
- * \return A list of directory paths containing executable scripts for /exec
- */
+ * \return A list of directory paths containing executable scripts for /exec
+ */
static QStringList scriptDirPaths();
- static void loadTranslation(const QLocale &locale);
+ static void loadTranslation(const QLocale& locale);
- static QString optionValue(const QString &option);
- static bool isOptionSet(const QString &option);
+ static QString optionValue(const QString& option);
+ static bool isOptionSet(const QString& option);
using ReloadHandler = std::function<bool()>;
*/
static void registerQuitHandler(QuitHandler quitHandler);
- const QString &coreDumpFileName();
+ const QString& coreDumpFileName();
public slots:
/**
void quit();
signals:
- void messageLogged(const QDateTime &timeStamp, const QString &msg);
+ void messageLogged(const QDateTime& timeStamp, const QString& msg);
private:
void registerMetaTypes();
*/
bool reloadConfig();
- void logBacktrace(const QString &filename);
+ void logBacktrace(const QString& filename);
private slots:
void handleSignal(AbstractSignalWatcher::Action action);
QCommandLineParser _cliParser;
- Logger *_logger;
- AbstractSignalWatcher *_signalWatcher{nullptr};
+ Logger* _logger;
+ AbstractSignalWatcher* _signalWatcher{nullptr};
std::vector<ReloadHandler> _reloadHandlers;
std::vector<QuitHandler> _quitHandlers;
* @param legacyFeatures Holds a bit-wise combination of LegacyFeature flag values, which are each added to the list of
* features represented by this Features instance.
*/
- Features(const QStringList &features, LegacyFeatures legacyFeatures);
+ Features(const QStringList& features, LegacyFeatures legacyFeatures);
/**
* Check if a given feature is marked as enabled in this Features instance.
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include <QtEndian>
-
#include <QHostAddress>
#include <QTimer>
+#include <QtEndian>
#ifdef HAVE_SSL
-# include <QSslSocket>
+# include <QSslSocket>
#else
-# include <QTcpSocket>
+# include <QTcpSocket>
#endif
#include "remotepeer.h"
using namespace Protocol;
-const quint32 maxMessageSize = 64 * 1024 * 1024; // This is uncompressed size. 64 MB should be enough for any sort of initData or backlog chunk
-
-RemotePeer::RemotePeer(::AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent)
- : Peer(authHandler, parent),
- _socket(socket),
- _compressor(new Compressor(socket, level, this)),
- _signalProxy(nullptr),
- _heartBeatTimer(new QTimer(this)),
- _heartBeatCount(0),
- _lag(0),
- _msgSize(0)
+const quint32 maxMessageSize = 64 * 1024
+ * 1024; // This is uncompressed size. 64 MB should be enough for any sort of initData or backlog chunk
+
+RemotePeer::RemotePeer(::AuthHandler* authHandler, QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent)
+ : Peer(authHandler, parent)
+ , _socket(socket)
+ , _compressor(new Compressor(socket, level, this))
+ , _signalProxy(nullptr)
+ , _heartBeatTimer(new QTimer(this))
+ , _heartBeatCount(0)
+ , _lag(0)
+ , _msgSize(0)
{
socket->setParent(this);
connect(socket, &QAbstractSocket::stateChanged, this, &RemotePeer::onSocketStateChanged);
connect(socket, &QAbstractSocket::disconnected, this, &Peer::disconnected);
#ifdef HAVE_SSL
- auto *sslSocket = qobject_cast<QSslSocket *>(socket);
+ auto* sslSocket = qobject_cast<QSslSocket*>(socket);
if (sslSocket) {
connect(sslSocket, &QSslSocket::encrypted, this, [this]() { emit secureStateChanged(true); });
}
connect(_heartBeatTimer, &QTimer::timeout, this, &RemotePeer::sendHeartBeat);
}
-
void RemotePeer::onSocketStateChanged(QAbstractSocket::SocketState state)
{
if (state == QAbstractSocket::ClosingState) {
}
}
-
void RemotePeer::onSocketError(QAbstractSocket::SocketError error)
{
emit socketError(error, socket()->errorString());
}
-
void RemotePeer::onCompressionError(Compressor::Error error)
{
close(QString("Compression error %1").arg(error));
}
-
QString RemotePeer::description() const
{
if (socket())
return 0;
}
-
-::SignalProxy *RemotePeer::signalProxy() const
+::SignalProxy* RemotePeer::signalProxy() const
{
return _signalProxy;
}
-
-void RemotePeer::setSignalProxy(::SignalProxy *proxy)
+void RemotePeer::setSignalProxy(::SignalProxy* proxy)
{
if (proxy == _signalProxy)
return;
}
}
-
void RemotePeer::changeHeartBeatInterval(int secs)
{
- if(secs <= 0)
+ if (secs <= 0)
_heartBeatTimer->stop();
else {
_heartBeatTimer->setInterval(secs * 1000);
}
}
-
int RemotePeer::lag() const
{
return _lag;
}
-
-QTcpSocket *RemotePeer::socket() const
+QTcpSocket* RemotePeer::socket() const
{
return _socket;
}
-
bool RemotePeer::isSecure() const
{
if (socket()) {
if (isLocal())
return true;
#ifdef HAVE_SSL
- auto *sslSocket = qobject_cast<QSslSocket *>(socket());
+ auto* sslSocket = qobject_cast<QSslSocket*>(socket());
if (sslSocket && sslSocket->isEncrypted())
return true;
#endif
return false;
}
-
bool RemotePeer::isLocal() const
{
if (socket()) {
return false;
}
-
bool RemotePeer::isOpen() const
{
return socket() && socket()->state() == QTcpSocket::ConnectedState;
}
-
-void RemotePeer::close(const QString &reason)
+void RemotePeer::close(const QString& reason)
{
if (!reason.isEmpty()) {
qWarning() << "Disconnecting:" << reason;
}
}
-
void RemotePeer::onReadyRead()
{
QByteArray msg;
}
}
-
-bool RemotePeer::readMessage(QByteArray &msg)
+bool RemotePeer::readMessage(QByteArray& msg)
{
if (_msgSize == 0) {
if (_compressor->bytesAvailable() < 4)
return true;
}
-
-void RemotePeer::writeMessage(const QByteArray &msg)
+void RemotePeer::writeMessage(const QByteArray& msg)
{
auto size = qToBigEndian<quint32>(msg.size());
_compressor->write((const char*)&size, 4, Compressor::NoFlush);
_compressor->write(msg.constData(), msg.size());
}
-
-void RemotePeer::handle(const HeartBeat &heartBeat)
+void RemotePeer::handle(const HeartBeat& heartBeat)
{
dispatch(HeartBeatReply(heartBeat.timestamp));
}
-
-void RemotePeer::handle(const HeartBeatReply &heartBeatReply)
+void RemotePeer::handle(const HeartBeatReply& heartBeatReply)
{
_heartBeatCount = 0;
emit lagUpdated(heartBeatReply.timestamp.msecsTo(QDateTime::currentDateTime().toUTC()) / 2);
}
-
void RemotePeer::sendHeartBeat()
{
if (signalProxy()->maxHeartBeatCount() > 0 && _heartBeatCount >= signalProxy()->maxHeartBeatCount()) {
- qWarning() << "Disconnecting peer:" << description()
- << "(didn't receive a heartbeat for over" << _heartBeatCount *_heartBeatTimer->interval() / 1000 << "seconds)";
+ qWarning() << "Disconnecting peer:" << description() << "(didn't receive a heartbeat for over"
+ << _heartBeatCount * _heartBeatTimer->interval() / 1000 << "seconds)";
socket()->close();
_heartBeatTimer->stop();
return;
public:
// import the virtuals from the baseclass
- using Peer::handle;
using Peer::dispatch;
+ using Peer::handle;
- RemotePeer(AuthHandler *authHandler, QTcpSocket *socket, Compressor::CompressionLevel level, QObject *parent = nullptr);
+ RemotePeer(AuthHandler* authHandler, QTcpSocket* socket, Compressor::CompressionLevel level, QObject* parent = nullptr);
- void setSignalProxy(SignalProxy *proxy) override;
+ void setSignalProxy(SignalProxy* proxy) override;
virtual QString protocolName() const = 0;
QString description() const override;
bool compressionEnabled() const;
void setCompressionEnabled(bool enabled);
- QTcpSocket *socket() const;
+ QTcpSocket* socket() const;
public slots:
- void close(const QString &reason = QString()) override;
+ void close(const QString& reason = QString()) override;
signals:
void transferProgress(int current, int max);
- void socketError(QAbstractSocket::SocketError error, const QString &errorString);
- void statusMessage(const QString &msg);
+ void socketError(QAbstractSocket::SocketError error, const QString& errorString);
+ void statusMessage(const QString& msg);
// Only used by LegacyPeer
void protocolVersionMismatch(int actual, int expected);
protected:
- SignalProxy *signalProxy() const override;
+ SignalProxy* signalProxy() const override;
- void writeMessage(const QByteArray &msg);
- virtual void processMessage(const QByteArray &msg) = 0;
+ void writeMessage(const QByteArray& msg);
+ virtual void processMessage(const QByteArray& msg) = 0;
// These protocol messages get handled internally and won't reach SignalProxy
- void handle(const Protocol::HeartBeat &heartBeat);
- void handle(const Protocol::HeartBeatReply &heartBeatReply);
- virtual void dispatch(const Protocol::HeartBeat &msg) = 0;
- virtual void dispatch(const Protocol::HeartBeatReply &msg) = 0;
+ void handle(const Protocol::HeartBeat& heartBeat);
+ void handle(const Protocol::HeartBeatReply& heartBeatReply);
+ virtual void dispatch(const Protocol::HeartBeat& msg) = 0;
+ virtual void dispatch(const Protocol::HeartBeatReply& msg) = 0;
protected slots:
virtual void onSocketStateChanged(QAbstractSocket::SocketState state);
void changeHeartBeatInterval(int secs);
private:
- bool readMessage(QByteArray &msg);
+ bool readMessage(QByteArray& msg);
private:
- QTcpSocket *_socket;
- Compressor *_compressor;
- SignalProxy *_signalProxy;
- QTimer *_heartBeatTimer;
+ QTcpSocket* _socket;
+ Compressor* _compressor;
+ SignalProxy* _signalProxy;
+ QTimer* _heartBeatTimer;
int _heartBeatCount;
int _lag;
quint32 _msgSize;
#include "serializers.h"
-bool checkStreamValid(QDataStream &stream)
+bool checkStreamValid(QDataStream& stream)
{
if (stream.status() != QDataStream::Ok) {
qWarning() << "Peer sent corrupt data";
return true;
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QVariantList &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QVariantList& data)
{
uint32_t size;
if (!deserialize(stream, features, size))
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QVariantMap &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QVariantMap& data)
{
uint32_t size;
if (!deserialize(stream, features, size))
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QVariant &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QVariant& data)
{
Types::VariantType type;
int8_t isNull;
name.chop(1);
if (!deserialize(stream, features, data, Types::fromName(name)))
return false;
- } else {
+ }
+ else {
if (!deserialize(stream, features, data, type))
return false;
}
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QVariant &data, Types::VariantType type)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QVariant& data, Types::VariantType type)
{
switch (type) {
- case Types::VariantType::Void: {
- return true;
- }
- case Types::VariantType::Bool: {
- bool content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::Int: {
- int32_t content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::UInt: {
- uint32_t content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::QChar: {
- QChar content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::QVariantMap: {
- QVariantMap content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::QVariantList: {
- QVariantList content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::QString: {
- QString content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::QStringList: {
- QStringList content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::QByteArray: {
- QByteArray content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::QDate: {
- QDate content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::QTime: {
- QTime content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::QDateTime: {
- QDateTime content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::Long: {
- qlonglong content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::Short: {
- int16_t content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::Char: {
- int8_t content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::ULong: {
- qulonglong content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::UShort: {
- uint16_t content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::UChar: {
- uint8_t content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- case Types::VariantType::QVariant: {
- QVariant content;
- if (!deserialize(stream, features, content))
- return false;
- data = QVariant(content);
- return true;
- }
- default: {
- qWarning() << "Usertype should have been caught earlier already";
+ case Types::VariantType::Void: {
+ return true;
+ }
+ case Types::VariantType::Bool: {
+ bool content;
+ if (!deserialize(stream, features, content))
return false;
- }
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::Int: {
+ int32_t content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::UInt: {
+ uint32_t content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::QChar: {
+ QChar content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::QVariantMap: {
+ QVariantMap content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::QVariantList: {
+ QVariantList content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::QString: {
+ QString content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::QStringList: {
+ QStringList content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::QByteArray: {
+ QByteArray content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::QDate: {
+ QDate content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::QTime: {
+ QTime content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::QDateTime: {
+ QDateTime content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::Long: {
+ qlonglong content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::Short: {
+ int16_t content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::Char: {
+ int8_t content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::ULong: {
+ qulonglong content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::UShort: {
+ uint16_t content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::UChar: {
+ uint8_t content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ case Types::VariantType::QVariant: {
+ QVariant content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = QVariant(content);
+ return true;
+ }
+ default: {
+ qWarning() << "Usertype should have been caught earlier already";
+ return false;
+ }
}
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QVariant &data, Types::QuasselType type)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QVariant& data, Types::QuasselType type)
{
switch (type) {
- case Types::QuasselType::BufferId: {
- BufferId content;
- if (!deserialize(stream, features, content))
- return false;
- data = qVariantFromValue(content);
- return true;
- }
- case Types::QuasselType::BufferInfo: {
- BufferInfo content;
- if (!deserialize(stream, features, content))
- return false;
- data = qVariantFromValue(content);
- return true;
- }
- case Types::QuasselType::Identity: {
- Identity content;
- if (!deserialize(stream, features, content))
- return false;
- data = qVariantFromValue(content);
- return true;
- }
- case Types::QuasselType::IdentityId: {
- IdentityId content;
- if (!deserialize(stream, features, content))
- return false;
- data = qVariantFromValue(content);
- return true;
- }
- case Types::QuasselType::Message: {
- Message content;
- if (!deserialize(stream, features, content))
- return false;
- data = qVariantFromValue(content);
- return true;
- }
- case Types::QuasselType::MsgId: {
- MsgId content;
- if (!deserialize(stream, features, content))
- return false;
- data = qVariantFromValue(content);
- return true;
- }
- case Types::QuasselType::NetworkId: {
- NetworkId content;
- if (!deserialize(stream, features, content))
- return false;
- data = qVariantFromValue(content);
- return true;
- }
- case Types::QuasselType::NetworkInfo: {
- NetworkInfo content;
- if (!deserialize(stream, features, content))
- return false;
- data = qVariantFromValue(content);
- return true;
- }
- case Types::QuasselType::Network_Server: {
- Network::Server content;
- if (!deserialize(stream, features, content))
- return false;
- data = qVariantFromValue(content);
- return true;
- }
- case Types::QuasselType::PeerPtr: {
- PeerPtr content;
- if (!deserialize(stream, features, content))
- return false;
- data = qVariantFromValue(content);
- return true;
- }
- default: {
- qWarning() << "Invalid QType";
+ case Types::QuasselType::BufferId: {
+ BufferId content;
+ if (!deserialize(stream, features, content))
return false;
- }
+ data = qVariantFromValue(content);
+ return true;
+ }
+ case Types::QuasselType::BufferInfo: {
+ BufferInfo content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = qVariantFromValue(content);
+ return true;
+ }
+ case Types::QuasselType::Identity: {
+ Identity content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = qVariantFromValue(content);
+ return true;
+ }
+ case Types::QuasselType::IdentityId: {
+ IdentityId content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = qVariantFromValue(content);
+ return true;
+ }
+ case Types::QuasselType::Message: {
+ Message content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = qVariantFromValue(content);
+ return true;
+ }
+ case Types::QuasselType::MsgId: {
+ MsgId content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = qVariantFromValue(content);
+ return true;
+ }
+ case Types::QuasselType::NetworkId: {
+ NetworkId content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = qVariantFromValue(content);
+ return true;
+ }
+ case Types::QuasselType::NetworkInfo: {
+ NetworkInfo content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = qVariantFromValue(content);
+ return true;
+ }
+ case Types::QuasselType::Network_Server: {
+ Network::Server content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = qVariantFromValue(content);
+ return true;
+ }
+ case Types::QuasselType::PeerPtr: {
+ PeerPtr content;
+ if (!deserialize(stream, features, content))
+ return false;
+ data = qVariantFromValue(content);
+ return true;
+ }
+ default: {
+ qWarning() << "Invalid QType";
+ return false;
+ }
}
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, Types::VariantType &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, Types::VariantType& data)
{
uint32_t raw;
if (!deserialize(stream, features, raw))
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QStringList &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QStringList& data)
{
uint32_t size;
if (!deserialize(stream, features, size))
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, Network::Server &server)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, Network::Server& server)
{
Q_UNUSED(features);
QVariantMap serverMap;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, Identity &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, Identity& data)
{
Q_UNUSED(features);
QVariantMap raw;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, NetworkInfo &info)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, NetworkInfo& info)
{
Q_UNUSED(features);
QVariantMap i;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, PeerPtr &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, PeerPtr& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QByteArray &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QByteArray& data)
{
Q_UNUSED(features);
data.clear();
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QString &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QString& data)
{
Q_UNUSED(features);
uint32_t bytes = 0;
while (allocated < length) {
int blockSize = std::min(step, length - allocated);
data.resize(allocated + blockSize);
- if (stream.readRawData(reinterpret_cast<char *>(data.data()) + allocated * 2, blockSize * 2) != blockSize * 2) {
+ if (stream.readRawData(reinterpret_cast<char*>(data.data()) + allocated * 2, blockSize * 2) != blockSize * 2) {
data.clear();
qWarning() << "BufferUnderFlow while reading QString";
return false;
allocated += blockSize;
}
if ((stream.byteOrder() == QDataStream::BigEndian) != (QSysInfo::ByteOrder == QSysInfo::BigEndian)) {
- auto *rawData = reinterpret_cast<uint16_t *>(data.data());
+ auto* rawData = reinterpret_cast<uint16_t*>(data.data());
while (length--) {
*rawData = qbswap(*rawData);
++rawData;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QChar &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QChar& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QDate &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QDate& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QTime &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QTime& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, QDateTime &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, QDateTime& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, int32_t &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, int32_t& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, uint32_t &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, uint32_t& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, int16_t &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, int16_t& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, uint16_t &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, uint16_t& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, int8_t &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, int8_t& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, uint8_t &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, uint8_t& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, qlonglong &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, qlonglong& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, qulonglong &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, qulonglong& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, bool &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, bool& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, BufferInfo &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, BufferInfo& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, Message &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, Message& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, NetworkId &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, NetworkId& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, IdentityId &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, IdentityId& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, BufferId &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, BufferId& data)
{
Q_UNUSED(features);
stream >> data;
return checkStreamValid(stream);
}
-bool Serializers::deserialize(QDataStream &stream, const Quassel::Features &features, MsgId &data)
+bool Serializers::deserialize(QDataStream& stream, const Quassel::Features& features, MsgId& data)
{
Q_UNUSED(features);
stream >> data;
Serializers::Types::VariantType Serializers::Types::variantType(Serializers::Types::QuasselType type)
{
switch (type) {
- case QuasselType::BufferId:
- return VariantType::UserType;
- case QuasselType::BufferInfo:
- return VariantType::UserType;
- case QuasselType::Identity:
- return VariantType::UserType;
- case QuasselType::IdentityId:
- return VariantType::UserType;
- case QuasselType::Message:
- return VariantType::UserType;
- case QuasselType::MsgId:
- return VariantType::UserType;
- case QuasselType::NetworkId:
- return VariantType::UserType;
- case QuasselType::NetworkInfo:
- return VariantType::UserType;
- case QuasselType::Network_Server:
- return VariantType::UserType;
- case QuasselType::PeerPtr:
- return VariantType::Long;
- default:
- return VariantType::UserType;
+ case QuasselType::BufferId:
+ return VariantType::UserType;
+ case QuasselType::BufferInfo:
+ return VariantType::UserType;
+ case QuasselType::Identity:
+ return VariantType::UserType;
+ case QuasselType::IdentityId:
+ return VariantType::UserType;
+ case QuasselType::Message:
+ return VariantType::UserType;
+ case QuasselType::MsgId:
+ return VariantType::UserType;
+ case QuasselType::NetworkId:
+ return VariantType::UserType;
+ case QuasselType::NetworkInfo:
+ return VariantType::UserType;
+ case QuasselType::Network_Server:
+ return VariantType::UserType;
+ case QuasselType::PeerPtr:
+ return VariantType::Long;
+ default:
+ return VariantType::UserType;
}
}
QString Serializers::Types::toName(Serializers::Types::QuasselType type)
{
switch (type) {
- case QuasselType::BufferId:
- return QString("BufferId");
- case QuasselType::BufferInfo:
- return QString("BufferInfo");
- case QuasselType::Identity:
- return QString("Identity");
- case QuasselType::IdentityId:
- return QString("IdentityId");
- case QuasselType::Message:
- return QString("Message");
- case QuasselType::MsgId:
- return QString("MsgId");
- case QuasselType::NetworkId:
- return QString("NetworkId");
- case QuasselType::NetworkInfo:
- return QString("NetworkInfo");
- case QuasselType::Network_Server:
- return QString("Network::Server");
- case QuasselType::PeerPtr:
- return QString("PeerPtr");
- default:
- return QString("Invalid Type");
- }
-}
-
-Serializers::Types::QuasselType Serializers::Types::fromName(::QByteArray &name)
-{
- if (qstrcmp(name, "BufferId") == 0) return QuasselType::BufferId;
- else if (qstrcmp(name, "BufferInfo") == 0) return QuasselType::BufferInfo;
- else if (qstrcmp(name, "Identity") == 0) return QuasselType::Identity;
- else if (qstrcmp(name, "IdentityId") == 0) return QuasselType::IdentityId;
- else if (qstrcmp(name, "Message") == 0) return QuasselType::Message;
- else if (qstrcmp(name, "MsgId") == 0) return QuasselType::MsgId;
- else if (qstrcmp(name, "NetworkId") == 0) return QuasselType::NetworkId;
- else if (qstrcmp(name, "NetworkInfo") == 0) return QuasselType::NetworkInfo;
- else if (qstrcmp(name, "Network::Server") == 0) return QuasselType::Network_Server;
- else if (qstrcmp(name, "PeerPtr") == 0) return QuasselType::PeerPtr;
+ case QuasselType::BufferId:
+ return QString("BufferId");
+ case QuasselType::BufferInfo:
+ return QString("BufferInfo");
+ case QuasselType::Identity:
+ return QString("Identity");
+ case QuasselType::IdentityId:
+ return QString("IdentityId");
+ case QuasselType::Message:
+ return QString("Message");
+ case QuasselType::MsgId:
+ return QString("MsgId");
+ case QuasselType::NetworkId:
+ return QString("NetworkId");
+ case QuasselType::NetworkInfo:
+ return QString("NetworkInfo");
+ case QuasselType::Network_Server:
+ return QString("Network::Server");
+ case QuasselType::PeerPtr:
+ return QString("PeerPtr");
+ default:
+ return QString("Invalid Type");
+ }
+}
+
+Serializers::Types::QuasselType Serializers::Types::fromName(::QByteArray& name)
+{
+ if (qstrcmp(name, "BufferId") == 0)
+ return QuasselType::BufferId;
+ else if (qstrcmp(name, "BufferInfo") == 0)
+ return QuasselType::BufferInfo;
+ else if (qstrcmp(name, "Identity") == 0)
+ return QuasselType::Identity;
+ else if (qstrcmp(name, "IdentityId") == 0)
+ return QuasselType::IdentityId;
+ else if (qstrcmp(name, "Message") == 0)
+ return QuasselType::Message;
+ else if (qstrcmp(name, "MsgId") == 0)
+ return QuasselType::MsgId;
+ else if (qstrcmp(name, "NetworkId") == 0)
+ return QuasselType::NetworkId;
+ else if (qstrcmp(name, "NetworkInfo") == 0)
+ return QuasselType::NetworkInfo;
+ else if (qstrcmp(name, "Network::Server") == 0)
+ return QuasselType::Network_Server;
+ else if (qstrcmp(name, "PeerPtr") == 0)
+ return QuasselType::PeerPtr;
else {
qWarning() << "Type name is not valid: " << name;
return QuasselType::Invalid;
#include "peer.h"
namespace Serializers {
- namespace Types {
- enum class VariantType : quint32 {
- Void = 0,
- Bool = 1,
- Int = 2,
- UInt = 3,
+namespace Types {
+enum class VariantType : quint32
+{
+ Void = 0,
+ Bool = 1,
+ Int = 2,
+ UInt = 3,
- QChar = 7,
- QVariantMap = 8,
- QVariantList = 9,
- QString = 10,
- QStringList = 11,
- QByteArray = 12,
+ QChar = 7,
+ QVariantMap = 8,
+ QVariantList = 9,
+ QString = 10,
+ QStringList = 11,
+ QByteArray = 12,
- QDate = 14,
- QTime = 15,
- QDateTime = 16,
+ QDate = 14,
+ QTime = 15,
+ QDateTime = 16,
- Long = 129,
- Short = 130,
- Char = 131,
- ULong = 132,
- UShort = 133,
- UChar = 134,
+ Long = 129,
+ Short = 130,
+ Char = 131,
+ ULong = 132,
+ UShort = 133,
+ UChar = 134,
- QVariant = 138,
+ QVariant = 138,
- UserType = 127
- };
+ UserType = 127
+};
- enum class QuasselType {
- Invalid,
- BufferId,
- BufferInfo,
- Identity,
- IdentityId,
- Message,
- MsgId,
- NetworkId,
- NetworkInfo,
- Network_Server,
- PeerPtr
- };
+enum class QuasselType
+{
+ Invalid,
+ BufferId,
+ BufferInfo,
+ Identity,
+ IdentityId,
+ Message,
+ MsgId,
+ NetworkId,
+ NetworkInfo,
+ Network_Server,
+ PeerPtr
+};
- VariantType variantType(QuasselType type);
- QString toName(QuasselType type);
- Types::QuasselType fromName(::QByteArray &name);
- }
+VariantType variantType(QuasselType type);
+QString toName(QuasselType type);
+Types::QuasselType fromName(::QByteArray& name);
+} // namespace Types
- bool deserialize(QDataStream &stream, const Quassel::Features &features, QVariant &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, QVariantList &list);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, QVariantMap &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, QVariant &data, Types::VariantType type);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, QVariant &data, Types::QuasselType type);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, bool &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, int8_t &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, uint8_t &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, int16_t &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, uint16_t &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, int32_t &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, uint32_t &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, qlonglong &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, qulonglong &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, Types::VariantType &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, QChar &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, QString &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, QTime &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, QDate &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, QDateTime &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, QByteArray &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, QStringList &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, Message &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, BufferInfo &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, BufferId &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, IdentityId &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, NetworkId &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, MsgId &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, PeerPtr &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, NetworkInfo &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, Identity &data);
- bool deserialize(QDataStream &stream, const Quassel::Features &features, Network::Server &data);
-}
+bool deserialize(QDataStream& stream, const Quassel::Features& features, QVariant& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, QVariantList& list);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, QVariantMap& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, QVariant& data, Types::VariantType type);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, QVariant& data, Types::QuasselType type);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, bool& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, int8_t& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, uint8_t& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, int16_t& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, uint16_t& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, int32_t& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, uint32_t& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, qlonglong& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, qulonglong& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, Types::VariantType& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, QChar& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, QString& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, QTime& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, QDate& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, QDateTime& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, QByteArray& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, QStringList& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, Message& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, BufferInfo& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, BufferId& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, IdentityId& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, NetworkId& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, MsgId& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, PeerPtr& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, NetworkInfo& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, Identity& data);
+bool deserialize(QDataStream& stream, const Quassel::Features& features, Network::Server& data);
+} // namespace Serializers
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include <QStringList>
-
#include "settings.h"
-const int VERSION = 1; /// Settings version for backwords/forwards incompatible changes
+#include <QStringList>
+
+const int VERSION = 1; /// Settings version for backwords/forwards incompatible changes
// This is used if no VersionMinor key exists, e.g. upgrading from a Quassel version before this
// change. This shouldn't be increased from 1; instead, change the logic in Core::Core() and
// QtUiApplication::init() to handle upgrading and downgrading.
-const int VERSION_MINOR_INITIAL = 1; /// Initial settings version for compatible changes
+const int VERSION_MINOR_INITIAL = 1; /// Initial settings version for compatible changes
QHash<QString, QVariant> Settings::_settingsCache;
QHash<QString, bool> Settings::_settingsKeyPersistedCache;
QHash<QString, std::shared_ptr<SettingsChangeNotifier>> Settings::_settingsChangeNotifier;
#ifdef Q_OS_MAC
-# define create_qsettings QSettings s(QCoreApplication::organizationDomain(), _appName)
+# define create_qsettings QSettings s(QCoreApplication::organizationDomain(), _appName)
#else
-# define create_qsettings QSettings s(fileName(), format())
+# define create_qsettings QSettings s(fileName(), format())
#endif
Settings::Settings(QString group, QString appName)
- : _group(std::move(group)), _appName(std::move(appName))
+ : _group(std::move(group))
+ , _appName(std::move(appName))
{}
-
-void Settings::setGroup(QString group) {
+void Settings::setGroup(QString group)
+{
_group = std::move(group);
}
-
-QString Settings::keyForNotify(const QString &key) const
+QString Settings::keyForNotify(const QString& key) const
{
return key;
}
-
uint Settings::version() const
{
// we don't cache this value, and we ignore the group
return ver;
}
-
uint Settings::versionMinor() const
{
// Don't cache this value; ignore the group
// const_cast is ok, because setVersionMinor() doesn't actually change this instance
const_cast<Settings*>(this)->setVersionMinor(VERSION_MINOR_INITIAL);
return VERSION_MINOR_INITIAL;
- } else {
+ }
+ else {
return verMinor;
}
}
-
void Settings::setVersionMinor(const uint versionMinor)
{
// Don't cache this value; ignore the group
s.setValue("Config/VersionMinor", versionMinor);
}
-
QSettings::Format Settings::format() const
{
#ifdef Q_OS_WIN
#endif
}
-
bool Settings::sync()
{
create_qsettings;
s.sync();
switch (s.status()) {
- case QSettings::NoError:
- return true;
- default:
- return false;
+ case QSettings::NoError:
+ return true;
+ default:
+ return false;
}
}
-
bool Settings::isWritable() const
{
create_qsettings;
return s.isWritable();
}
-
QStringList Settings::allLocalKeys() const
{
create_qsettings;
return res;
}
-
-QStringList Settings::localChildKeys(const QString &rootkey) const
+QStringList Settings::localChildKeys(const QString& rootkey) const
{
QString g;
if (rootkey.isEmpty())
return res;
}
-
-QStringList Settings::localChildGroups(const QString &rootkey) const
+QStringList Settings::localChildGroups(const QString& rootkey) const
{
QString g;
if (rootkey.isEmpty())
return res;
}
-
-void Settings::setLocalValue(const QString &key, const QVariant &data)
+void Settings::setLocalValue(const QString& key, const QVariant& data)
{
QString normKey = normalizedKey(_group, key);
create_qsettings;
}
}
-
-QVariant Settings::localValue(const QString &key, const QVariant &def) const
+QVariant Settings::localValue(const QString& key, const QVariant& def) const
{
QString normKey = normalizedKey(_group, key);
if (!isCached(normKey)) {
return def;
}
-
-bool Settings::localKeyExists(const QString &key) const
+bool Settings::localKeyExists(const QString& key) const
{
QString normKey = normalizedKey(_group, key);
if (!isKeyPersistedCached(normKey)) {
return cacheKeyPersisted(normKey);
}
-
-void Settings::removeLocalKey(const QString &key)
+void Settings::removeLocalKey(const QString& key)
{
create_qsettings;
s.beginGroup(_group);
}
}
-
QString Settings::fileName() const
{
- return Quassel::configDirPath() + _appName
- + ((format() == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
+ return Quassel::configDirPath() + _appName + ((format() == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
}
-
-QString Settings::normalizedKey(const QString &group, const QString &key) const
+QString Settings::normalizedKey(const QString& group, const QString& key) const
{
if (group.isEmpty())
return key;
return group + '/' + key;
}
-
-void Settings::setCacheKeyPersisted(const QString &normKey, bool exists) const
+void Settings::setCacheKeyPersisted(const QString& normKey, bool exists) const
{
_settingsKeyPersistedCache[normKey] = exists;
}
-
-bool Settings::cacheKeyPersisted(const QString &normKey) const
+bool Settings::cacheKeyPersisted(const QString& normKey) const
{
return _settingsKeyPersistedCache[normKey];
}
-
-bool Settings::isKeyPersistedCached(const QString &normKey) const
+bool Settings::isKeyPersistedCached(const QString& normKey) const
{
return _settingsKeyPersistedCache.contains(normKey);
}
-
-void Settings::setCacheValue(const QString &normKey, const QVariant &data) const
+void Settings::setCacheValue(const QString& normKey, const QVariant& data) const
{
_settingsCache[normKey] = data;
}
-
-QVariant Settings::cacheValue(const QString &normKey) const
+QVariant Settings::cacheValue(const QString& normKey) const
{
return _settingsCache[normKey];
}
-
-bool Settings::isCached(const QString &normKey) const
+bool Settings::isCached(const QString& normKey) const
{
return _settingsCache.contains(normKey);
}
-
-SettingsChangeNotifier *Settings::notifier(const QString &normKey) const
+SettingsChangeNotifier* Settings::notifier(const QString& normKey) const
{
if (!hasNotifier(normKey))
_settingsChangeNotifier[normKey] = std::make_shared<SettingsChangeNotifier>();
return _settingsChangeNotifier[normKey].get();
}
-
-bool Settings::hasNotifier(const QString &normKey) const
+bool Settings::hasNotifier(const QString& normKey) const
{
return _settingsChangeNotifier.contains(normKey);
}
#include <memory>
#include <type_traits>
+#include <utility>
#include <QCoreApplication>
#include <QHash>
#include <QSettings>
#include <QString>
#include <QVariant>
-#include <utility>
#include "quassel.h"
Q_OBJECT
signals:
- void valueChanged(const QVariant &newValue);
+ void valueChanged(const QVariant& newValue);
private:
friend class Settings;
};
-
class COMMON_EXPORT Settings
{
public:
- enum Mode { Default, Custom };
+ enum Mode
+ {
+ Default,
+ Custom
+ };
public:
//! Calls the given slot on change of the given key
template<typename Receiver, typename Slot>
- void notify(const QString &key, const Receiver *receiver, Slot slot) const
+ void notify(const QString& key, const Receiver* receiver, Slot slot) const
{
static_assert(!std::is_same<Slot, const char*>::value, "Old-style slots not supported");
QObject::connect(notifier(normalizedKey(_group, keyForNotify(key))), &SettingsChangeNotifier::valueChanged, receiver, slot);
//! Sets up notification and calls the given slot to set the initial value
template<typename Receiver, typename Slot>
- void initAndNotify(const QString &key, const Receiver *receiver, Slot slot, const QVariant &defaultValue = {}) const
+ void initAndNotify(const QString& key, const Receiver* receiver, Slot slot, const QVariant& defaultValue = {}) const
{
notify(key, receiver, std::move(slot));
auto notifyKey = keyForNotify(key);
* @param key Key given to notify()
* @returns Key that should be used for notfication
*/
- virtual QString keyForNotify(const QString &key) const;
+ virtual QString keyForNotify(const QString& key) const;
virtual QStringList allLocalKeys() const;
- virtual QStringList localChildKeys(const QString &rootkey = QString()) const;
- virtual QStringList localChildGroups(const QString &rootkey = QString()) const;
+ virtual QStringList localChildKeys(const QString& rootkey = QString()) const;
+ virtual QStringList localChildGroups(const QString& rootkey = QString()) const;
- virtual void setLocalValue(const QString &key, const QVariant &data);
- virtual QVariant localValue(const QString &key, const QVariant &def = QVariant()) const;
+ virtual void setLocalValue(const QString& key, const QVariant& data);
+ virtual QVariant localValue(const QString& key, const QVariant& def = QVariant()) const;
/**
* Gets if a key exists in settings
* @param[in] key ID of local settings key
* @returns True if key exists in settings, otherwise false
*/
- virtual bool localKeyExists(const QString &key) const;
+ virtual bool localKeyExists(const QString& key) const;
- virtual void removeLocalKey(const QString &key);
+ virtual void removeLocalKey(const QString& key);
QString _group;
QString _appName;
QString fileName() const;
- QString normalizedKey(const QString &group, const QString &key) const;
+ QString normalizedKey(const QString& group, const QString& key) const;
/**
* Update the cache of whether or not a given settings key persists on disk
* @param normKey Normalized settings key ID
* @param exists True if key exists, otherwise false
*/
- void setCacheKeyPersisted(const QString &normKey, bool exists) const;
+ void setCacheKeyPersisted(const QString& normKey, bool exists) const;
/**
* Check if the given settings key ID persists on disk (rather than being a default value)
* @param normKey Normalized settings key ID
* @return True if key exists and persistence has been cached, otherwise false
*/
- bool cacheKeyPersisted(const QString &normKey) const;
+ bool cacheKeyPersisted(const QString& normKey) const;
/**
* Check if the persistence of the given settings key ID has been cached
* @param normKey Normalized settings key ID
* @return True if key persistence has been cached, otherwise false
*/
- bool isKeyPersistedCached(const QString &normKey) const;
+ bool isKeyPersistedCached(const QString& normKey) const;
- void setCacheValue(const QString &normKey, const QVariant &data) const;
+ void setCacheValue(const QString& normKey, const QVariant& data) const;
- QVariant cacheValue(const QString &normKey) const;
+ QVariant cacheValue(const QString& normKey) const;
- bool isCached(const QString &normKey) const;
+ bool isCached(const QString& normKey) const;
- SettingsChangeNotifier *notifier(const QString &normKey) const;
+ SettingsChangeNotifier* notifier(const QString& normKey) const;
- bool hasNotifier(const QString &normKey) const;
+ bool hasNotifier(const QString& normKey) const;
private:
- static QHash<QString, QVariant> _settingsCache; ///< Cached settings values
- static QHash<QString, bool> _settingsKeyPersistedCache; ///< Cached settings key exists on disk
+ static QHash<QString, QVariant> _settingsCache; ///< Cached settings values
+ static QHash<QString, bool> _settingsKeyPersistedCache; ///< Cached settings key exists on disk
static QHash<QString, std::shared_ptr<SettingsChangeNotifier>> _settingsChangeNotifier;
};
#include <QThread>
#ifdef HAVE_SSL
- #include <QSslSocket>
+# include <QSslSocket>
#endif
-#include "signalproxy.h"
-
#include "peer.h"
#include "protocol.h"
+#include "signalproxy.h"
#include "syncableobject.h"
-#include "util.h"
#include "types.h"
+#include "util.h"
using namespace Protocol;
class RemovePeerEvent : public QEvent
{
public:
- RemovePeerEvent(Peer *peer) : QEvent(QEvent::Type(SignalProxy::RemovePeerEvent)), peer(peer) {}
- Peer *peer;
+ RemovePeerEvent(Peer* peer)
+ : QEvent(QEvent::Type(SignalProxy::RemovePeerEvent))
+ , peer(peer)
+ {}
+ Peer* peer;
};
-
// ==================================================
// SignalRelay
// ==================================================
class SignalProxy::SignalRelay : public QObject
{
-/* Q_OBJECT is not necessary or even allowed, because we implement
- qt_metacall ourselves (and don't use any other features of the meta
- object system)
-*/
+ /* Q_OBJECT is not necessary or even allowed, because we implement
+ qt_metacall ourselves (and don't use any other features of the meta
+ object system)
+ */
public:
- SignalRelay(SignalProxy *parent) : QObject(parent), _proxy(parent) {}
- inline SignalProxy *proxy() const { return _proxy; }
+ SignalRelay(SignalProxy* parent)
+ : QObject(parent)
+ , _proxy(parent)
+ {}
+ inline SignalProxy* proxy() const { return _proxy; }
- int qt_metacall(QMetaObject::Call _c, int _id, void **_a) override;
+ int qt_metacall(QMetaObject::Call _c, int _id, void** _a) override;
- void attachSignal(QObject *sender, int signalId, const QByteArray &funcName);
- void detachSignal(QObject *sender, int signalId = -1);
+ void attachSignal(QObject* sender, int signalId, const QByteArray& funcName);
+ void detachSignal(QObject* sender, int signalId = -1);
private:
- struct Signal {
- QObject *sender{nullptr};
+ struct Signal
+ {
+ QObject* sender{nullptr};
int signalId{-1};
QByteArray signature;
- Signal(QObject *sender, int sigId, QByteArray signature) : sender(sender), signalId(sigId), signature(std::move(signature)) {}
+ Signal(QObject* sender, int sigId, QByteArray signature)
+ : sender(sender)
+ , signalId(sigId)
+ , signature(std::move(signature))
+ {}
Signal() = default;
};
- SignalProxy *_proxy;
+ SignalProxy* _proxy;
QHash<int, Signal> _slots;
};
-
-void SignalProxy::SignalRelay::attachSignal(QObject *sender, int signalId, const QByteArray &funcName)
+void SignalProxy::SignalRelay::attachSignal(QObject* sender, int signalId, const QByteArray& funcName)
{
// we ride without safetybelts here... all checking for valid method etc pp has to be done by the caller
// all connected methodIds are offset by the standard methodCount of QObject
QMetaObject::connect(sender, signalId, this, QObject::staticMetaObject.methodCount() + slotId);
}
-
-void SignalProxy::SignalRelay::detachSignal(QObject *sender, int signalId)
+void SignalProxy::SignalRelay::detachSignal(QObject* sender, int signalId)
{
QHash<int, Signal>::iterator slotIter = _slots.begin();
while (slotIter != _slots.end()) {
}
}
-
-int SignalProxy::SignalRelay::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
+int SignalProxy::SignalRelay::qt_metacall(QMetaObject::Call _c, int _id, void** _a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
if (_c == QMetaObject::InvokeMetaMethod) {
if (_slots.contains(_id)) {
- QObject *caller = sender();
+ QObject* caller = sender();
- SignalProxy::ExtendedMetaObject *eMeta = proxy()->extendedMetaObject(caller->metaObject());
+ SignalProxy::ExtendedMetaObject* eMeta = proxy()->extendedMetaObject(caller->metaObject());
Q_ASSERT(eMeta);
- const Signal &signal = _slots[_id];
+ const Signal& signal = _slots[_id];
QVariantList params;
- const QList<int> &argTypes = eMeta->argTypes(signal.signalId);
+ const QList<int>& argTypes = eMeta->argTypes(signal.signalId);
for (int i = 0; i < argTypes.size(); i++) {
if (argTypes[i] == 0) {
- qWarning() << "SignalRelay::qt_metacall(): received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(caller->metaObject()->className()).arg(caller->metaObject()->method(signal.signalId).methodSignature().constData());
+ qWarning() << "SignalRelay::qt_metacall(): received invalid data for argument number" << i << "of signal"
+ << QString("%1::%2")
+ .arg(caller->metaObject()->className())
+ .arg(caller->metaObject()->method(signal.signalId).methodSignature().constData());
qWarning() << " - make sure all your data types are known by the Qt MetaSystem";
return _id;
}
- params << QVariant(argTypes[i], _a[i+1]);
+ params << QVariant(argTypes[i], _a[i + 1]);
}
if (proxy()->_restrictMessageTarget) {
if (peer != nullptr)
proxy()->dispatch(peer, RpcCall(signal.signature, params));
}
- } else
+ }
+ else
proxy()->dispatch(RpcCall(signal.signature, params));
}
_id -= _slots.count();
return _id;
}
-
// ==================================================
// SignalProxy
// ==================================================
namespace {
-thread_local SignalProxy *_current{nullptr};
+thread_local SignalProxy* _current{nullptr};
}
-SignalProxy::SignalProxy(QObject *parent)
+SignalProxy::SignalProxy(QObject* parent)
: QObject(parent)
{
setProxyMode(Client);
init();
}
-
-SignalProxy::SignalProxy(ProxyMode mode, QObject *parent)
+SignalProxy::SignalProxy(ProxyMode mode, QObject* parent)
: QObject(parent)
{
setProxyMode(mode);
init();
}
-
SignalProxy::~SignalProxy()
{
QHash<QByteArray, ObjectId>::iterator classIter = _syncSlave.begin();
while (classIter != _syncSlave.end()) {
ObjectId::iterator objIter = classIter->begin();
while (objIter != classIter->end()) {
- SyncableObject *obj = objIter.value();
+ SyncableObject* obj = objIter.value();
objIter = classIter->erase(objIter);
obj->stopSynchronize(this);
}
_current = nullptr;
}
-
-SignalProxy *SignalProxy::current()
+SignalProxy* SignalProxy::current()
{
return _current;
}
-
void SignalProxy::setProxyMode(ProxyMode mode)
{
if (!_peerMap.empty()) {
updateSecureState();
}
-
-void SignalProxy::initServer()
-{
-}
-
+void SignalProxy::initServer() {}
void SignalProxy::initClient()
{
- attachSlot("__objectRenamed__", this, SLOT(objectRenamed(QByteArray,QString,QString)));
+ attachSlot("__objectRenamed__", this, SLOT(objectRenamed(QByteArray, QString, QString)));
}
-
void SignalProxy::setHeartBeatInterval(int secs)
{
if (_heartBeatInterval != secs) {
}
}
-
void SignalProxy::setMaxHeartBeatCount(int max)
{
if (_maxHeartBeatCount != max) {
}
}
-
-bool SignalProxy::addPeer(Peer *peer)
+bool SignalProxy::addPeer(Peer* peer)
{
if (!peer)
return false;
return true;
}
-
void SignalProxy::removeAllPeers()
{
Q_ASSERT(proxyMode() == Server || peerCount() <= 1);
// wee need to copy that list since we modify it in the loop
- QList<Peer *> peers = _peerMap.values();
+ QList<Peer*> peers = _peerMap.values();
for (auto peer : peers) {
removePeer(peer);
}
}
-
-void SignalProxy::removePeer(Peer *peer)
+void SignalProxy::removePeer(Peer* peer)
{
if (!peer) {
qWarning() << Q_FUNC_INFO << "Trying to remove a null peer!";
emit disconnected();
}
-
void SignalProxy::removePeerBySender()
{
- removePeer(qobject_cast<Peer *>(sender()));
+ removePeer(qobject_cast<Peer*>(sender()));
}
-
-void SignalProxy::renameObject(const SyncableObject *obj, const QString &newname, const QString &oldname)
+void SignalProxy::renameObject(const SyncableObject* obj, const QString& newname, const QString& oldname)
{
if (proxyMode() == Client)
return;
- const QMetaObject *meta = obj->syncMetaObject();
+ const QMetaObject* meta = obj->syncMetaObject();
const QByteArray className(meta->className());
objectRenamed(className, newname, oldname);
dispatch(RpcCall("__objectRenamed__", QVariantList() << className << newname << oldname));
}
-
-void SignalProxy::objectRenamed(const QByteArray &classname, const QString &newname, const QString &oldname)
+void SignalProxy::objectRenamed(const QByteArray& classname, const QString& newname, const QString& oldname)
{
if (_syncSlave.contains(classname) && _syncSlave[classname].contains(oldname) && oldname != newname) {
- SyncableObject *obj = _syncSlave[classname][newname] = _syncSlave[classname].take(oldname);
+ SyncableObject* obj = _syncSlave[classname][newname] = _syncSlave[classname].take(oldname);
requestInit(obj);
}
}
-
-const QMetaObject *SignalProxy::metaObject(const QObject *obj)
+const QMetaObject* SignalProxy::metaObject(const QObject* obj)
{
- if (const auto *syncObject = qobject_cast<const SyncableObject *>(obj))
+ if (const auto* syncObject = qobject_cast<const SyncableObject*>(obj))
return syncObject->syncMetaObject();
else
return obj->metaObject();
}
-
-SignalProxy::ExtendedMetaObject *SignalProxy::extendedMetaObject(const QMetaObject *meta) const
+SignalProxy::ExtendedMetaObject* SignalProxy::extendedMetaObject(const QMetaObject* meta) const
{
if (_extendedMetaObjects.contains(meta))
return _extendedMetaObjects[meta];
return nullptr;
}
-
-SignalProxy::ExtendedMetaObject *SignalProxy::createExtendedMetaObject(const QMetaObject *meta, bool checkConflicts)
+SignalProxy::ExtendedMetaObject* SignalProxy::createExtendedMetaObject(const QMetaObject* meta, bool checkConflicts)
{
if (!_extendedMetaObjects.contains(meta)) {
_extendedMetaObjects[meta] = new ExtendedMetaObject(meta, checkConflicts);
return _extendedMetaObjects[meta];
}
-
-bool SignalProxy::attachSignal(QObject *sender, const char *signal, const QByteArray &sigName)
+bool SignalProxy::attachSignal(QObject* sender, const char* signal, const QByteArray& sigName)
{
- const QMetaObject *meta = sender->metaObject();
+ const QMetaObject* meta = sender->metaObject();
QByteArray sig(meta->normalizedSignature(signal).mid(1));
int methodId = meta->indexOfMethod(sig.constData());
if (methodId == -1 || meta->method(methodId).methodType() != QMetaMethod::Signal) {
return true;
}
-
-bool SignalProxy::attachSlot(const QByteArray &sigName, QObject *recv, const char *slot)
+bool SignalProxy::attachSlot(const QByteArray& sigName, QObject* recv, const char* slot)
{
- const QMetaObject *meta = recv->metaObject();
+ const QMetaObject* meta = recv->metaObject();
int methodId = meta->indexOfMethod(meta->normalizedSignature(slot).mid(1));
if (methodId == -1 || meta->method(methodId).methodType() == QMetaMethod::Method) {
qWarning() << "SignalProxy::attachSlot(): No such slot" << slot;
return true;
}
-
-void SignalProxy::synchronize(SyncableObject *obj)
+void SignalProxy::synchronize(SyncableObject* obj)
{
createExtendedMetaObject(obj, true);
obj->synchronize(this);
}
-
-void SignalProxy::detachObject(QObject *obj)
+void SignalProxy::detachObject(QObject* obj)
{
// Don't try to connect SignalProxy from itself on shutdown
if (obj != this) {
}
}
-
-void SignalProxy::detachSignals(QObject *sender)
+void SignalProxy::detachSignals(QObject* sender)
{
_signalRelay->detachSignal(sender);
}
-
-void SignalProxy::detachSlots(QObject *receiver)
+void SignalProxy::detachSlots(QObject* receiver)
{
SlotHash::iterator slotIter = _attachedSlots.begin();
while (slotIter != _attachedSlots.end()) {
}
}
-
-void SignalProxy::stopSynchronize(SyncableObject *obj)
+void SignalProxy::stopSynchronize(SyncableObject* obj)
{
// we can't use a className here, since it might be effed up, if we receive the call as a result of a decon
// gladly the objectName() is still valid. So we have only to iterate over the classes not each instance! *sigh*
obj->stopSynchronize(this);
}
-
template<class T>
-void SignalProxy::dispatch(const T &protoMessage)
+void SignalProxy::dispatch(const T& protoMessage)
{
for (auto&& peer : _peerMap.values()) {
dispatch(peer, protoMessage);
}
}
-
template<class T>
-void SignalProxy::dispatch(Peer *peer, const T &protoMessage)
+void SignalProxy::dispatch(Peer* peer, const T& protoMessage)
{
_targetPeer = peer;
_targetPeer = nullptr;
}
-
-void SignalProxy::handle(Peer *peer, const SyncMessage &syncMessage)
+void SignalProxy::handle(Peer* peer, const SyncMessage& syncMessage)
{
if (!_syncSlave.contains(syncMessage.className) || !_syncSlave[syncMessage.className].contains(syncMessage.objectName)) {
- qWarning() << QString("no registered receiver for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
+ qWarning() << QString("no registered receiver for sync call: %1::%2 (objectName=\"%3\"). Params are:")
+ .arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
<< syncMessage.params;
return;
}
- SyncableObject *receiver = _syncSlave[syncMessage.className][syncMessage.objectName];
- ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
+ SyncableObject* receiver = _syncSlave[syncMessage.className][syncMessage.objectName];
+ ExtendedMetaObject* eMeta = extendedMetaObject(receiver);
if (!eMeta->slotMap().contains(syncMessage.slotName)) {
- qWarning() << QString("no matching slot for sync call: %1::%2 (objectName=\"%3\"). Params are:").arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
+ qWarning() << QString("no matching slot for sync call: %1::%2 (objectName=\"%3\"). Params are:")
+ .arg(syncMessage.className, syncMessage.slotName, syncMessage.objectName)
<< syncMessage.params;
return;
}
invokeSlot(receiver, eMeta->updatedRemotelyId());
}
-
-void SignalProxy::handle(Peer *peer, const InitRequest &initRequest)
+void SignalProxy::handle(Peer* peer, const InitRequest& initRequest)
{
- if (!_syncSlave.contains(initRequest.className)) {
- qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Class:"
- << initRequest.className;
+ if (!_syncSlave.contains(initRequest.className)) {
+ qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Class:" << initRequest.className;
return;
}
if (!_syncSlave[initRequest.className].contains(initRequest.objectName)) {
- qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Object:"
- << initRequest.className << initRequest.objectName;
+ qWarning() << "SignalProxy::handleInitRequest() received initRequest for unregistered Object:" << initRequest.className
+ << initRequest.objectName;
return;
}
- SyncableObject *obj = _syncSlave[initRequest.className][initRequest.objectName];
+ SyncableObject* obj = _syncSlave[initRequest.className][initRequest.objectName];
_targetPeer = peer;
peer->dispatch(InitData(initRequest.className, initRequest.objectName, initData(obj)));
_targetPeer = nullptr;
}
-
-void SignalProxy::handle(Peer *peer, const InitData &initData)
+void SignalProxy::handle(Peer* peer, const InitData& initData)
{
Q_UNUSED(peer)
if (!_syncSlave.contains(initData.className)) {
- qWarning() << "SignalProxy::handleInitData() received initData for unregistered Class:"
- << initData.className;
+ qWarning() << "SignalProxy::handleInitData() received initData for unregistered Class:" << initData.className;
return;
}
if (!_syncSlave[initData.className].contains(initData.objectName)) {
- qWarning() << "SignalProxy::handleInitData() received initData for unregistered Object:"
- << initData.className << initData.objectName;
+ qWarning() << "SignalProxy::handleInitData() received initData for unregistered Object:" << initData.className << initData.objectName;
return;
}
- SyncableObject *obj = _syncSlave[initData.className][initData.objectName];
+ SyncableObject* obj = _syncSlave[initData.className][initData.objectName];
setInitData(obj, initData.initData);
}
-
-void SignalProxy::handle(Peer *peer, const RpcCall &rpcCall)
+void SignalProxy::handle(Peer* peer, const RpcCall& rpcCall)
{
- QObject *receiver;
+ QObject* receiver;
int methodId;
SlotHash::const_iterator slot = _attachedSlots.constFind(rpcCall.slotName);
while (slot != _attachedSlots.constEnd() && slot.key() == rpcCall.slotName) {
receiver = (*slot).first;
methodId = (*slot).second;
if (!invokeSlot(receiver, methodId, rpcCall.params, peer)) {
- ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
+ ExtendedMetaObject* eMeta = extendedMetaObject(receiver);
qWarning("SignalProxy::handleSignal(): invokeMethod for \"%s\" failed ", eMeta->methodName(methodId).constData());
}
++slot;
}
}
-
-bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList ¶ms, QVariant &returnValue, Peer *peer)
+bool SignalProxy::invokeSlot(QObject* receiver, int methodId, const QVariantList& params, QVariant& returnValue, Peer* peer)
{
- ExtendedMetaObject *eMeta = extendedMetaObject(receiver);
+ ExtendedMetaObject* eMeta = extendedMetaObject(receiver);
const QList<int> args = eMeta->argTypes(methodId);
- const int numArgs = params.count() < args.count()
- ? params.count()
- : args.count();
+ const int numArgs = params.count() < args.count() ? params.count() : args.count();
if (eMeta->minArgCount(methodId) > params.count()) {
qWarning() << "SignalProxy::invokeSlot(): not enough params to invoke" << eMeta->methodName(methodId);
return false;
}
- void *_a[] = { nullptr, // return type...
- nullptr, nullptr, nullptr, nullptr, nullptr, // and 10 args - that's the max size qt can handle with signals and slots
- nullptr, nullptr, nullptr, nullptr, nullptr };
+ void* _a[] = {nullptr, // return type...
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr, // and 10 args - that's the max size qt can handle with signals and slots
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr};
// check for argument compatibility and build params array
for (int i = 0; i < numArgs; i++) {
if (!params[i].isValid()) {
- qWarning() << "SignalProxy::invokeSlot(): received invalid data for argument number" << i << "of method" << QString("%1::%2()").arg(receiver->metaObject()->className()).arg(receiver->metaObject()->method(methodId).methodSignature().constData());
+ qWarning() << "SignalProxy::invokeSlot(): received invalid data for argument number" << i << "of method"
+ << QString("%1::%2()")
+ .arg(receiver->metaObject()->className())
+ .arg(receiver->metaObject()->method(methodId).methodSignature().constData());
qWarning() << " - make sure all your data types are known by the Qt MetaSystem";
return false;
}
return false;
}
- _a[i+1] = const_cast<void *>(params[i].constData());
+ _a[i + 1] = const_cast<void*>(params[i].constData());
}
if (returnValue.type() != QVariant::Invalid)
- _a[0] = const_cast<void *>(returnValue.constData());
+ _a[0] = const_cast<void*>(returnValue.constData());
- Qt::ConnectionType type = QThread::currentThread() == receiver->thread()
- ? Qt::DirectConnection
- : Qt::QueuedConnection;
+ Qt::ConnectionType type = QThread::currentThread() == receiver->thread() ? Qt::DirectConnection : Qt::QueuedConnection;
if (type == Qt::DirectConnection) {
_sourcePeer = peer;
auto result = receiver->qt_metacall(QMetaObject::InvokeMetaMethod, methodId, _a) < 0;
_sourcePeer = nullptr;
return result;
- } else {
+ }
+ else {
qWarning() << "Queued Connections are not implemented yet";
// note to self: qmetaobject.cpp:990 ff
return false;
}
}
-
-bool SignalProxy::invokeSlot(QObject *receiver, int methodId, const QVariantList ¶ms, Peer *peer)
+bool SignalProxy::invokeSlot(QObject* receiver, int methodId, const QVariantList& params, Peer* peer)
{
QVariant ret;
return invokeSlot(receiver, methodId, params, ret, peer);
}
-
-void SignalProxy::requestInit(SyncableObject *obj)
+void SignalProxy::requestInit(SyncableObject* obj)
{
if (proxyMode() == Server || obj->isInitialized())
return;
dispatch(InitRequest(obj->syncMetaObject()->className(), obj->objectName()));
}
-
-QVariantMap SignalProxy::initData(SyncableObject *obj) const
+QVariantMap SignalProxy::initData(SyncableObject* obj) const
{
return obj->toVariantMap();
}
-
-void SignalProxy::setInitData(SyncableObject *obj, const QVariantMap &properties)
+void SignalProxy::setInitData(SyncableObject* obj, const QVariantMap& properties)
{
if (obj->isInitialized())
return;
invokeSlot(obj, extendedMetaObject(obj)->updatedRemotelyId());
}
-
-void SignalProxy::customEvent(QEvent *event)
+void SignalProxy::customEvent(QEvent* event)
{
switch ((int)event->type()) {
case RemovePeerEvent: {
- auto *e = static_cast< ::RemovePeerEvent *>(event);
+ auto* e = static_cast<::RemovePeerEvent*>(event);
removePeer(e->peer);
event->accept();
break;
}
}
-
-void SignalProxy::sync_call__(const SyncableObject *obj, SignalProxy::ProxyMode modeType, const char *funcname, va_list ap)
+void SignalProxy::sync_call__(const SyncableObject* obj, SignalProxy::ProxyMode modeType, const char* funcname, va_list ap)
{
// qDebug() << obj << modeType << "(" << _proxyMode << ")" << funcname;
if (modeType != _proxyMode)
return;
- ExtendedMetaObject *eMeta = extendedMetaObject(obj);
+ ExtendedMetaObject* eMeta = extendedMetaObject(obj);
QVariantList params;
- const QList<int> &argTypes = eMeta->argTypes(eMeta->methodId(QByteArray(funcname)));
+ const QList<int>& argTypes = eMeta->argTypes(eMeta->methodId(QByteArray(funcname)));
for (int i = 0; i < argTypes.size(); i++) {
if (argTypes[i] == 0) {
- qWarning() << Q_FUNC_INFO << "received invalid data for argument number" << i << "of signal" << QString("%1::%2").arg(eMeta->metaObject()->className()).arg(funcname);
+ qWarning() << Q_FUNC_INFO << "received invalid data for argument number" << i << "of signal"
+ << QString("%1::%2").arg(eMeta->metaObject()->className()).arg(funcname);
qWarning() << " - make sure all your data types are known by the Qt MetaSystem";
return;
}
- params << QVariant(argTypes[i], va_arg(ap, void *));
+ params << QVariant(argTypes[i], va_arg(ap, void*));
}
if (_restrictMessageTarget) {
if (peer != nullptr)
dispatch(peer, SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
}
- } else
+ }
+ else
dispatch(SyncMessage(eMeta->metaObject()->className(), obj->objectName(), QByteArray(funcname), params));
}
-
-void SignalProxy::disconnectDevice(QIODevice *dev, const QString &reason)
+void SignalProxy::disconnectDevice(QIODevice* dev, const QString& reason)
{
if (!reason.isEmpty())
qWarning() << qPrintable(reason);
- auto *sock = qobject_cast<QAbstractSocket *>(dev);
+ auto* sock = qobject_cast<QAbstractSocket*>(dev);
if (sock)
qWarning() << qPrintable(tr("Disconnecting")) << qPrintable(sock->peerAddress().toString());
dev->close();
}
-
void SignalProxy::dumpProxyStats()
{
QString mode;
mode = "Client";
int slaveCount = 0;
- foreach(ObjectId oid, _syncSlave.values())
- slaveCount += oid.count();
+ foreach (ObjectId oid, _syncSlave.values())
+ slaveCount += oid.count();
qDebug() << this;
qDebug() << " Proxy Mode:" << mode;
qDebug() << "number of Classes cached:" << _extendedMetaObjects.count();
}
-
void SignalProxy::updateSecureState()
{
bool wasSecure = _secure;
_secure = !_peerMap.isEmpty();
- for (auto peer : _peerMap.values()) {
+ for (auto peer : _peerMap.values()) {
_secure &= peer->isSecure();
}
emit secureStateChanged(_secure);
}
-QVariantList SignalProxy::peerData() {
+QVariantList SignalProxy::peerData()
+{
QVariantList result;
- for (auto &&peer : _peerMap.values()) {
+ for (auto&& peer : _peerMap.values()) {
QVariantMap data;
data["id"] = peer->id();
data["clientVersion"] = peer->clientVersion();
return result;
}
-Peer *SignalProxy::peerById(int peerId) {
+Peer* SignalProxy::peerById(int peerId)
+{
// We use ::value() here instead of the [] operator because the latter has the side-effect
// of automatically inserting a null value with the passed key into the map. See
// https://doc.qt.io/qt-5/qhash.html#operator-5b-5d and https://doc.qt.io/qt-5/qhash.html#value.
_restrictedTargets = previousRestrictedTargets;
}
-Peer *SignalProxy::sourcePeer() {
+Peer* SignalProxy::sourcePeer()
+{
return _sourcePeer;
}
-void SignalProxy::setSourcePeer(Peer *sourcePeer) {
+void SignalProxy::setSourcePeer(Peer* sourcePeer)
+{
_sourcePeer = sourcePeer;
}
-Peer *SignalProxy::targetPeer() {
+Peer* SignalProxy::targetPeer()
+{
return _targetPeer;
}
-void SignalProxy::setTargetPeer(Peer *targetPeer) {
+void SignalProxy::setTargetPeer(Peer* targetPeer)
+{
_targetPeer = targetPeer;
}
// ==================================================
// ExtendedMetaObject
// ==================================================
-SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject *meta, bool checkConflicts)
- : _meta(meta),
- _updatedRemotelyId(_meta->indexOfSignal("updatedRemotely()"))
+SignalProxy::ExtendedMetaObject::ExtendedMetaObject(const QMetaObject* meta, bool checkConflicts)
+ : _meta(meta)
+ , _updatedRemotelyId(_meta->indexOfSignal("updatedRemotely()"))
{
for (int i = 0; i < _meta->methodCount(); i++) {
if (_meta->method(i).methodType() != QMetaMethod::Slot)
/* funny... moc creates for methods containing default parameters multiple metaMethod with separate methodIds.
we don't care... we just need the full fledged version
*/
- const QMetaMethod ¤t = _meta->method(_methodIds[method]);
- const QMetaMethod &candidate = _meta->method(i);
+ const QMetaMethod& current = _meta->method(_methodIds[method]);
+ const QMetaMethod& candidate = _meta->method(i);
if (current.parameterTypes().count() > candidate.parameterTypes().count()) {
int minCount = candidate.parameterTypes().count();
QList<QByteArray> commonParams = current.parameterTypes().mid(0, minCount);
int minCount = current.parameterTypes().count();
QList<QByteArray> commonParams = candidate.parameterTypes().mid(0, minCount);
if (commonParams == current.parameterTypes()) {
- _methodIds[method] = i; // use the new one
+ _methodIds[method] = i; // use the new one
continue;
}
}
if (checkConflicts) {
qWarning() << "class" << meta->className() << "contains overloaded methods which is currently not supported!";
- qWarning() << " - " << _meta->method(i).methodSignature() << "conflicts with" << _meta->method(_methodIds[method]).methodSignature();
+ qWarning() << " - " << _meta->method(i).methodSignature() << "conflicts with"
+ << _meta->method(_methodIds[method]).methodSignature();
}
continue;
}
}
}
-
-const SignalProxy::ExtendedMetaObject::MethodDescriptor &SignalProxy::ExtendedMetaObject::methodDescriptor(int methodId)
+const SignalProxy::ExtendedMetaObject::MethodDescriptor& SignalProxy::ExtendedMetaObject::methodDescriptor(int methodId)
{
if (!_methods.contains(methodId)) {
_methods[methodId] = MethodDescriptor(_meta->method(methodId));
return _methods[methodId];
}
-
-const QHash<int, int> &SignalProxy::ExtendedMetaObject::receiveMap()
+const QHash<int, int>& SignalProxy::ExtendedMetaObject::receiveMap()
{
if (_receiveMap.isEmpty()) {
QHash<int, int> receiveMap;
return _receiveMap;
}
-
-QByteArray SignalProxy::ExtendedMetaObject::methodName(const QMetaMethod &method)
+QByteArray SignalProxy::ExtendedMetaObject::methodName(const QMetaMethod& method)
{
QByteArray sig(method.methodSignature());
return sig.left(sig.indexOf("("));
}
-
-QString SignalProxy::ExtendedMetaObject::methodBaseName(const QMetaMethod &method)
+QString SignalProxy::ExtendedMetaObject::methodBaseName(const QMetaMethod& method)
{
QString methodname = QString(method.methodSignature()).section("(", 0, 0);
return methodname;
}
-
-SignalProxy::ExtendedMetaObject::MethodDescriptor::MethodDescriptor(const QMetaMethod &method)
- : _methodName(SignalProxy::ExtendedMetaObject::methodName(method)),
- _returnType(QMetaType::type(method.typeName()))
+SignalProxy::ExtendedMetaObject::MethodDescriptor::MethodDescriptor(const QMetaMethod& method)
+ : _methodName(SignalProxy::ExtendedMetaObject::methodName(method))
+ , _returnType(QMetaType::type(method.typeName()))
{
// determine argTypes
QList<QByteArray> paramTypes = method.parameterTypes();
QString signature(method.methodSignature());
_minArgCount = method.parameterTypes().count() - signature.count("=");
- _receiverMode = (_methodName.startsWith("request"))
- ? SignalProxy::Server
- : SignalProxy::Client;
+ _receiverMode = (_methodName.startsWith("request")) ? SignalProxy::Server : SignalProxy::Client;
}
#include "common-export.h"
-#include <QEvent>
-#include <QSet>
-
#include <functional>
#include <initializer_list>
+#include <QEvent>
+#include <QSet>
+
#include "protocol.h"
struct QMetaObject;
class SignalRelay;
public:
- enum ProxyMode {
+ enum ProxyMode
+ {
Server,
Client
};
- enum EventType {
+ enum EventType
+ {
RemovePeerEvent = QEvent::User
};
- SignalProxy(QObject *parent);
- SignalProxy(ProxyMode mode, QObject *parent);
+ SignalProxy(QObject* parent);
+ SignalProxy(ProxyMode mode, QObject* parent);
~SignalProxy() override;
void setProxyMode(ProxyMode mode);
void setMaxHeartBeatCount(int max);
inline int maxHeartBeatCount() const { return _maxHeartBeatCount; }
- bool addPeer(Peer *peer);
+ bool addPeer(Peer* peer);
- bool attachSignal(QObject *sender, const char *signal, const QByteArray &sigName = QByteArray());
- bool attachSlot(const QByteArray &sigName, QObject *recv, const char *slot);
+ bool attachSignal(QObject* sender, const char* signal, const QByteArray& sigName = QByteArray());
+ bool attachSlot(const QByteArray& sigName, QObject* recv, const char* slot);
- void synchronize(SyncableObject *obj);
- void stopSynchronize(SyncableObject *obj);
+ void synchronize(SyncableObject* obj);
+ void stopSynchronize(SyncableObject* obj);
class ExtendedMetaObject;
- ExtendedMetaObject *extendedMetaObject(const QMetaObject *meta) const;
- ExtendedMetaObject *createExtendedMetaObject(const QMetaObject *meta, bool checkConflicts = false);
- inline ExtendedMetaObject *extendedMetaObject(const QObject *obj) const { return extendedMetaObject(metaObject(obj)); }
- inline ExtendedMetaObject *createExtendedMetaObject(const QObject *obj, bool checkConflicts = false) { return createExtendedMetaObject(metaObject(obj), checkConflicts); }
+ ExtendedMetaObject* extendedMetaObject(const QMetaObject* meta) const;
+ ExtendedMetaObject* createExtendedMetaObject(const QMetaObject* meta, bool checkConflicts = false);
+ inline ExtendedMetaObject* extendedMetaObject(const QObject* obj) const { return extendedMetaObject(metaObject(obj)); }
+ inline ExtendedMetaObject* createExtendedMetaObject(const QObject* obj, bool checkConflicts = false)
+ {
+ return createExtendedMetaObject(metaObject(obj), checkConflicts);
+ }
bool isSecure() const { return _secure; }
void dumpProxyStats();
- void dumpSyncMap(SyncableObject *object);
+ void dumpSyncMap(SyncableObject* object);
- static SignalProxy *current();
+ static SignalProxy* current();
/**@{*/
/**
* @param closure Code you want to execute within of that restricted environment
*/
void restrictTargetPeers(QSet<Peer*> peers, std::function<void()> closure);
- void restrictTargetPeers(Peer *peer, std::function<void()> closure) {
+ void restrictTargetPeers(Peer* peer, std::function<void()> closure)
+ {
QSet<Peer*> set;
set.insert(peer);
restrictTargetPeers(set, std::move(closure));
}
- //A better version, but only implemented on Qt5 if Initializer Lists exist
+ // A better version, but only implemented on Qt5 if Initializer Lists exist
#ifdef Q_COMPILER_INITIALIZER_LISTS
- void restrictTargetPeers(std::initializer_list<Peer*> peers, std::function<void()> closure) {
+ void restrictTargetPeers(std::initializer_list<Peer*> peers, std::function<void()> closure)
+ {
restrictTargetPeers(QSet<Peer*>(peers), std::move(closure));
}
#endif
inline int peerCount() const { return _peerMap.size(); }
QVariantList peerData();
- Peer *peerById(int peerId);
+ Peer* peerById(int peerId);
/**
* @return If handling a signal, the Peer from which the current signal originates
*/
- Peer *sourcePeer();
- void setSourcePeer(Peer *sourcePeer);
+ Peer* sourcePeer();
+ void setSourcePeer(Peer* sourcePeer);
/**
* @return If sending a signal, the Peer to which the current signal is directed
*/
- Peer *targetPeer();
- void setTargetPeer(Peer *targetPeer);
+ Peer* targetPeer();
+ void setTargetPeer(Peer* targetPeer);
public slots:
- void detachObject(QObject *obj);
- void detachSignals(QObject *sender);
- void detachSlots(QObject *receiver);
+ void detachObject(QObject* obj);
+ void detachSignals(QObject* sender);
+ void detachSlots(QObject* receiver);
protected:
- void customEvent(QEvent *event) override;
- void sync_call__(const SyncableObject *obj, ProxyMode modeType, const char *funcname, va_list ap);
- void renameObject(const SyncableObject *obj, const QString &newname, const QString &oldname);
+ void customEvent(QEvent* event) override;
+ void sync_call__(const SyncableObject* obj, ProxyMode modeType, const char* funcname, va_list ap);
+ void renameObject(const SyncableObject* obj, const QString& newname, const QString& oldname);
private slots:
void removePeerBySender();
- void objectRenamed(const QByteArray &classname, const QString &newname, const QString &oldname);
+ void objectRenamed(const QByteArray& classname, const QString& newname, const QString& oldname);
void updateSecureState();
signals:
- void peerRemoved(Peer *peer);
+ void peerRemoved(Peer* peer);
void connected();
void disconnected();
- void objectInitialized(SyncableObject *);
+ void objectInitialized(SyncableObject*);
void heartBeatIntervalChanged(int secs);
void maxHeartBeatCountChanged(int max);
void lagUpdated(int lag);
void initServer();
void initClient();
- static const QMetaObject *metaObject(const QObject *obj);
+ static const QMetaObject* metaObject(const QObject* obj);
- void removePeer(Peer *peer);
+ void removePeer(Peer* peer);
void removeAllPeers();
- int nextPeerId() {
- return _lastPeerId++;
- }
+ int nextPeerId() { return _lastPeerId++; }
template<class T>
- void dispatch(const T &protoMessage);
+ void dispatch(const T& protoMessage);
template<class T>
- void dispatch(Peer *peer, const T &protoMessage);
+ void dispatch(Peer* peer, const T& protoMessage);
- void handle(Peer *peer, const Protocol::SyncMessage &syncMessage);
- void handle(Peer *peer, const Protocol::RpcCall &rpcCall);
- void handle(Peer *peer, const Protocol::InitRequest &initRequest);
- void handle(Peer *peer, const Protocol::InitData &initData);
+ void handle(Peer* peer, const Protocol::SyncMessage& syncMessage);
+ void handle(Peer* peer, const Protocol::RpcCall& rpcCall);
+ void handle(Peer* peer, const Protocol::InitRequest& initRequest);
+ void handle(Peer* peer, const Protocol::InitData& initData);
template<class T>
- void handle(Peer *, T) { Q_ASSERT(0); }
+ void handle(Peer*, T)
+ {
+ Q_ASSERT(0);
+ }
- bool invokeSlot(QObject *receiver, int methodId, const QVariantList ¶ms, QVariant &returnValue, Peer *peer = nullptr);
- bool invokeSlot(QObject *receiver, int methodId, const QVariantList ¶ms = QVariantList(), Peer *peer = nullptr);
+ bool invokeSlot(QObject* receiver, int methodId, const QVariantList& params, QVariant& returnValue, Peer* peer = nullptr);
+ bool invokeSlot(QObject* receiver, int methodId, const QVariantList& params = QVariantList(), Peer* peer = nullptr);
- void requestInit(SyncableObject *obj);
- QVariantMap initData(SyncableObject *obj) const;
- void setInitData(SyncableObject *obj, const QVariantMap &properties);
+ void requestInit(SyncableObject* obj);
+ QVariantMap initData(SyncableObject* obj) const;
+ void setInitData(SyncableObject* obj, const QVariantMap& properties);
- static void disconnectDevice(QIODevice *dev, const QString &reason = QString());
+ static void disconnectDevice(QIODevice* dev, const QString& reason = QString());
QHash<int, Peer*> _peerMap;
// containg a list of argtypes for fast access
- QHash<const QMetaObject *, ExtendedMetaObject *> _extendedMetaObjects;
+ QHash<const QMetaObject*, ExtendedMetaObject*> _extendedMetaObjects;
// SignalRelay for all manually attached signals
- SignalRelay *_signalRelay;
+ SignalRelay* _signalRelay;
// RPC function -> (object, slot ID)
- using MethodId = QPair<QObject *, int>;
+ using MethodId = QPair<QObject*, int>;
using SlotHash = QMultiHash<QByteArray, MethodId>;
SlotHash _attachedSlots;
// slaves for sync
- using ObjectId = QHash<QString, SyncableObject *>;
+ using ObjectId = QHash<QString, SyncableObject*>;
QHash<QByteArray, ObjectId> _syncSlave;
ProxyMode _proxyMode;
int _heartBeatInterval;
int _maxHeartBeatCount;
- bool _secure; // determines if all connections are in a secured state (using ssl or internal connections)
+ bool _secure; // determines if all connections are in a secured state (using ssl or internal connections)
int _lastPeerId = 0;
- QSet<Peer *> _restrictedTargets;
+ QSet<Peer*> _restrictedTargets;
bool _restrictMessageTarget = false;
- Peer *_sourcePeer = nullptr;
- Peer *_targetPeer = nullptr;
+ Peer* _sourcePeer = nullptr;
+ Peer* _targetPeer = nullptr;
friend class SignalRelay;
friend class SyncableObject;
friend class Peer;
};
-
// ==================================================
// ExtendedMetaObject
// ==================================================
class MethodDescriptor
{
public:
- MethodDescriptor(const QMetaMethod &method);
+ MethodDescriptor(const QMetaMethod& method);
MethodDescriptor() = default;
- inline const QByteArray &methodName() const { return _methodName; }
- inline const QList<int> &argTypes() const { return _argTypes; }
+ inline const QByteArray& methodName() const { return _methodName; }
+ inline const QList<int>& argTypes() const { return _argTypes; }
inline int returnType() const { return _returnType; }
inline int minArgCount() const { return _minArgCount; }
inline SignalProxy::ProxyMode receiverMode() const { return _receiverMode; }
QList<int> _argTypes;
int _returnType{-1};
int _minArgCount{-1};
- SignalProxy::ProxyMode _receiverMode{SignalProxy::Client}; // Only acceptable as a Sync Call if the receiving SignalProxy is in this mode.
+ SignalProxy::ProxyMode _receiverMode{
+ SignalProxy::Client}; // Only acceptable as a Sync Call if the receiving SignalProxy is in this mode.
};
-
public:
- ExtendedMetaObject(const QMetaObject *meta, bool checkConflicts);
+ ExtendedMetaObject(const QMetaObject* meta, bool checkConflicts);
- inline const QByteArray &methodName(int methodId) { return methodDescriptor(methodId).methodName(); }
- inline const QList<int> &argTypes(int methodId) { return methodDescriptor(methodId).argTypes(); }
+ inline const QByteArray& methodName(int methodId) { return methodDescriptor(methodId).methodName(); }
+ inline const QList<int>& argTypes(int methodId) { return methodDescriptor(methodId).argTypes(); }
inline int returnType(int methodId) { return methodDescriptor(methodId).returnType(); }
inline int minArgCount(int methodId) { return methodDescriptor(methodId).minArgCount(); }
inline SignalProxy::ProxyMode receiverMode(int methodId) { return methodDescriptor(methodId).receiverMode(); }
- inline int methodId(const QByteArray &methodName) { return _methodIds.contains(methodName) ? _methodIds[methodName] : -1; }
+ inline int methodId(const QByteArray& methodName) { return _methodIds.contains(methodName) ? _methodIds[methodName] : -1; }
inline int updatedRemotelyId() { return _updatedRemotelyId; }
- inline const QHash<QByteArray, int> &slotMap() { return _methodIds; }
- const QHash<int, int> &receiveMap();
+ inline const QHash<QByteArray, int>& slotMap() { return _methodIds; }
+ const QHash<int, int>& receiveMap();
- const QMetaObject *metaObject() const { return _meta; }
+ const QMetaObject* metaObject() const { return _meta; }
- static QByteArray methodName(const QMetaMethod &method);
- static QString methodBaseName(const QMetaMethod &method);
+ static QByteArray methodName(const QMetaMethod& method);
+ static QString methodBaseName(const QMetaMethod& method);
private:
- const MethodDescriptor &methodDescriptor(int methodId);
+ const MethodDescriptor& methodDescriptor(int methodId);
- const QMetaObject *_meta;
- int _updatedRemotelyId; // id of the updatedRemotely() signal - makes things faster
+ const QMetaObject* _meta;
+ int _updatedRemotelyId; // id of the updatedRemotely() signal - makes things faster
QHash<int, MethodDescriptor> _methods;
QHash<QByteArray, int> _methodIds;
- QHash<int, int> _receiveMap; // if slot x is called then hand over the result to slot y
+ QHash<int, int> _receiveMap; // if slot x is called then hand over the result to slot y
};
// We need to export the function on anything not using Windows DLLs, otherwise local static members don't
// work across library boundaries.
template<typename T>
-QUASSEL_SINGLETON_EXPORT T *getOrSetInstance(T *instance = nullptr, bool destroyed = false)
+QUASSEL_SINGLETON_EXPORT T* getOrSetInstance(T* instance = nullptr, bool destroyed = false)
{
- static T *_instance = instance;
+ static T* _instance = instance;
static bool _destroyed = destroyed;
if (destroyed) {
*
* @param instance Pointer to the instance being created, i.e. the 'this' pointer of the parent class
*/
- Singleton(T *instance)
+ Singleton(T* instance)
{
detail::getOrSetInstance<T>(instance);
}
// Satisfy Rule of Five
- Singleton(const Singleton &) = delete;
- Singleton(Singleton &&) = delete;
- Singleton &operator=(const Singleton &) = delete;
- Singleton &operator=(Singleton &&) = delete;
+ Singleton(const Singleton&) = delete;
+ Singleton(Singleton&&) = delete;
+ Singleton& operator=(const Singleton&) = delete;
+ Singleton& operator=(Singleton&&) = delete;
/**
* Destructor.
*
* @returns A pointer to the instance
*/
- static T *instance()
+ static T* instance()
{
return detail::getOrSetInstance<T>();
}
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include <QMetaProperty>
+#include "syncableobject.h"
#include <QDebug>
-
-#include "syncableobject.h"
+#include <QMetaProperty>
#include "signalproxy.h"
#include "util.h"
-SyncableObject::SyncableObject(QObject *parent)
+SyncableObject::SyncableObject(QObject* parent)
: QObject(parent)
-{
-}
+{}
-
-SyncableObject::SyncableObject(const QString &objectName, QObject *parent)
+SyncableObject::SyncableObject(const QString& objectName, QObject* parent)
: QObject(parent)
{
setObjectName(objectName);
}
-
-SyncableObject::SyncableObject(const SyncableObject &other, QObject *parent)
- : QObject(parent),
- _initialized(other._initialized),
- _allowClientUpdates(other._allowClientUpdates)
-{
-}
-
+SyncableObject::SyncableObject(const SyncableObject& other, QObject* parent)
+ : QObject(parent)
+ , _initialized(other._initialized)
+ , _allowClientUpdates(other._allowClientUpdates)
+{}
SyncableObject::~SyncableObject()
{
- QList<SignalProxy *>::iterator proxyIter = _signalProxies.begin();
+ QList<SignalProxy*>::iterator proxyIter = _signalProxies.begin();
while (proxyIter != _signalProxies.end()) {
- SignalProxy *proxy = (*proxyIter);
+ SignalProxy* proxy = (*proxyIter);
proxyIter = _signalProxies.erase(proxyIter);
proxy->stopSynchronize(this);
}
}
-
-SyncableObject &SyncableObject::operator=(const SyncableObject &other)
+SyncableObject& SyncableObject::operator=(const SyncableObject& other)
{
if (this == &other)
return *this;
return *this;
}
-
bool SyncableObject::isInitialized() const
{
return _initialized;
}
-
void SyncableObject::setInitialized()
{
_initialized = true;
emit initDone();
}
-
QVariantMap SyncableObject::toVariantMap()
{
QVariantMap properties;
- const QMetaObject *meta = metaObject();
+ const QMetaObject* meta = metaObject();
// we collect data from properties
QMetaProperty prop;
QVariant::Type variantType = QVariant::nameToType(method.typeName());
if (variantType == QVariant::Invalid && !QByteArray(method.typeName()).isEmpty()) {
- qWarning() << "SyncableObject::toVariantMap(): cannot fetch init data for:" << this << method.methodSignature() << "- Returntype is unknown to Qt's MetaSystem:" << QByteArray(method.typeName());
+ qWarning() << "SyncableObject::toVariantMap(): cannot fetch init data for:" << this << method.methodSignature()
+ << "- Returntype is unknown to Qt's MetaSystem:" << QByteArray(method.typeName());
continue;
}
- QVariant value(variantType, (const void *)nullptr);
+ QVariant value(variantType, (const void*)nullptr);
QGenericReturnArgument genericvalue = QGenericReturnArgument(method.typeName(), value.data());
QMetaObject::invokeMethod(this, methodname.toLatin1(), genericvalue);
return properties;
}
-
-void SyncableObject::fromVariantMap(const QVariantMap &properties)
+void SyncableObject::fromVariantMap(const QVariantMap& properties)
{
- const QMetaObject *meta = metaObject();
+ const QMetaObject* meta = metaObject();
QVariantMap::const_iterator iterator = properties.constBegin();
QString propName;
}
}
-
-bool SyncableObject::setInitValue(const QString &property, const QVariant &value)
+bool SyncableObject::setInitValue(const QString& property, const QVariant& value)
{
QString handlername = QString("initSet") + property;
handlername[7] = handlername[7].toUpper();
QString methodSignature = QString("%1(%2)").arg(handlername).arg(value.typeName());
int methodIdx = metaObject()->indexOfMethod(methodSignature.toLatin1().constData());
- if (methodIdx < 0) {
+ if (methodIdx < 0) {
QByteArray normedMethodName = QMetaObject::normalizedSignature(methodSignature.toLatin1().constData());
methodIdx = metaObject()->indexOfMethod(normedMethodName.constData());
}
return QMetaObject::invokeMethod(this, handlername.toLatin1(), param);
}
-
-void SyncableObject::renameObject(const QString &newName)
+void SyncableObject::renameObject(const QString& newName)
{
const QString oldName = objectName();
if (oldName != newName) {
setObjectName(newName);
- foreach(SignalProxy *proxy, _signalProxies) {
+ foreach (SignalProxy* proxy, _signalProxies) {
proxy->renameObject(this, newName, oldName);
}
}
}
-
-void SyncableObject::update(const QVariantMap &properties)
+void SyncableObject::update(const QVariantMap& properties)
{
fromVariantMap(properties);
SYNC(ARG(properties))
emit updated();
}
-
-void SyncableObject::requestUpdate(const QVariantMap &properties)
+void SyncableObject::requestUpdate(const QVariantMap& properties)
{
if (allowClientUpdates()) {
update(properties);
REQUEST(ARG(properties))
}
-
-void SyncableObject::sync_call__(SignalProxy::ProxyMode modeType, const char *funcname, ...) const
+void SyncableObject::sync_call__(SignalProxy::ProxyMode modeType, const char* funcname, ...) const
{
- //qDebug() << Q_FUNC_INFO << modeType << funcname;
- foreach(SignalProxy *proxy, _signalProxies) {
+ // qDebug() << Q_FUNC_INFO << modeType << funcname;
+ foreach (SignalProxy* proxy, _signalProxies) {
va_list ap;
va_start(ap, funcname);
proxy->sync_call__(this, modeType, funcname, ap);
}
}
-
-void SyncableObject::synchronize(SignalProxy *proxy)
+void SyncableObject::synchronize(SignalProxy* proxy)
{
if (_signalProxies.contains(proxy))
return;
_signalProxies << proxy;
}
-
-void SyncableObject::stopSynchronize(SignalProxy *proxy)
+void SyncableObject::stopSynchronize(SignalProxy* proxy)
{
for (int i = 0; i < _signalProxies.count(); i++) {
if (_signalProxies[i] == proxy) {
* i.e., if you have Foo, ClientFoo and/or CoreFoo, the SYNCABLE_OBJECT macro would
* only be declared in the class declaration of Foo.
*/
-#define SYNCABLE_OBJECT \
- public: \
- const QMetaObject *syncMetaObject() const final override { \
- return &staticMetaObject; \
- } \
- private: \
+#define SYNCABLE_OBJECT \
+public: \
+ const QMetaObject* syncMetaObject() const final override { return &staticMetaObject; } \
+ \
+private:
#define SYNC(...) sync_call__(SignalProxy::Server, __func__, __VA_ARGS__);
#define REQUEST(...) sync_call__(SignalProxy::Client, __func__, __VA_ARGS__);
#define SYNC_OTHER(x, ...) sync_call__(SignalProxy::Server, #x, __VA_ARGS__);
#define REQUEST_OTHER(x, ...) sync_call__(SignalProxy::Client, #x, __VA_ARGS__);
-#define ARG(x) const_cast<void *>(reinterpret_cast<const void *>(&x))
+#define ARG(x) const_cast<void*>(reinterpret_cast<const void*>(&x))
#define NO_ARG 0
class COMMON_EXPORT SyncableObject : public QObject
Q_OBJECT
public:
- SyncableObject(QObject *parent = nullptr);
- SyncableObject(const QString &objectName, QObject *parent = nullptr);
- SyncableObject(const SyncableObject &other, QObject *parent = nullptr);
+ SyncableObject(QObject* parent = nullptr);
+ SyncableObject(const QString& objectName, QObject* parent = nullptr);
+ SyncableObject(const SyncableObject& other, QObject* parent = nullptr);
~SyncableObject() override;
//! Stores the object's state into a QVariantMap.
//! Initialize the object's state from a given QVariantMap.
/** \see toVariantMap() for important information concerning this method.
*/
- virtual void fromVariantMap(const QVariantMap &properties);
+ virtual void fromVariantMap(const QVariantMap& properties);
virtual bool isInitialized() const;
- virtual const QMetaObject *syncMetaObject() const { return metaObject(); }
+ virtual const QMetaObject* syncMetaObject() const { return metaObject(); }
inline void setAllowClientUpdates(bool allow) { _allowClientUpdates = allow; }
inline bool allowClientUpdates() const { return _allowClientUpdates; }
public slots:
virtual void setInitialized();
- void requestUpdate(const QVariantMap &properties);
- virtual void update(const QVariantMap &properties);
+ void requestUpdate(const QVariantMap& properties);
+ virtual void update(const QVariantMap& properties);
protected:
- void sync_call__(SignalProxy::ProxyMode modeType, const char *funcname, ...) const;
+ void sync_call__(SignalProxy::ProxyMode modeType, const char* funcname, ...) const;
- void renameObject(const QString &newName);
- SyncableObject &operator=(const SyncableObject &other);
+ void renameObject(const QString& newName);
+ SyncableObject& operator=(const SyncableObject& other);
signals:
void initDone();
void updated();
private:
- void synchronize(SignalProxy *proxy);
- void stopSynchronize(SignalProxy *proxy);
+ void synchronize(SignalProxy* proxy);
+ void stopSynchronize(SignalProxy* proxy);
- bool setInitValue(const QString &property, const QVariant &value);
+ bool setInitValue(const QString& property, const QVariant& value);
bool _initialized{false};
bool _allowClientUpdates{false};
- QList<SignalProxy *> _signalProxies;
+ QList<SignalProxy*> _signalProxies;
friend class SignalProxy;
};
#include <utility>
-Transfer::Transfer(const QUuid &uuid, QObject *parent)
- : SyncableObject(parent),
- _status(Status::New),
- _direction(Direction::Receive),
- _port(0),
- _fileSize(0),
- _uuid(uuid)
+Transfer::Transfer(const QUuid& uuid, QObject* parent)
+ : SyncableObject(parent)
+ , _status(Status::New)
+ , _direction(Direction::Receive)
+ , _port(0)
+ , _fileSize(0)
+ , _uuid(uuid)
{
init();
}
-Transfer::Transfer(Direction direction, QString nick, QString fileName, const QHostAddress &address, quint16 port, quint64 fileSize, QObject *parent)
- : SyncableObject(parent),
- _status(Status::New),
- _direction(direction),
- _fileName(std::move(fileName)),
- _address(address),
- _port(port),
- _fileSize(fileSize),
- _nick(std::move(nick)),
- _uuid(QUuid::createUuid())
+Transfer::Transfer(
+ Direction direction, QString nick, QString fileName, const QHostAddress& address, quint16 port, quint64 fileSize, QObject* parent)
+ : SyncableObject(parent)
+ , _status(Status::New)
+ , _direction(direction)
+ , _fileName(std::move(fileName))
+ , _address(address)
+ , _port(port)
+ , _fileSize(fileSize)
+ , _nick(std::move(nick))
+ , _uuid(QUuid::createUuid())
{
init();
}
-
void Transfer::init()
{
static auto regTypes = []() -> bool {
setAllowClientUpdates(true);
}
-
QUuid Transfer::uuid() const
{
return _uuid;
}
-
Transfer::Status Transfer::status() const
{
return _status;
}
-
void Transfer::setStatus(Transfer::Status status)
{
if (_status != status) {
}
}
-
QString Transfer::prettyStatus() const
{
- switch(status()) {
- case Status::New:
- return tr("New");
- case Status::Pending:
- return tr("Pending");
- case Status::Connecting:
- return tr("Connecting");
- case Status::Transferring:
- return tr("Transferring");
- case Status::Paused:
- return tr("Paused");
- case Status::Completed:
- return tr("Completed");
- case Status::Failed:
- return tr("Failed");
- case Status::Rejected:
- return tr("Rejected");
+ switch (status()) {
+ case Status::New:
+ return tr("New");
+ case Status::Pending:
+ return tr("Pending");
+ case Status::Connecting:
+ return tr("Connecting");
+ case Status::Transferring:
+ return tr("Transferring");
+ case Status::Paused:
+ return tr("Paused");
+ case Status::Completed:
+ return tr("Completed");
+ case Status::Failed:
+ return tr("Failed");
+ case Status::Rejected:
+ return tr("Rejected");
}
return QString();
}
-
-
Transfer::Direction Transfer::direction() const
{
return _direction;
}
-
void Transfer::setDirection(Transfer::Direction direction)
{
if (_direction != direction) {
}
}
-
QHostAddress Transfer::address() const
{
return _address;
}
-
-void Transfer::setAddress(const QHostAddress &address)
+void Transfer::setAddress(const QHostAddress& address)
{
if (_address != address) {
_address = address;
}
}
-
quint16 Transfer::port() const
{
return _port;
}
-
void Transfer::setPort(quint16 port)
{
if (_port != port) {
}
}
-
QString Transfer::fileName() const
{
return _fileName;
}
-
-void Transfer::setFileName(const QString &fileName)
+void Transfer::setFileName(const QString& fileName)
{
if (_fileName != fileName) {
_fileName = fileName;
}
}
-
quint64 Transfer::fileSize() const
{
return _fileSize;
}
-
void Transfer::setFileSize(quint64 fileSize)
{
if (_fileSize != fileSize) {
}
}
-
QString Transfer::nick() const
{
return _nick;
}
-
-void Transfer::setNick(const QString &nick)
+void Transfer::setNick(const QString& nick)
{
if (_nick != nick) {
_nick = nick;
}
}
-
-void Transfer::setError(const QString &errorString)
+void Transfer::setError(const QString& errorString)
{
qWarning() << Q_FUNC_INFO << errorString;
emit error(errorString);
setStatus(Status::Failed);
}
-
-QDataStream &operator<<(QDataStream &out, Transfer::Status state) {
+QDataStream& operator<<(QDataStream& out, Transfer::Status state)
+{
out << static_cast<qint8>(state);
return out;
}
-QDataStream &operator>>(QDataStream &in, Transfer::Status &state) {
+QDataStream& operator>>(QDataStream& in, Transfer::Status& state)
+{
qint8 s;
in >> s;
state = static_cast<Transfer::Status>(s);
return in;
}
-QDataStream &operator<<(QDataStream &out, Transfer::Direction direction) {
+QDataStream& operator<<(QDataStream& out, Transfer::Direction direction)
+{
out << static_cast<qint8>(direction);
return out;
}
-QDataStream &operator>>(QDataStream &in, Transfer::Direction &direction) {
+QDataStream& operator>>(QDataStream& in, Transfer::Direction& direction)
+{
qint8 d;
in >> d;
direction = static_cast<Transfer::Direction>(d);
Q_PROPERTY(QString nick READ nick WRITE setNick NOTIFY nickChanged)
public:
- enum class Status {
+ enum class Status
+ {
New,
Pending,
Connecting,
};
Q_ENUMS(State)
- enum class Direction {
+ enum class Direction
+ {
Send,
Receive
};
Q_ENUMS(Direction)
- Transfer(const QUuid &uuid, QObject *parent = nullptr); // for creating a syncable object client-side
- Transfer(Direction direction, QString nick, QString fileName, const QHostAddress &address, quint16 port, quint64 size = 0, QObject *parent = nullptr);
+ Transfer(const QUuid& uuid, QObject* parent = nullptr); // for creating a syncable object client-side
+ Transfer(Direction direction,
+ QString nick,
+ QString fileName,
+ const QHostAddress& address,
+ quint16 port,
+ quint64 size = 0,
+ QObject* parent = nullptr);
QUuid uuid() const;
Status status() const;
public slots:
// called on the client side
- virtual void accept(const QString &savePath) const { Q_UNUSED(savePath); }
+ virtual void accept(const QString& savePath) const { Q_UNUSED(savePath); }
virtual void reject() const {}
// called on the core side through sync calls
signals:
void statusChanged(Transfer::Status state);
void directionChanged(Transfer::Direction direction);
- void addressChanged(const QHostAddress &address);
+ void addressChanged(const QHostAddress& address);
void portChanged(quint16 port);
- void fileNameChanged(const QString &fileName);
+ void fileNameChanged(const QString& fileName);
void fileSizeChanged(quint64 fileSize);
void transferredChanged(quint64 transferred);
- void nickChanged(const QString &nick);
+ void nickChanged(const QString& nick);
- void error(const QString &errorString);
+ void error(const QString& errorString);
void accepted(PeerPtr peer = nullptr) const;
void rejected(PeerPtr peer = nullptr) const;
protected slots:
void setStatus(Transfer::Status status);
- void setError(const QString &errorString);
+ void setError(const QString& errorString);
// called on the client side through sync calls
- virtual void dataReceived(PeerPtr, const QByteArray &data) { Q_UNUSED(data); }
+ virtual void dataReceived(PeerPtr, const QByteArray& data) { Q_UNUSED(data); }
virtual void cleanUp() = 0;
void init();
void setDirection(Direction direction);
- void setAddress(const QHostAddress &address);
+ void setAddress(const QHostAddress& address);
void setPort(quint16 port);
- void setFileName(const QString &fileName);
+ void setFileName(const QString& fileName);
void setFileSize(quint64 fileSize);
- void setNick(const QString &nick);
-
+ void setNick(const QString& nick);
Status _status;
Direction _direction;
Q_DECLARE_METATYPE(Transfer::Status)
Q_DECLARE_METATYPE(Transfer::Direction)
-QDataStream &operator<<(QDataStream &out, Transfer::Status state);
-QDataStream &operator>>(QDataStream &in, Transfer::Status &state);
-QDataStream &operator<<(QDataStream &out, Transfer::Direction direction);
-QDataStream &operator>>(QDataStream &in, Transfer::Direction &direction);
+QDataStream& operator<<(QDataStream& out, Transfer::Status state);
+QDataStream& operator>>(QDataStream& in, Transfer::Status& state);
+QDataStream& operator<<(QDataStream& out, Transfer::Direction direction);
+QDataStream& operator>>(QDataStream& in, Transfer::Direction& direction);
#include "transfer.h"
-TransferManager::TransferManager(QObject *parent)
+TransferManager::TransferManager(QObject* parent)
: SyncableObject(parent)
{
static auto regTypes = []() -> bool {
renameObject("TransferManager");
}
-
-Transfer *TransferManager::transfer(const QUuid &uuid) const
+Transfer* TransferManager::transfer(const QUuid& uuid) const
{
return _transfers.value(uuid, nullptr);
}
-
TransferManager::TransferIdList TransferManager::transferIds() const
{
return _transfers.keys();
}
-
-void TransferManager::addTransfer(Transfer *transfer)
+void TransferManager::addTransfer(Transfer* transfer)
{
QUuid uuid = transfer->uuid();
if (_transfers.contains(uuid)) {
emit transferAdded(uuid);
}
-
-void TransferManager::removeTransfer(const QUuid &uuid)
+void TransferManager::removeTransfer(const QUuid& uuid)
{
if (!_transfers.contains(uuid)) {
qWarning() << "Can not find transfer" << uuid << "to remove!";
transfer->deleteLater();
}
-
-QDataStream &operator<<(QDataStream &out, const TransferManager::TransferIdList &transferIds)
+QDataStream& operator<<(QDataStream& out, const TransferManager::TransferIdList& transferIds)
{
out << static_cast<quint32>(transferIds.size());
- for (auto &&id : transferIds) {
+ for (auto&& id : transferIds) {
out << id;
}
return out;
}
-
-QDataStream &operator>>(QDataStream &in, TransferManager::TransferIdList &transferIds)
+QDataStream& operator>>(QDataStream& in, TransferManager::TransferIdList& transferIds)
{
quint32 count;
in >> count;
public:
using TransferIdList = QList<QUuid>;
- TransferManager(QObject *parent = nullptr);
+ TransferManager(QObject* parent = nullptr);
- Transfer *transfer(const QUuid &uuid) const;
+ Transfer* transfer(const QUuid& uuid) const;
TransferIdList transferIds() const;
signals:
- void transferAdded(const QUuid &uuid);
- void transferRemoved(const QUuid &uuid);
+ void transferAdded(const QUuid& uuid);
+ void transferRemoved(const QUuid& uuid);
protected:
- void addTransfer(Transfer *transfer);
- void removeTransfer(const QUuid &uuid);
+ void addTransfer(Transfer* transfer);
+ void removeTransfer(const QUuid& uuid);
protected slots:
- virtual void setTransferIds(const TransferIdList &transferIds) { Q_UNUSED(transferIds) };
- virtual void onCoreTransferAdded(const QUuid &transferId) { Q_UNUSED(transferId) };
+ virtual void setTransferIds(const TransferIdList& transferIds){Q_UNUSED(transferIds)};
+ virtual void onCoreTransferAdded(const QUuid& transferId){Q_UNUSED(transferId)};
private:
- QHash<QUuid, Transfer *> _transfers;
+ QHash<QUuid, Transfer*> _transfers;
};
-QDataStream &operator<<(QDataStream &out, const TransferManager::TransferIdList &transferIds);
-QDataStream &operator>>(QDataStream &in, TransferManager::TransferIdList &state);
+QDataStream& operator<<(QDataStream& out, const TransferManager::TransferIdList& transferIds);
+QDataStream& operator>>(QDataStream& in, TransferManager::TransferIdList& state);
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include "peer.h"
#include "types.h"
-QDataStream &operator<<(QDataStream &out, const SignedId64 &signedId) {
+#include "peer.h"
+
+QDataStream& operator<<(QDataStream& out, const SignedId64& signedId)
+{
Q_ASSERT(SignalProxy::current());
Q_ASSERT(SignalProxy::current()->targetPeer());
if (SignalProxy::current()->targetPeer()->hasFeature(Quassel::Feature::LongMessageId)) {
out << signedId.toQint64();
- } else {
- out << (qint32) signedId.toQint64();
+ }
+ else {
+ out << (qint32)signedId.toQint64();
}
return out;
}
-QDataStream &operator>>(QDataStream &in, SignedId64 &signedId) {
+QDataStream& operator>>(QDataStream& in, SignedId64& signedId)
+{
Q_ASSERT(SignalProxy::current());
Q_ASSERT(SignalProxy::current()->sourcePeer());
if (SignalProxy::current()->sourcePeer()->hasFeature(Quassel::Feature::LongMessageId)) {
in >> signedId.id;
- } else {
+ }
+ else {
qint32 id;
in >> id;
signedId.id = id;
#include <type_traits>
+#include <QDataStream>
#include <QDebug>
+#include <QHostAddress>
#include <QString>
-#include <QVariant>
-#include <QDataStream>
#include <QTextStream>
-#include <QHostAddress>
-#include <QDataStream>
+#include <QVariant>
class SignedId
{
inline qint32 toInt() const { return id; }
inline bool isValid() const { return id > 0; }
- inline bool operator==(const SignedId &other) const { return id == other.id; }
- inline bool operator!=(const SignedId &other) const { return id != other.id; }
- inline bool operator<(const SignedId &other) const { return id < other.id; }
- inline bool operator<=(const SignedId &other) const { return id <= other.id; }
- inline bool operator>(const SignedId &other) const { return id > other.id; }
- inline bool operator>=(const SignedId &other) const { return id >= other.id; }
+ inline bool operator==(const SignedId& other) const { return id == other.id; }
+ inline bool operator!=(const SignedId& other) const { return id != other.id; }
+ inline bool operator<(const SignedId& other) const { return id < other.id; }
+ inline bool operator<=(const SignedId& other) const { return id <= other.id; }
+ inline bool operator>(const SignedId& other) const { return id > other.id; }
+ inline bool operator>=(const SignedId& other) const { return id >= other.id; }
inline bool operator==(int i) const { return id == i; }
inline bool operator!=(int i) const { return id != i; }
inline bool operator<(int i) const { return id < i; }
inline bool operator>(int i) const { return id > i; }
inline bool operator<=(int i) const { return id <= i; }
- inline SignedId operator++(int) { id++; return *this; }
- //inline operator int() const { return toInt(); } // no automatic conversion!
+ inline SignedId operator++(int)
+ {
+ id++;
+ return *this;
+ }
+ // inline operator int() const { return toInt(); } // no automatic conversion!
- friend QDataStream &operator>>(QDataStream &in, SignedId &signedId);
+ friend QDataStream& operator>>(QDataStream& in, SignedId& signedId);
};
-inline QDataStream &operator<<(QDataStream &out, const SignedId &signedId) { out << signedId.toInt(); return out; }
-inline QDataStream &operator>>(QDataStream &in, SignedId &signedId) { in >> signedId.id; return in; }
-inline QTextStream &operator<<(QTextStream &out, const SignedId &signedId) { out << QString::number(signedId.toInt()); return out; }
-inline QDebug operator<<(QDebug dbg, const SignedId &signedId) { dbg.space() << signedId.toInt(); return dbg; }
-inline uint qHash(const SignedId &id) { return qHash(id.toInt()); }
+inline QDataStream& operator<<(QDataStream& out, const SignedId& signedId)
+{
+ out << signedId.toInt();
+ return out;
+}
+inline QDataStream& operator>>(QDataStream& in, SignedId& signedId)
+{
+ in >> signedId.id;
+ return in;
+}
+inline QTextStream& operator<<(QTextStream& out, const SignedId& signedId)
+{
+ out << QString::number(signedId.toInt());
+ return out;
+}
+inline QDebug operator<<(QDebug dbg, const SignedId& signedId)
+{
+ dbg.space() << signedId.toInt();
+ return dbg;
+}
+inline uint qHash(const SignedId& id)
+{
+ return qHash(id.toInt());
+}
class SignedId64
{
inline qint64 toQint64() const { return id; }
inline bool isValid() const { return id > 0; }
- inline bool operator==(const SignedId64 &other) const { return id == other.id; }
- inline bool operator!=(const SignedId64 &other) const { return id != other.id; }
- inline bool operator<(const SignedId64 &other) const { return id < other.id; }
- inline bool operator<=(const SignedId64 &other) const { return id <= other.id; }
- inline bool operator>(const SignedId64 &other) const { return id > other.id; }
- inline bool operator>=(const SignedId64 &other) const { return id >= other.id; }
+ inline bool operator==(const SignedId64& other) const { return id == other.id; }
+ inline bool operator!=(const SignedId64& other) const { return id != other.id; }
+ inline bool operator<(const SignedId64& other) const { return id < other.id; }
+ inline bool operator<=(const SignedId64& other) const { return id <= other.id; }
+ inline bool operator>(const SignedId64& other) const { return id > other.id; }
+ inline bool operator>=(const SignedId64& other) const { return id >= other.id; }
inline bool operator==(qint64 i) const { return id == i; }
inline bool operator!=(qint64 i) const { return id != i; }
inline bool operator<(qint64 i) const { return id < i; }
inline bool operator>(qint64 i) const { return id > i; }
inline bool operator<=(qint64 i) const { return id <= i; }
- inline SignedId64 operator++(int) { id++; return *this; }
- //inline operator int() const { return toQint64(); } // no automatic conversion!
+ inline SignedId64 operator++(int)
+ {
+ id++;
+ return *this;
+ }
+ // inline operator int() const { return toQint64(); } // no automatic conversion!
- friend QDataStream &operator>>(QDataStream &in, SignedId64 &signedId);
+ friend QDataStream& operator>>(QDataStream& in, SignedId64& signedId);
};
-QDataStream &operator<<(QDataStream &out, const SignedId64 &signedId);
-QDataStream &operator>>(QDataStream &in, SignedId64 &signedId);
-inline QTextStream &operator<<(QTextStream &out, const SignedId64 &signedId) { out << QString::number(signedId.toQint64()); return out; }
-inline QDebug operator<<(QDebug dbg, const SignedId64 &signedId) { dbg.space() << signedId.toQint64(); return dbg; }
-inline uint qHash(const SignedId64 &id) { return qHash(id.toQint64()); }
+QDataStream& operator<<(QDataStream& out, const SignedId64& signedId);
+QDataStream& operator>>(QDataStream& in, SignedId64& signedId);
+inline QTextStream& operator<<(QTextStream& out, const SignedId64& signedId)
+{
+ out << QString::number(signedId.toQint64());
+ return out;
+}
+inline QDebug operator<<(QDebug dbg, const SignedId64& signedId)
+{
+ dbg.space() << signedId.toQint64();
+ return dbg;
+}
+inline uint qHash(const SignedId64& id)
+{
+ return qHash(id.toQint64());
+}
-struct UserId : public SignedId {
- inline UserId(int _id = 0) : SignedId(_id) {}
- //inline operator QVariant() const { return QVariant::fromValue<UserId>(*this); } // no automatic conversion!
+struct UserId : public SignedId
+{
+ inline UserId(int _id = 0)
+ : SignedId(_id)
+ {}
+ // inline operator QVariant() const { return QVariant::fromValue<UserId>(*this); } // no automatic conversion!
};
-struct MsgId : public SignedId64 {
- inline MsgId(qint64 _id = 0) : SignedId64(_id) {}
- //inline operator QVariant() const { return QVariant::fromValue<MsgId>(*this); }
+struct MsgId : public SignedId64
+{
+ inline MsgId(qint64 _id = 0)
+ : SignedId64(_id)
+ {}
+ // inline operator QVariant() const { return QVariant::fromValue<MsgId>(*this); }
};
-struct BufferId : public SignedId {
- inline BufferId(int _id = 0) : SignedId(_id) {}
- //inline operator QVariant() const { return QVariant::fromValue<BufferId>(*this); }
+struct BufferId : public SignedId
+{
+ inline BufferId(int _id = 0)
+ : SignedId(_id)
+ {}
+ // inline operator QVariant() const { return QVariant::fromValue<BufferId>(*this); }
};
-struct NetworkId : public SignedId {
- inline NetworkId(int _id = 0) : SignedId(_id) {}
- //inline operator QVariant() const { return QVariant::fromValue<NetworkId>(*this); }
+struct NetworkId : public SignedId
+{
+ inline NetworkId(int _id = 0)
+ : SignedId(_id)
+ {}
+ // inline operator QVariant() const { return QVariant::fromValue<NetworkId>(*this); }
};
-struct IdentityId : public SignedId {
- inline IdentityId(int _id = 0) : SignedId(_id) {}
- //inline operator QVariant() const { return QVariant::fromValue<IdentityId>(*this); }
+struct IdentityId : public SignedId
+{
+ inline IdentityId(int _id = 0)
+ : SignedId(_id)
+ {}
+ // inline operator QVariant() const { return QVariant::fromValue<IdentityId>(*this); }
};
-struct AccountId : public SignedId {
- inline AccountId(int _id = 0) : SignedId(_id) {}
+struct AccountId : public SignedId
+{
+ inline AccountId(int _id = 0)
+ : SignedId(_id)
+ {}
};
Q_DECLARE_METATYPE(UserId)
* @param[in] value Value to serialize
* @returns A reference to the stream
*/
-template<typename T,
- typename = typename std::enable_if<std::is_enum<T>::value>::type>
-QDataStream &operator<<(QDataStream &out, T value) {
+template<typename T, typename = typename std::enable_if<std::is_enum<T>::value>::type>
+QDataStream& operator<<(QDataStream& out, T value)
+{
out << static_cast<typename std::underlying_type<T>::type>(value);
return out;
}
* @param[out] value Value to deserialize into
* @returns A reference to the stream
*/
-template<typename T,
- typename = typename std::enable_if<std::is_enum<T>::value>::type>
-QDataStream &operator>>(QDataStream &in, T &value) {
+template<typename T, typename = typename std::enable_if<std::is_enum<T>::value>::type>
+QDataStream& operator>>(QDataStream& in, T& value)
+{
typename std::underlying_type<T>::type v;
in >> v;
value = static_cast<T>(v);
QString errorString;
ExitException(int code = EXIT_FAILURE, QString error = {})
- : exitCode(code), errorString(std::move(error)) {}
+ : exitCode(code)
+ , errorString(std::move(error))
+ {}
};
#include "quassel.h"
// MIBenum values from http://www.iana.org/assignments/character-sets/character-sets.xml#table-character-sets-1
-static QList<int> utf8DetectionBlacklist = QList<int>()
- << 39 /* ISO-2022-JP */;
+static QList<int> utf8DetectionBlacklist = QList<int>() << 39 /* ISO-2022-JP */;
-QString nickFromMask(const QString &mask)
+QString nickFromMask(const QString& mask)
{
return mask.left(mask.indexOf('!'));
}
-
-QString userFromMask(const QString &mask)
+QString userFromMask(const QString& mask)
{
const int offset = mask.indexOf('!') + 1;
if (offset <= 0)
return mask.mid(offset, length >= 0 ? length : -1);
}
-
-QString hostFromMask(const QString &mask)
+QString hostFromMask(const QString& mask)
{
const int excl = mask.indexOf('!');
if (excl < 0)
return offset > 0 && offset < mask.size() ? mask.mid(offset) : QString{};
}
-
-bool isChannelName(const QString &str)
+bool isChannelName(const QString& str)
{
if (str.isEmpty())
return false;
return std::any_of(prefixes.cbegin(), prefixes.cend(), [&str](quint8 c) { return c == str[0]; });
}
-
QString stripFormatCodes(QString message)
{
static QRegExp regEx{"\x03(\\d\\d?(,\\d\\d?)?)?|\x04([\\da-fA-F]{6}(,[\\da-fA-F]{6})?)?|[\x02\x0f\x11\x12\x16\x1d\x1e\x1f]"};
return message.remove(regEx);
}
-
-QString stripAcceleratorMarkers(const QString &label_)
+QString stripAcceleratorMarkers(const QString& label_)
{
QString label = label_;
int p = 0;
- forever {
+ forever
+ {
p = label.indexOf('&', p);
if (p < 0 || p + 1 >= label.length())
break;
return label;
}
-
-QString decodeString(const QByteArray &input, QTextCodec *codec)
+QString decodeString(const QByteArray& input, QTextCodec* codec)
{
if (codec && utf8DetectionBlacklist.contains(codec->mibEnum()))
return codec->toUnicode(input);
for (uchar c : input) {
if (cnt) {
// We check a part of a multibyte char. These need to be of the form 10yyyyyy.
- if ((c & 0xc0) != 0x80) { isUtf8 = false; break; }
+ if ((c & 0xc0) != 0x80) {
+ isUtf8 = false;
+ break;
+ }
cnt--;
continue;
}
- if ((c & 0x80) == 0x00) continue; // 7 bit is always ok
- if ((c & 0xf8) == 0xf0) { cnt = 3; continue; } // 4-byte char 11110xxx 10yyyyyy 10zzzzzz 10vvvvvv
- if ((c & 0xf0) == 0xe0) { cnt = 2; continue; } // 3-byte char 1110xxxx 10yyyyyy 10zzzzzz
- if ((c & 0xe0) == 0xc0) { cnt = 1; continue; } // 2-byte char 110xxxxx 10yyyyyy
- isUtf8 = false; break; // 8 bit char, but not utf8!
+ if ((c & 0x80) == 0x00)
+ continue; // 7 bit is always ok
+ if ((c & 0xf8) == 0xf0) {
+ cnt = 3;
+ continue;
+ } // 4-byte char 11110xxx 10yyyyyy 10zzzzzz 10vvvvvv
+ if ((c & 0xf0) == 0xe0) {
+ cnt = 2;
+ continue;
+ } // 3-byte char 1110xxxx 10yyyyyy 10zzzzzz
+ if ((c & 0xe0) == 0xc0) {
+ cnt = 1;
+ continue;
+ } // 2-byte char 110xxxxx 10yyyyyy
+ isUtf8 = false;
+ break; // 8 bit char, but not utf8!
}
if (isUtf8 && cnt == 0) {
QString s = QString::fromUtf8(input);
- //qDebug() << "Detected utf8:" << s;
+ // qDebug() << "Detected utf8:" << s;
return s;
}
- //QTextCodec *codec = QTextCodec::codecForName(encoding.toLatin1());
- if (!codec) return QString::fromLatin1(input);
+ // QTextCodec *codec = QTextCodec::codecForName(encoding.toLatin1());
+ if (!codec)
+ return QString::fromLatin1(input);
return codec->toUnicode(input);
}
-
-uint editingDistance(const QString &s1, const QString &s2)
+uint editingDistance(const QString& s1, const QString& s2)
{
- uint n = s1.size()+1;
- uint m = s2.size()+1;
- QVector<QVector<uint> > matrix(n, QVector<uint>(m, 0));
+ uint n = s1.size() + 1;
+ uint m = s2.size() + 1;
+ QVector<QVector<uint>> matrix(n, QVector<uint>(m, 0));
for (uint i = 0; i < n; i++)
matrix[i][0] = i;
uint min;
for (uint i = 1; i < n; i++) {
for (uint j = 1; j < m; j++) {
- uint deleteChar = matrix[i-1][j] + 1;
- uint insertChar = matrix[i][j-1] + 1;
+ uint deleteChar = matrix[i - 1][j] + 1;
+ uint insertChar = matrix[i][j - 1] + 1;
if (deleteChar < insertChar)
min = deleteChar;
else
min = insertChar;
- if (s1[i-1] == s2[j-1]) {
- uint inheritChar = matrix[i-1][j-1];
+ if (s1[i - 1] == s2[j - 1]) {
+ uint inheritChar = matrix[i - 1][j - 1];
if (inheritChar < min)
min = inheritChar;
}
matrix[i][j] = min;
}
}
- return matrix[n-1][m-1];
+ return matrix[n - 1][m - 1];
}
-
QString secondsToString(int timeInSeconds)
{
- static QVector<std::pair<int, QString>> timeUnit {
- std::make_pair(365*24*60*60, QCoreApplication::translate("Quassel::secondsToString()", "year")),
- std::make_pair(24*60*60, QCoreApplication::translate("Quassel::secondsToString()", "day")),
- std::make_pair(60*60, QCoreApplication::translate("Quassel::secondsToString()", "h")),
- std::make_pair(60, QCoreApplication::translate("Quassel::secondsToString()", "min")),
- std::make_pair(1, QCoreApplication::translate("Quassel::secondsToString()", "sec"))
- };
+ static QVector<std::pair<int, QString>> timeUnit{std::make_pair(365 * 24 * 60 * 60,
+ QCoreApplication::translate("Quassel::secondsToString()", "year")),
+ std::make_pair(24 * 60 * 60,
+ QCoreApplication::translate("Quassel::secondsToString()", "day")),
+ std::make_pair(60 * 60, QCoreApplication::translate("Quassel::secondsToString()", "h")),
+ std::make_pair(60, QCoreApplication::translate("Quassel::secondsToString()", "min")),
+ std::make_pair(1, QCoreApplication::translate("Quassel::secondsToString()", "sec"))};
if (timeInSeconds != 0) {
QStringList returnString;
- for (const auto &tu : timeUnit) {
+ for (const auto& tu : timeUnit) {
int n = timeInSeconds / tu.first;
if (n > 0) {
returnString += QString("%1 %2").arg(QString::number(n), tu.second);
return QString("%1 %2").arg(QString::number(timeInSeconds), timeUnit.last().second);
}
-
-QByteArray prettyDigest(const QByteArray &digest)
+QByteArray prettyDigest(const QByteArray& digest)
{
QByteArray hexDigest = digest.toHex().toUpper();
QByteArray prettyDigest;
return prettyDigest;
}
-
-QString formatCurrentDateTimeInString(const QString &formatStr)
+QString formatCurrentDateTimeInString(const QString& formatStr)
{
// Work on a copy of the string to avoid modifying the input string
QString formattedStr = QString(formatStr);
if (matchedFormat.length() > 0) {
// Format the string according to the current date and time. Invalid time format
// strings are ignored.
- formattedStr.replace(index, matchLength,
- QDateTime::currentDateTime().toString(matchedFormat));
+ formattedStr.replace(index, matchLength, QDateTime::currentDateTime().toString(matchedFormat));
// Subtract the length of the removed % signs
// E.g. "%%h:mm ap%%" turns into "h:mm ap", removing four % signs, thus -4. This is
// used below to determine how far to advance when looking for the next formatting code.
matchLength -= 4;
- } else if (matchLength == 4) {
+ }
+ else if (matchLength == 4) {
// Remove two of the four percent signs, so '%%%%' escapes to '%%'
formattedStr.remove(index, 2);
// Subtract the length of the removed % signs, this time removing two % signs, thus -2.
matchLength -= 2;
- } else {
+ }
+ else {
// If neither of these match, something went wrong. Don't modify it to be safe.
qDebug() << "Unexpected time format when parsing string, no matchedFormat, matchLength "
- "should be 4, actually is" << matchLength;
+ "should be 4, actually is"
+ << matchLength;
}
// Find the next group of %%text here%% starting from where the last group ended
return formattedStr;
}
-
-QString tryFormatUnixEpoch(const QString &possibleEpochDate, Qt::DateFormat dateFormat, bool useUTC)
+QString tryFormatUnixEpoch(const QString& possibleEpochDate, Qt::DateFormat dateFormat, bool useUTC)
{
// Does the string resemble a Unix epoch? Parse as 64-bit time
qint64 secsSinceEpoch = possibleEpochDate.toLongLong();
// See https://en.wikipedia.org/wiki/ISO_8601#cite_note-32
// And https://www.ietf.org/rfc/rfc3339.txt
return date.toUTC().toString(dateFormat).replace(10, 1, " ");
- } else {
+ }
+ else {
return date.toUTC().toString(dateFormat);
}
- } else if (dateFormat == Qt::DateFormat::ISODate) {
+ }
+ else if (dateFormat == Qt::DateFormat::ISODate) {
// Add in ISO local timezone information via special handling below
// formatDateTimeToOffsetISO() handles converting "T" to " "
return formatDateTimeToOffsetISO(date);
- } else {
+ }
+ else {
// Return local time
return date.toString(dateFormat);
}
}
-
-QString formatDateTimeToOffsetISO(const QDateTime &dateTime)
+QString formatDateTimeToOffsetISO(const QDateTime& dateTime)
{
if (!dateTime.isValid()) {
// Don't try to do anything with invalid date/time
#include <QString>
#include <QVariant>
-COMMON_EXPORT QString nickFromMask(const QString &mask);
-COMMON_EXPORT QString userFromMask(const QString &mask);
-COMMON_EXPORT QString hostFromMask(const QString &mask);
-COMMON_EXPORT bool isChannelName(const QString &str);
+COMMON_EXPORT QString nickFromMask(const QString& mask);
+COMMON_EXPORT QString userFromMask(const QString& mask);
+COMMON_EXPORT QString hostFromMask(const QString& mask);
+COMMON_EXPORT bool isChannelName(const QString& str);
//! Strip mIRC format codes
COMMON_EXPORT QString stripFormatCodes(QString);
//! Remove accelerator markers (&) from the string
-COMMON_EXPORT QString stripAcceleratorMarkers(const QString &);
+COMMON_EXPORT QString stripAcceleratorMarkers(const QString&);
COMMON_EXPORT QString secondsToString(int timeInSeconds);
* \param codec The text codec we use if the input is not utf8
* \return The decoded string.
*/
-COMMON_EXPORT QString decodeString(const QByteArray &input, QTextCodec *codec = nullptr);
+COMMON_EXPORT QString decodeString(const QByteArray& input, QTextCodec* codec = nullptr);
-COMMON_EXPORT uint editingDistance(const QString &s1, const QString &s2);
+COMMON_EXPORT uint editingDistance(const QString& s1, const QString& s2);
template<typename T>
-QVariantList toVariantList(const QList<T> &list)
+QVariantList toVariantList(const QList<T>& list)
{
QVariantList variants;
for (int i = 0; i < list.count(); i++) {
return variants;
}
-
template<typename T>
-QList<T> fromVariantList(const QVariantList &variants)
+QList<T> fromVariantList(const QVariantList& variants)
{
QList<T> list;
for (int i = 0; i < variants.count(); i++) {
return list;
}
-
-COMMON_EXPORT QByteArray prettyDigest(const QByteArray &digest);
+COMMON_EXPORT QByteArray prettyDigest(const QByteArray& digest);
/**
* Format a string with %%<text>%% to current date/timestamp via QDateTime.
* @param[in] formatStr String with format codes
* @return String with current date/time substituted in via formatting codes
*/
-COMMON_EXPORT QString formatCurrentDateTimeInString(const QString &formatStr);
+COMMON_EXPORT QString formatCurrentDateTimeInString(const QString& formatStr);
/**
* Try to localize a given date/time in seconds from Unix epoch, pass through string if invalid
* @param useUTC If true, use UTC timezone, otherwise use local time
* @return Localized date/time if parse succeeded, otherwise the source string
*/
-COMMON_EXPORT QString tryFormatUnixEpoch(const QString &possibleEpochDate,
+COMMON_EXPORT QString tryFormatUnixEpoch(const QString& possibleEpochDate,
Qt::DateFormat dateFormat = Qt::DateFormat::TextDate,
bool useUTC = false);
-
/**
* Format the given date/time in ISO 8601 format with timezone offset
*
* @param dateTime Date/time of interest
* @return Date/time in ISO 8601 format with timezone offset
*/
-COMMON_EXPORT QString formatDateTimeToOffsetISO(const QDateTime &dateTime);
+COMMON_EXPORT QString formatDateTimeToOffsetISO(const QDateTime& dateTime);
namespace detail {
-template<typename ...Args>
+template<typename... Args>
struct SelectOverloadHelper
{
- template <typename R, typename C>
- constexpr auto operator()(R(C::*func)(Args...)) const noexcept -> decltype(func) { return func; }
+ template<typename R, typename C>
+ constexpr auto operator()(R (C::*func)(Args...)) const noexcept -> decltype(func)
+ {
+ return func;
+ }
};
-} // detail
+} // namespace detail
/**
* Helper for resolving ambiguous overloads when using the member function-based connect syntax.
*
* @tparam Args Argument types of the desired signature
*/
-template<typename ...Args>
+template<typename... Args>
constexpr Q_DECL_UNUSED detail::SelectOverloadHelper<Args...> selectOverload = {};
// condition variable once shutdown is complete...
static BOOL WINAPI consoleCtrlHandler(DWORD ctrlType)
{
- switch (ctrlType) {
- case CTRL_C_EVENT: // Ctrl+C
- case CTRL_CLOSE_EVENT: // Closing the console window
- WindowsSignalWatcher::signalHandler(SIGTERM);
- return TRUE;
- default:
- return FALSE;
- }
+ switch (ctrlType) {
+ case CTRL_C_EVENT: // Ctrl+C
+ case CTRL_CLOSE_EVENT: // Closing the console window
+ WindowsSignalWatcher::signalHandler(SIGTERM);
+ return TRUE;
+ default:
+ return FALSE;
+ }
}
-WindowsSignalWatcher::WindowsSignalWatcher(QObject *parent)
+WindowsSignalWatcher::WindowsSignalWatcher(QObject* parent)
: AbstractSignalWatcher{parent}
, Singleton<WindowsSignalWatcher>{this}
{
Q_OBJECT
public:
- WindowsSignalWatcher(QObject *parent = nullptr);
+ WindowsSignalWatcher(QObject* parent = nullptr);
static void signalHandler(int signal);
};
#include "quassel.h"
int AbstractSqlStorage::_nextConnectionId = 0;
-AbstractSqlStorage::AbstractSqlStorage(QObject *parent)
+AbstractSqlStorage::AbstractSqlStorage(QObject* parent)
: Storage(parent)
-{
-}
-
+{}
AbstractSqlStorage::~AbstractSqlStorage()
{
// disconnect the connections, so their deletion is no longer interessting for us
- QHash<QThread *, Connection *>::iterator conIter;
+ QHash<QThread*, Connection*>::iterator conIter;
for (conIter = _connectionPool.begin(); conIter != _connectionPool.end(); ++conIter) {
QSqlDatabase::removeDatabase(conIter.value()->name());
disconnect(conIter.value(), nullptr, this, nullptr);
}
}
-
QSqlDatabase AbstractSqlStorage::logDb()
{
if (!_connectionPool.contains(QThread::currentThread()))
addConnectionToPool();
- QSqlDatabase db = QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name(),false);
+ QSqlDatabase db = QSqlDatabase::database(_connectionPool[QThread::currentThread()]->name(), false);
if (!db.isOpen()) {
- qWarning() << "Database connection" << displayName() << "for thread" << QThread::currentThread() << "was lost, attempting to reconnect...";
+ qWarning() << "Database connection" << displayName() << "for thread" << QThread::currentThread()
+ << "was lost, attempting to reconnect...";
dbConnect(db);
}
return db;
}
-
void AbstractSqlStorage::addConnectionToPool()
{
QMutexLocker locker(&_connectionPoolMutex);
if (_connectionPool.contains(QThread::currentThread()))
return;
- QThread *currentThread = QThread::currentThread();
+ QThread* currentThread = QThread::currentThread();
int connectionId = _nextConnectionId++;
- Connection *connection = new Connection(QLatin1String(QString("quassel_%1_con_%2").arg(driverName()).arg(connectionId).toLatin1()));
+ Connection* connection = new Connection(QLatin1String(QString("quassel_%1_con_%2").arg(driverName()).arg(connectionId).toLatin1()));
connection->moveToThread(currentThread);
connect(this, &QObject::destroyed, connection, &QObject::deleteLater);
connect(currentThread, &QObject::destroyed, connection, &QObject::deleteLater);
dbConnect(db);
}
-
-void AbstractSqlStorage::dbConnect(QSqlDatabase &db)
+void AbstractSqlStorage::dbConnect(QSqlDatabase& db)
{
if (!db.open()) {
quWarning() << "Unable to open database" << displayName() << "for thread" << QThread::currentThread();
}
}
-
-Storage::State AbstractSqlStorage::init(const QVariantMap &settings,
- const QProcessEnvironment &environment,
- bool loadFromEnvironment)
+Storage::State AbstractSqlStorage::init(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment)
{
setConnectionProperties(settings, environment, loadFromEnvironment);
if (installedSchemaVersion() < schemaVersion()) {
quInfo() << qPrintable(tr("Installed database schema (version %1) is not up to date. Upgrading to "
- "version %2... This may take a while for major upgrades."
- ).arg(installedSchemaVersion()).arg(schemaVersion()));
+ "version %2... This may take a while for major upgrades.")
+ .arg(installedSchemaVersion())
+ .arg(schemaVersion()));
emit dbUpgradeInProgress(true);
auto upgradeResult = upgradeDb();
emit dbUpgradeInProgress(false);
return IsReady;
}
-
-QString AbstractSqlStorage::queryString(const QString &queryName, int version)
+QString AbstractSqlStorage::queryString(const QString& queryName, int version)
{
QFileInfo queryInfo;
// Use the current SQL schema, not a versioned request
queryInfo = QFileInfo(QString(":/SQL/%1/%2.sql").arg(displayName()).arg(queryName));
// If version is needed later, get it via version = schemaVersion();
- } else {
+ }
+ else {
// Use the specified schema version, not the general folder
- queryInfo = QFileInfo(QString(":/SQL/%1/version/%2/%3.sql")
- .arg(displayName()).arg(version).arg(queryName));
+ queryInfo = QFileInfo(QString(":/SQL/%1/version/%2/%3.sql").arg(displayName()).arg(version).arg(queryName));
}
if (!queryInfo.exists() || !queryInfo.isFile() || !queryInfo.isReadable()) {
return query.trimmed();
}
-
QStringList AbstractSqlStorage::setupQueries()
{
QStringList queries;
// The current schema is stored in the root folder, including setup scripts.
QDir dir = QDir(QString(":/SQL/%1/").arg(displayName()));
- foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
+ foreach (QFileInfo fileInfo, dir.entryInfoList(QStringList() << "setup*", QDir::NoFilter, QDir::Name)) {
queries << queryString(fileInfo.baseName());
}
return queries;
}
-
-bool AbstractSqlStorage::setup(const QVariantMap &settings, const QProcessEnvironment &environment,
- bool loadFromEnvironment)
+bool AbstractSqlStorage::setup(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment)
{
setConnectionProperties(settings, environment, loadFromEnvironment);
QSqlDatabase db = logDb();
}
db.transaction();
- foreach(QString queryString, setupQueries()) {
+ foreach (QString queryString, setupQueries()) {
QSqlQuery query = db.exec(queryString);
if (!watchQuery(query)) {
qCritical() << "Unable to setup Logging Backend!";
return success;
}
-
QStringList AbstractSqlStorage::upgradeQueries(int version)
{
QStringList queries;
// Upgrade queries are stored in the 'version/##' subfolders.
QDir dir = QDir(QString(":/SQL/%1/version/%2/").arg(displayName()).arg(version));
- foreach(QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
+ foreach (QFileInfo fileInfo, dir.entryInfoList(QStringList() << "upgrade*", QDir::NoFilter, QDir::Name)) {
queries << queryString(fileInfo.baseName(), version);
}
return queries;
}
-
bool AbstractSqlStorage::upgradeDb()
{
if (schemaVersion() <= installedSchemaVersion())
// any database modifications that might not be allowed in a transaction.
for (int ver = installedSchemaVersion() + 1; ver <= schemaVersion(); ver++) {
- foreach(QString queryString, upgradeQueries(ver)) {
+ foreach (QString queryString, upgradeQueries(ver)) {
QSqlQuery query = db.exec(queryString);
if (!watchQuery(query)) {
// Individual upgrade query failed, bail out
- qCritical() << "Unable to upgrade Logging Backend! Upgrade query in schema version"
- << ver << "failed.";
+ qCritical() << "Unable to upgrade Logging Backend! Upgrade query in schema version" << ver << "failed.";
return false;
}
}
// version.
if (!updateSchemaVersion(ver)) {
// Updating the schema version failed, bail out
- qCritical() << "Unable to upgrade Logging Backend! Setting schema version"
- << ver << "failed.";
+ qCritical() << "Unable to upgrade Logging Backend! Setting schema version" << ver << "failed.";
return false;
}
}
// logging (though setting schema version really should not fail).
if (!updateSchemaVersion(schemaVersion())) {
// Updating the final schema version failed, bail out
- qCritical() << "Unable to upgrade Logging Backend! Setting final schema version"
- << schemaVersion() << "failed.";
+ qCritical() << "Unable to upgrade Logging Backend! Setting final schema version" << schemaVersion() << "failed.";
return false;
}
return true;
}
-
int AbstractSqlStorage::schemaVersion()
{
// returns the newest Schema Version!
bool ok;
// Schema versions are stored in the 'version/##' subfolders.
QDir dir = QDir(QString(":/SQL/%1/version/").arg(displayName()));
- foreach(QFileInfo fileInfo, dir.entryInfoList()) {
+ foreach (QFileInfo fileInfo, dir.entryInfoList()) {
if (!fileInfo.isDir())
continue;
return _schemaVersion;
}
-
-bool AbstractSqlStorage::watchQuery(QSqlQuery &query)
+bool AbstractSqlStorage::watchQuery(QSqlQuery& query)
{
bool queryError = query.lastError().isValid();
if (queryError || _debug) {
field.clear();
else
field.setValue(iter.value());
- value = query.driver()->formatValue(field);
+ value = query.driver()->formatValue(field);
}
else {
switch (iter.value().type()) {
return true;
}
-
void AbstractSqlStorage::connectionDestroyed()
{
QMutexLocker locker(&_connectionPoolMutex);
_connectionPool.remove(sender()->thread());
}
-
// ========================================
// AbstractSqlStorage::Connection
// ========================================
-AbstractSqlStorage::Connection::Connection(const QString &name, QObject *parent)
- : QObject(parent),
- _name(name.toLatin1())
-{
-}
-
+AbstractSqlStorage::Connection::Connection(const QString& name, QObject* parent)
+ : QObject(parent)
+ , _name(name.toLatin1())
+{}
AbstractSqlStorage::Connection::~Connection()
{
QSqlDatabase::removeDatabase(name());
}
-
// ========================================
// AbstractSqlMigrator
// ========================================
-void AbstractSqlMigrator::newQuery(const QString &query, QSqlDatabase db)
+void AbstractSqlMigrator::newQuery(const QString& query, QSqlDatabase db)
{
Q_ASSERT(!_query);
_query = new QSqlQuery(db);
_query->prepare(query);
}
-
void AbstractSqlMigrator::resetQuery()
{
delete _query;
_query = nullptr;
}
-
bool AbstractSqlMigrator::exec()
{
Q_ASSERT(_query);
return !_query->lastError().isValid();
}
-
QString AbstractSqlMigrator::migrationObject(MigrationObject moType)
{
switch (moType) {
return QString();
}
-
QVariantList AbstractSqlMigrator::boundValues()
{
QVariantList values;
return values;
}
-
void AbstractSqlMigrator::dumpStatus()
{
qWarning() << " executed Query:";
QList<QVariant> list = boundValues();
for (int i = 0; i < list.size(); ++i)
qWarning() << i << ": " << list.at(i).toString().toLatin1().data();
- qWarning() << " Error Number:" << lastError().number();
- qWarning() << " Error Message:" << lastError().text();
+ qWarning() << " Error Number:" << lastError().number();
+ qWarning() << " Error Message:" << lastError().text();
}
-
// ========================================
// AbstractSqlMigrationReader
// ========================================
AbstractSqlMigrationReader::AbstractSqlMigrationReader()
: AbstractSqlMigrator()
-{
-}
+{}
-
-bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter *writer)
+bool AbstractSqlMigrationReader::migrateTo(AbstractSqlMigrationWriter* writer)
{
if (!transaction()) {
qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start reader's transaction!";
}
if (!writer->transaction()) {
qWarning() << "AbstractSqlMigrationReader::migrateTo(): unable to start writer's transaction!";
- rollback(); // close the reader transaction;
+ rollback(); // close the reader transaction;
return false;
}
return finalizeMigration();
}
-
-void AbstractSqlMigrationReader::abortMigration(const QString &errorMsg)
+void AbstractSqlMigrationReader::abortMigration(const QString& errorMsg)
{
qWarning() << "Migration Failed!";
if (!errorMsg.isNull()) {
_writer = nullptr;
}
-
bool AbstractSqlMigrationReader::finalizeMigration()
{
resetQuery();
return true;
}
-
template<typename T>
-bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T &mo)
+bool AbstractSqlMigrationReader::transferMo(MigrationObject moType, T& mo)
{
resetQuery();
_writer->resetQuery();
if (!prepareQuery(moType)) {
- abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
+ abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare reader query of type %1!")
+ .arg(AbstractSqlMigrator::migrationObject(moType)));
return false;
}
if (!_writer->prepareQuery(moType)) {
- abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
+ abortMigration(QString("AbstractSqlMigrationReader::migrateTo(): unable to prepare writer query of type %1!")
+ .arg(AbstractSqlMigrator::migrationObject(moType)));
return false;
}
while (readMo(mo)) {
if (!_writer->writeMo(mo)) {
- abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!").arg(AbstractSqlMigrator::migrationObject(moType)));
+ abortMigration(QString("AbstractSqlMigrationReader::transferMo(): unable to transfer Migratable Object of type %1!")
+ .arg(AbstractSqlMigrator::migrationObject(moType)));
return false;
}
i++;
return true;
}
-uint qHash(const SenderData &key) {
+uint qHash(const SenderData& key)
+{
return qHash(QString(key.sender + "\n" + key.realname + "\n" + key.avatarurl));
}
-bool operator==(const SenderData &a, const SenderData &b) {
- return a.sender == b.sender &&
- a.realname == b.realname &&
- a.avatarurl == b.avatarurl;
+bool operator==(const SenderData& a, const SenderData& b)
+{
+ return a.sender == b.sender && a.realname == b.realname && a.avatarurl == b.avatarurl;
}
#pragma once
-#include "storage.h"
-
#include <memory>
#include <QSqlDatabase>
-#include <QSqlQuery>
#include <QSqlError>
+#include <QSqlQuery>
+
+#include "storage.h"
class AbstractSqlMigrationReader;
class AbstractSqlMigrationWriter;
Q_OBJECT
public:
- AbstractSqlStorage(QObject *parent = nullptr);
+ AbstractSqlStorage(QObject* parent = nullptr);
~AbstractSqlStorage() override;
virtual std::unique_ptr<AbstractSqlMigrationReader> createMigrationReader() { return {}; }
virtual std::unique_ptr<AbstractSqlMigrationWriter> createMigrationWriter() { return {}; }
public slots:
- State init(const QVariantMap &settings = QVariantMap(),
- const QProcessEnvironment &environment = {},
- bool loadFromEnvironment = false) override;
- bool setup(const QVariantMap &settings = QVariantMap(),
- const QProcessEnvironment &environment = {},
- bool loadFromEnvironment = false) override;
+ State init(const QVariantMap& settings = QVariantMap(),
+ const QProcessEnvironment& environment = {},
+ bool loadFromEnvironment = false) override;
+ bool setup(const QVariantMap& settings = QVariantMap(),
+ const QProcessEnvironment& environment = {},
+ bool loadFromEnvironment = false) override;
protected:
- inline void sync() override {};
+ inline void sync() override{};
QSqlDatabase logDb();
* @endparblock
* @return String with the requested SQL query, ready for parameter substitution
*/
- QString queryString(const QString &queryName, int version = 0);
+ QString queryString(const QString& queryName, int version = 0);
QStringList setupQueries();
QStringList upgradeQueries(int ver);
bool upgradeDb();
- bool watchQuery(QSqlQuery &query);
+ bool watchQuery(QSqlQuery& query);
int schemaVersion();
virtual int installedSchemaVersion() { return -1; };
virtual bool updateSchemaVersion(int newVersion) = 0;
virtual bool setupSchemaVersion(int version) = 0;
- virtual void setConnectionProperties(const QVariantMap &properties,
- const QProcessEnvironment &environment,
- bool loadFromEnvironment) = 0;
+ virtual void setConnectionProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment) = 0;
virtual QString driverName() = 0;
inline virtual QString hostName() { return QString(); }
inline virtual int port() { return -1; }
* When reimplementing this method, don't use logDB() inside this function as
* this would cause as we're just about to initialize that DB connection.
*/
- inline virtual bool initDbSession(QSqlDatabase & /* db */) { return true; }
+ inline virtual bool initDbSession(QSqlDatabase& /* db */) { return true; }
private slots:
void connectionDestroyed();
private:
void addConnectionToPool();
- void dbConnect(QSqlDatabase &db);
+ void dbConnect(QSqlDatabase& db);
int _schemaVersion{0};
bool _debug;
// those objects reside in the thread the connection belongs to
// which allows us thread safe termination of a connection
class Connection;
- QHash<QThread *, Connection *> _connectionPool;
+ QHash<QThread*, Connection*> _connectionPool;
};
-struct SenderData {
+struct SenderData
+{
QString sender;
QString realname;
QString avatarurl;
- friend uint qHash(const SenderData &key);
- friend bool operator==(const SenderData &a, const SenderData &b);
+ friend uint qHash(const SenderData& key);
+ friend bool operator==(const SenderData& a, const SenderData& b);
};
// ========================================
Q_OBJECT
public:
- Connection(const QString &name, QObject *parent = nullptr);
+ Connection(const QString& name, QObject* parent = nullptr);
~Connection() override;
inline QLatin1String name() const { return QLatin1String(_name); }
QByteArray _name;
};
-
// ========================================
// AbstractSqlMigrator
// ========================================
{
public:
// migration objects
- struct QuasselUserMO {
+ struct QuasselUserMO
+ {
UserId id;
QString username;
QString password;
QString authenticator;
};
- struct SenderMO {
+ struct SenderMO
+ {
qint64 senderId{0};
QString sender;
QString realname;
QString avatarurl;
};
- struct IdentityMO {
+ struct IdentityMO
+ {
IdentityId id;
UserId userid;
QString identityname;
QByteArray sslKey;
};
- struct IdentityNickMO {
+ struct IdentityNickMO
+ {
int nickid;
IdentityId identityId;
QString nick;
};
- struct NetworkMO {
+ struct NetworkMO
+ {
UserId userid;
QString networkname;
QString perform;
bool connected;
};
- struct BufferMO {
+ struct BufferMO
+ {
BufferId bufferid;
UserId userid;
int groupid;
QString cipher;
};
- struct BacklogMO {
+ struct BacklogMO
+ {
MsgId messageid;
- QDateTime time; // has to be in UTC!
+ QDateTime time; // has to be in UTC!
BufferId bufferid;
int type;
int flags;
QString message;
};
- struct IrcServerMO {
+ struct IrcServerMO
+ {
int serverid;
UserId userid;
NetworkId networkid;
int port;
QString password;
bool ssl;
- bool sslverify; /// If true, validate SSL certificates
+ bool sslverify; /// If true, validate SSL certificates
int sslversion;
bool useproxy;
int proxytype;
QString proxypass;
};
- struct UserSettingMO {
+ struct UserSettingMO
+ {
UserId userid;
QString settingname;
QByteArray settingvalue;
};
- struct CoreStateMO {
+ struct CoreStateMO
+ {
QString key;
QByteArray value;
};
- enum MigrationObject {
+ enum MigrationObject
+ {
QuasselUser,
Sender,
Identity,
static QString migrationObject(MigrationObject moType);
protected:
- void newQuery(const QString &query, QSqlDatabase db);
+ void newQuery(const QString& query, QSqlDatabase db);
virtual void resetQuery();
virtual bool prepareQuery(MigrationObject mo) = 0;
bool exec();
inline bool next() { return _query->next(); }
inline QVariant value(int index) { return _query->value(index); }
- inline void bindValue(const QString &placeholder, const QVariant &val) { _query->bindValue(placeholder, val); }
- inline void bindValue(int pos, const QVariant &val) { _query->bindValue(pos, val); }
+ inline void bindValue(const QString& placeholder, const QVariant& val) { _query->bindValue(placeholder, val); }
+ inline void bindValue(int pos, const QVariant& val) { _query->bindValue(pos, val); }
inline QSqlError lastError() { return _query ? _query->lastError() : QSqlError(); }
void dumpStatus();
virtual bool commit() = 0;
private:
- QSqlQuery *_query{nullptr};
+ QSqlQuery* _query{nullptr};
};
-
class AbstractSqlMigrationReader : public AbstractSqlMigrator
{
public:
AbstractSqlMigrationReader();
- virtual bool readMo(QuasselUserMO &user) = 0;
- virtual bool readMo(IdentityMO &identity) = 0;
- virtual bool readMo(IdentityNickMO &identityNick) = 0;
- virtual bool readMo(NetworkMO &network) = 0;
- virtual bool readMo(BufferMO &buffer) = 0;
- virtual bool readMo(SenderMO &sender) = 0;
- virtual bool readMo(BacklogMO &backlog) = 0;
- virtual bool readMo(IrcServerMO &ircserver) = 0;
- virtual bool readMo(UserSettingMO &userSetting) = 0;
- virtual bool readMo(CoreStateMO &coreState) = 0;
+ virtual bool readMo(QuasselUserMO& user) = 0;
+ virtual bool readMo(IdentityMO& identity) = 0;
+ virtual bool readMo(IdentityNickMO& identityNick) = 0;
+ virtual bool readMo(NetworkMO& network) = 0;
+ virtual bool readMo(BufferMO& buffer) = 0;
+ virtual bool readMo(SenderMO& sender) = 0;
+ virtual bool readMo(BacklogMO& backlog) = 0;
+ virtual bool readMo(IrcServerMO& ircserver) = 0;
+ virtual bool readMo(UserSettingMO& userSetting) = 0;
+ virtual bool readMo(CoreStateMO& coreState) = 0;
- bool migrateTo(AbstractSqlMigrationWriter *writer);
+ bool migrateTo(AbstractSqlMigrationWriter* writer);
private:
- void abortMigration(const QString &errorMsg = QString());
+ void abortMigration(const QString& errorMsg = QString());
bool finalizeMigration();
- template<typename T> bool transferMo(MigrationObject moType, T &mo);
+ template<typename T>
+ bool transferMo(MigrationObject moType, T& mo);
- AbstractSqlMigrationWriter *_writer{nullptr};
+ AbstractSqlMigrationWriter* _writer{nullptr};
};
-
class AbstractSqlMigrationWriter : public AbstractSqlMigrator
{
public:
- virtual bool writeMo(const QuasselUserMO &user) = 0;
- virtual bool writeMo(const IdentityMO &identity) = 0;
- virtual bool writeMo(const IdentityNickMO &identityNick) = 0;
- virtual bool writeMo(const NetworkMO &network) = 0;
- virtual bool writeMo(const BufferMO &buffer) = 0;
- virtual bool writeMo(const SenderMO &sender) = 0;
- virtual bool writeMo(const BacklogMO &backlog) = 0;
- virtual bool writeMo(const IrcServerMO &ircserver) = 0;
- virtual bool writeMo(const UserSettingMO &userSetting) = 0;
- virtual bool writeMo(const CoreStateMO &coreState) = 0;
-
- inline bool migrateFrom(AbstractSqlMigrationReader *reader) { return reader->migrateTo(this); }
+ virtual bool writeMo(const QuasselUserMO& user) = 0;
+ virtual bool writeMo(const IdentityMO& identity) = 0;
+ virtual bool writeMo(const IdentityNickMO& identityNick) = 0;
+ virtual bool writeMo(const NetworkMO& network) = 0;
+ virtual bool writeMo(const BufferMO& buffer) = 0;
+ virtual bool writeMo(const SenderMO& sender) = 0;
+ virtual bool writeMo(const BacklogMO& backlog) = 0;
+ virtual bool writeMo(const IrcServerMO& ircserver) = 0;
+ virtual bool writeMo(const UserSettingMO& userSetting) = 0;
+ virtual bool writeMo(const CoreStateMO& coreState) = 0;
+
+ inline bool migrateFrom(AbstractSqlMigrationReader* reader) { return reader->migrateTo(this); }
// called after migration process
virtual inline bool postProcess() { return true; }
// Make moc happy
#include "authenticator.h"
+
#include "moc_authenticator.cpp"
#include "types.h"
-class Authenticator : public QObject {
-
+class Authenticator : public QObject
+{
Q_OBJECT
public:
using QObject::QObject;
~Authenticator() override = default;
- enum State {
+ enum State
+ {
IsReady, // ready to go
NeedsSetup, // need basic setup (ask the user for input)
NotAvailable // remove the authenticator backend from the list of avaliable authenticators.
};
-
public slots:
// General
* \param settings Hostname, port, username, password, ...
* \return True if and only if the authenticator provider was initialized successfully.
*/
- virtual bool setup(const QVariantMap &settings = QVariantMap(),
- const QProcessEnvironment &environment = {},
- bool loadFromEnvironment = false) = 0;
+ virtual bool setup(const QVariantMap& settings = QVariantMap(),
+ const QProcessEnvironment& environment = {},
+ bool loadFromEnvironment = false)
+ = 0;
//! Initialize the authenticator provider
/** \param settings Hostname, port, username, password, ...
* \return the State the authenticator backend is now in (see authenticator::State)
*/
- virtual State init(const QVariantMap &settings = QVariantMap(),
- const QProcessEnvironment &environment = {},
- bool loadFromEnvironment = false) = 0;
+ virtual State init(const QVariantMap& settings = QVariantMap(),
+ const QProcessEnvironment& environment = {},
+ bool loadFromEnvironment = false)
+ = 0;
//! Validate a username with a given password.
/** \param user The username to validate
* \param password The user's alleged password
* \return A valid UserId if the password matches the username; 0 else
*/
- virtual UserId validateUser(const QString &user, const QString &password) = 0;
+ virtual UserId validateUser(const QString& user, const QString& password) = 0;
};
*/
#include "cipher.h"
+
#include "logmessage.h"
Cipher::Cipher()
{
- m_primeNum = QCA::BigInteger("12745216229761186769575009943944198619149164746831579719941140425076456621824834322853258804883232842877311723249782818608677050956745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862335062591404043092163187352352197487303798807791605274487594646923");
+ m_primeNum = QCA::BigInteger(
+ "1274521622976118676957500994394419861914916474683157971994114042507645662182483432285325880488323284287731172324978281860867705095"
+ "6745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862"
+ "335062591404043092163187352352197487303798807791605274487594646923");
setType("blowfish");
}
-
Cipher::Cipher(QByteArray key, QString cipherType)
{
- m_primeNum = QCA::BigInteger("12745216229761186769575009943944198619149164746831579719941140425076456621824834322853258804883232842877311723249782818608677050956745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862335062591404043092163187352352197487303798807791605274487594646923");
+ m_primeNum = QCA::BigInteger(
+ "1274521622976118676957500994394419861914916474683157971994114042507645662182483432285325880488323284287731172324978281860867705095"
+ "6745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862"
+ "335062591404043092163187352352197487303798807791605274487594646923");
setKey(key);
setType(cipherType);
}
-
bool Cipher::setKey(QByteArray key)
{
if (key.isEmpty()) {
return false;
}
- if (key.mid(0, 4).toLower() == "ecb:")
- {
+ if (key.mid(0, 4).toLower() == "ecb:") {
m_cbc = false;
m_key = key.mid(4);
}
- //strip cbc: if included
- else if (key.mid(0, 4).toLower() == "cbc:")
- {
+ // strip cbc: if included
+ else if (key.mid(0, 4).toLower() == "cbc:") {
m_cbc = true;
m_key = key.mid(4);
}
- else
- {
-// if(Preferences::self()->encryptionType())
-// m_cbc = true;
-// else
-// default to CBC
+ else {
+ // if(Preferences::self()->encryptionType())
+ // m_cbc = true;
+ // else
+ // default to CBC
m_cbc = true;
m_key = key;
}
return true;
}
-
-bool Cipher::setType(const QString &type)
+bool Cipher::setType(const QString& type)
{
- //TODO check QCA::isSupported()
+ // TODO check QCA::isSupported()
m_type = type;
return true;
}
-
QByteArray Cipher::decrypt(QByteArray cipherText)
{
QByteArray pfx = "";
- bool error = false; // used to flag non cbc, seems like good practice not to parse w/o regard for set encryption type
+ bool error = false; // used to flag non cbc, seems like good practice not to parse w/o regard for set encryption type
- //if we get cbc
- if (cipherText.mid(0, 5) == "+OK *")
- {
- //if we have cbc
+ // if we get cbc
+ if (cipherText.mid(0, 5) == "+OK *") {
+ // if we have cbc
if (m_cbc)
cipherText = cipherText.mid(5);
- //if we don't
- else
- {
+ // if we don't
+ else {
cipherText = cipherText.mid(5);
pfx = "ERROR_NONECB: ";
error = true;
}
}
- //if we get ecb
- else if (cipherText.mid(0, 4) == "+OK " || cipherText.mid(0, 5) == "mcps ")
- {
- //if we had cbc
- if (m_cbc)
- {
+ // if we get ecb
+ else if (cipherText.mid(0, 4) == "+OK " || cipherText.mid(0, 5) == "mcps ") {
+ // if we had cbc
+ if (m_cbc) {
cipherText = (cipherText.mid(0, 4) == "+OK ") ? cipherText.mid(4) : cipherText.mid(5);
pfx = "ERROR_NONCBC: ";
error = true;
}
- //if we don't
- else
- {
+ // if we don't
+ else {
if (cipherText.mid(0, 4) == "+OK ")
cipherText = cipherText.mid(4);
else
cipherText = cipherText.mid(5);
}
}
- //all other cases we fail
+ // all other cases we fail
else
return cipherText;
QByteArray temp;
// (if cbc and no error we parse cbc) || (if ecb and error we parse cbc)
- if ((m_cbc && !error) || (!m_cbc && error))
- {
+ if ((m_cbc && !error) || (!m_cbc && error)) {
temp = blowfishCBC(cipherText, false);
- if (temp == cipherText)
- {
+ if (temp == cipherText) {
// kDebug("Decryption from CBC Failed");
- return cipherText+' '+'\n';
+ return cipherText + ' ' + '\n';
}
else
cipherText = temp;
}
- else
- {
+ else {
temp = blowfishECB(cipherText, false);
- if (temp == cipherText)
- {
+ if (temp == cipherText) {
// kDebug("Decryption from ECB Failed");
- return cipherText+' '+'\n';
+ return cipherText + ' ' + '\n';
}
else
cipherText = temp;
// don't hate me for the mircryption reference there.
if (cipherText.at(0) == 1)
pfx = "\x0";
- cipherText = pfx+cipherText+' '+'\n'; // FIXME(??) why is there an added space here?
+ cipherText = pfx + cipherText + ' ' + '\n'; // FIXME(??) why is there an added space here?
return cipherText;
}
-
QByteArray Cipher::initKeyExchange()
{
QCA::Initializer init;
QByteArray publicKey = m_tempKey.toPublicKey().toDH().y().toArray().toByteArray();
- //remove leading 0
+ // remove leading 0
if (publicKey.length() > 135 && publicKey.at(0) == '\0')
publicKey = publicKey.mid(1);
return publicKey.toBase64().append('A');
}
-
QByteArray Cipher::parseInitKeyX(QByteArray key)
{
QCA::Initializer init;
bool isCBC = false;
- if (key.endsWith(" CBC"))
- {
+ if (key.endsWith(" CBC")) {
isCBC = true;
key.chop(4);
}
QByteArray publicKey = privateKey.y().toArray().toByteArray();
- //remove leading 0
+ // remove leading 0
if (publicKey.length() > 135 && publicKey.at(0) == '\0')
publicKey = publicKey.mid(1);
QByteArray sharedKey = privateKey.deriveKey(remotePub).toByteArray();
sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64();
- //remove trailing = because mircryption and fish think it's a swell idea.
- while (sharedKey.endsWith('=')) sharedKey.chop(1);
+ // remove trailing = because mircryption and fish think it's a swell idea.
+ while (sharedKey.endsWith('='))
+ sharedKey.chop(1);
if (isCBC)
sharedKey.prepend("cbc:");
return publicKey.toBase64().append('A');
}
-
bool Cipher::parseFinishKeyX(QByteArray key)
{
QCA::Initializer init;
QByteArray sharedKey = m_tempKey.deriveKey(remotePub).toByteArray();
sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64();
- //remove trailng = because mircryption and fish think it's a swell idea.
- while (sharedKey.endsWith('=')) sharedKey.chop(1);
+ // remove trailng = because mircryption and fish think it's a swell idea.
+ while (sharedKey.endsWith('='))
+ sharedKey.chop(1);
bool success = setKey(sharedKey);
return success;
}
-
QByteArray Cipher::decryptTopic(QByteArray cipherText)
{
- if (cipherText.mid(0, 4) == "+OK ") // FiSH style topic
+ if (cipherText.mid(0, 4) == "+OK ") // FiSH style topic
cipherText = cipherText.mid(4);
else if (cipherText.left(5) == "«m«")
- cipherText = cipherText.mid(5, cipherText.length()-10);
+ cipherText = cipherText.mid(5, cipherText.length() - 10);
else
return cipherText;
QByteArray temp;
- //TODO currently no backwards sanity checks for topic, it seems to use different standards
- //if somebody figures them out they can enable it and add "ERROR_NONECB/CBC" warnings
+ // TODO currently no backwards sanity checks for topic, it seems to use different standards
+ // if somebody figures them out they can enable it and add "ERROR_NONECB/CBC" warnings
if (m_cbc)
temp = blowfishCBC(cipherText.mid(1), false);
else
temp = blowfishECB(cipherText, false);
- if (temp == cipherText)
- {
+ if (temp == cipherText) {
return cipherText;
}
else
return cipherText;
}
-
-bool Cipher::encrypt(QByteArray &cipherText)
+bool Cipher::encrypt(QByteArray& cipherText)
{
- if (cipherText.left(3) == "+p ") //don't encode if...?
+ if (cipherText.left(3) == "+p ") // don't encode if...?
cipherText = cipherText.mid(3);
- else
- {
- if (m_cbc) //encode in ecb or cbc decide how to determine later
+ else {
+ if (m_cbc) // encode in ecb or cbc decide how to determine later
{
QByteArray temp = blowfishCBC(cipherText, true);
- if (temp == cipherText)
- {
+ if (temp == cipherText) {
// kDebug("CBC Encoding Failed");
return false;
}
cipherText = "+OK *" + temp;
}
- else
- {
+ else {
QByteArray temp = blowfishECB(cipherText, true);
- if (temp == cipherText)
- {
+ if (temp == cipherText) {
// kDebug("ECB Encoding Failed");
return false;
}
return true;
}
-
-//THE BELOW WORKS AKA DO NOT TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING
+// THE BELOW WORKS AKA DO NOT TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING
QByteArray Cipher::blowfishCBC(QByteArray cipherText, bool direction)
{
QCA::Initializer init;
QByteArray temp = cipherText;
- if (direction)
- {
+ if (direction) {
// make sure cipherText is an interval of 8 bits. We do this before so that we
// know there's at least 8 bytes to en/decryption this ensures QCA doesn't fail
- while ((temp.length() % 8) != 0) temp.append('\0');
+ while ((temp.length() % 8) != 0)
+ temp.append('\0');
QCA::InitializationVector iv(8);
- temp.prepend(iv.toByteArray()); // prefix with 8bits of IV for mircryptions *CUSTOM* cbc implementation
+ temp.prepend(iv.toByteArray()); // prefix with 8bits of IV for mircryptions *CUSTOM* cbc implementation
}
- else
- {
+ else {
temp = QByteArray::fromBase64(temp);
- //supposedly nescessary if we get a truncated message also allows for decryption of 'crazy'
- //en/decoding clients that use STANDARDIZED PADDING TECHNIQUES
- while ((temp.length() % 8) != 0) temp.append('\0');
+ // supposedly nescessary if we get a truncated message also allows for decryption of 'crazy'
+ // en/decoding clients that use STANDARDIZED PADDING TECHNIQUES
+ while ((temp.length() % 8) != 0)
+ temp.append('\0');
}
QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
if (!cipher.ok())
return cipherText;
- if (direction) //send in base64
+ if (direction) // send in base64
temp2 = temp2.toBase64();
- else //cut off the 8bits of IV
+ else // cut off the 8bits of IV
temp2 = temp2.remove(0, 8);
return temp2;
}
-
QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)
{
QCA::Initializer init;
QByteArray temp = cipherText;
- //do padding ourselves
- if (direction)
- {
- while ((temp.length() % 8) != 0) temp.append('\0');
+ // do padding ourselves
+ if (direction) {
+ while ((temp.length() % 8) != 0)
+ temp.append('\0');
}
- else
- {
+ else {
// ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input
if ((temp.length() % 12) != 0)
return cipherText;
temp = b64ToByte(temp);
- while ((temp.length() % 8) != 0) temp.append('\0');
+ while ((temp.length() % 8) != 0)
+ temp.append('\0');
}
QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
return temp2;
}
-
-//Custom non RFC 2045 compliant Base64 enc/dec code for mircryption / FiSH compatibility
+// Custom non RFC 2045 compliant Base64 enc/dec code for mircryption / FiSH compatibility
QByteArray Cipher::byteToB64(QByteArray text)
{
int left = 0;
QByteArray encoded;
while (k < (text.length() - 1)) {
k++;
- v = text.at(k); if (v < 0) v += 256;
+ v = text.at(k);
+ if (v < 0)
+ v += 256;
left = v << 24;
k++;
- v = text.at(k); if (v < 0) v += 256;
+ v = text.at(k);
+ if (v < 0)
+ v += 256;
left += v << 16;
k++;
- v = text.at(k); if (v < 0) v += 256;
+ v = text.at(k);
+ if (v < 0)
+ v += 256;
left += v << 8;
k++;
- v = text.at(k); if (v < 0) v += 256;
+ v = text.at(k);
+ if (v < 0)
+ v += 256;
left += v;
k++;
- v = text.at(k); if (v < 0) v += 256;
+ v = text.at(k);
+ if (v < 0)
+ v += 256;
right = v << 24;
k++;
- v = text.at(k); if (v < 0) v += 256;
+ v = text.at(k);
+ if (v < 0)
+ v += 256;
right += v << 16;
k++;
- v = text.at(k); if (v < 0) v += 256;
+ v = text.at(k);
+ if (v < 0)
+ v += 256;
right += v << 8;
k++;
- v = text.at(k); if (v < 0) v += 256;
+ v = text.at(k);
+ if (v < 0)
+ v += 256;
right += v;
for (int i = 0; i < 6; i++) {
right = right >> 6;
}
- //TODO make sure the .toLatin1 doesn't break anything
+ // TODO make sure the .toLatin1 doesn't break anything
for (int i = 0; i < 6; i++) {
encoded.append(base64.at(left & 0x3F).toLatin1());
left = left >> 6;
return encoded;
}
-
QByteArray Cipher::b64ToByte(QByteArray text)
{
QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < 4; i++) {
w = ((left & (0xFF << ((3 - i) * 8))));
z = w >> ((3 - i) * 8);
- if (z < 0) { z = z + 256; }
+ if (z < 0) {
+ z = z + 256;
+ }
decoded.append(z);
}
for (int i = 0; i < 4; i++) {
w = ((right & (0xFF << ((3 - i) * 8))));
z = w >> ((3 - i) * 8);
- if (z < 0) { z = z + 256; }
+ if (z < 0) {
+ z = z + 256;
+ }
decoded.append(z);
}
}
return decoded;
}
-
bool Cipher::neededFeaturesAvailable()
{
QCA::Initializer init;
explicit Cipher(QByteArray key, QString cipherType = QString("blowfish"));
QByteArray decrypt(QByteArray cipher);
QByteArray decryptTopic(QByteArray cipher);
- bool encrypt(QByteArray &cipher);
+ bool encrypt(QByteArray& cipher);
QByteArray initKeyExchange();
QByteArray parseInitKeyX(QByteArray key);
bool parseFinishKeyX(QByteArray key);
bool setKey(QByteArray key);
QByteArray key() { return m_key; }
- bool setType(const QString &type);
+ bool setType(const QString& type);
QString type() { return m_type; }
static bool neededFeaturesAvailable();
inline bool usesCBC() { return m_cbc; }
private:
- //direction is true for encrypt, false for decrypt
+ // direction is true for encrypt, false for decrypt
QByteArray blowfishCBC(QByteArray cipherText, bool direction);
QByteArray blowfishECB(QByteArray cipherText, bool direction);
QByteArray b64ToByte(QByteArray text);
bool m_cbc;
};
-
-#endif // CIPHER_H
+#endif // CIPHER_H
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "core.h"
+
#include <algorithm>
#include <QCoreApplication>
-#include "core.h"
#include "coreauthhandler.h"
#include "coresession.h"
#include "coresettings.h"
#include "util.h"
#ifdef HAVE_LDAP
-# include "ldapauthenticator.h"
+# include "ldapauthenticator.h"
#endif
// migration related
#include <QFile>
#ifdef Q_OS_WIN
-# include <windows.h>
+# include <windows.h>
#else
-# include <unistd.h>
-# include <termios.h>
+# include <termios.h>
+# include <unistd.h>
#endif /* Q_OS_WIN */
// ==============================
class AddClientEvent : public QEvent
{
public:
- AddClientEvent(RemotePeer *p, UserId uid) : QEvent(QEvent::Type(Core::AddClientEventId)), peer(p), userId(uid) {}
- RemotePeer *peer;
+ AddClientEvent(RemotePeer* p, UserId uid)
+ : QEvent(QEvent::Type(Core::AddClientEventId))
+ , peer(p)
+ , userId(uid)
+ {}
+ RemotePeer* peer;
UserId userId;
};
-
// ==============================
// Core
// ==============================
_storageSyncTimer.setParent(this);
}
-
Core::~Core()
{
qDeleteAll(_connectingClients);
syncStorage();
}
-
void Core::init()
{
- _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
+ _startTime = QDateTime::currentDateTime().toUTC(); // for uptime :)
// check settings version
// so far, we only have 1
_oidentdConfigGenerator = new OidentdConfigGenerator(this);
}
-
if (Quassel::isOptionSet("ident-daemon")) {
_identServer = new IdentServer(this);
}
});
connect(&_storageSyncTimer, &QTimer::timeout, this, &Core::syncStorage);
- _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
+ _storageSyncTimer.start(10 * 60 * 1000); // 10 minutes
}
connect(&_server, &QTcpServer::newConnection, this, &Core::incomingConnection);
}
}
-
void Core::initAsync()
{
try {
}
}
-
void Core::shutdown()
{
quInfo() << "Core shutting down...";
saveState();
- for (auto &&client : _connectingClients) {
+ for (auto&& client : _connectingClients) {
client->deleteLater();
}
_connectingClients.clear();
return;
}
- for (auto &&session : _sessions) {
+ for (auto&& session : _sessions) {
connect(session, &SessionThread::shutdownComplete, this, &Core::onSessionShutdown);
session->shutdown();
}
}
-
-void Core::onSessionShutdown(SessionThread *session)
+void Core::onSessionShutdown(SessionThread* session)
{
_sessions.take(_sessions.key(session))->deleteLater();
if (_sessions.isEmpty()) {
}
}
-
/*** Session Restore ***/
void Core::saveState()
{
if (_storage) {
QVariantList activeSessions;
- for (auto &&user : instance()->_sessions.keys())
+ for (auto&& user : instance()->_sessions.keys())
activeSessions << QVariant::fromValue<UserId>(user);
_storage->setCoreState(activeSessions);
}
}
-
void Core::restoreState()
{
if (!_configured) {
}
*/
- const QList<QVariant> &activeSessionsFallback = s.coreState().toMap()["ActiveSessions"].toList();
+ const QList<QVariant>& activeSessionsFallback = s.coreState().toMap()["ActiveSessions"].toList();
QVariantList activeSessions = instance()->_storage->getCoreState(activeSessionsFallback);
if (activeSessions.count() > 0) {
quInfo() << "Restoring previous core state...";
- for(auto &&v : activeSessions) {
+ for (auto&& v : activeSessions) {
UserId user = v.value<UserId>();
sessionForUser(user, true);
}
}
}
-
/*** Core Setup ***/
-QString Core::setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
+QString Core::setup(const QString& adminUser,
+ const QString& adminPassword,
+ const QString& backend,
+ const QVariantMap& setupData,
+ const QString& authenticator,
+ const QVariantMap& authSetupData)
{
return instance()->setupCore(adminUser, adminPassword, backend, setupData, authenticator, authSetupData);
}
-
-QString Core::setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupData)
+QString Core::setupCore(const QString& adminUser,
+ const QString& adminPassword,
+ const QString& backend,
+ const QVariantMap& setupData,
+ const QString& authenticator,
+ const QVariantMap& authSetupData)
{
if (_configured)
return tr("Core is already configured! Not configuring again...");
}
quInfo() << "Selected authenticator:" << authenticator;
- if (!(_configured = initAuthenticator(authenticator, authSetupData, {}, false, true)))
- {
+ if (!(_configured = initAuthenticator(authenticator, authSetupData, {}, false, true))) {
return tr("Could not setup authenticator!");
}
}
quInfo() << qPrintable(tr("Creating admin user..."));
_storage->addUser(adminUser, adminPassword);
cacheSysIdent();
- startListening(); // TODO check when we need this
+ startListening(); // TODO check when we need this
return QString();
}
-
QString Core::setupCoreForInternalUsage()
{
Q_ASSERT(!_registeredStorageBackends.empty());
return setupCore("AdminUser", QString::number(pass), "SQLite", QVariantMap(), "Database", QVariantMap());
}
-
/*** Storage Handling ***/
template<typename Storage>
backend->deleteLater();
}
-
void Core::registerStorageBackends()
{
if (_registeredStorageBackends.empty()) {
}
}
-
-DeferredSharedPtr<Storage> Core::storageBackend(const QString &backendId) const
+DeferredSharedPtr<Storage> Core::storageBackend(const QString& backendId) const
{
- auto it = std::find_if(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
- [backendId](const DeferredSharedPtr<Storage> &backend) {
- return backend->displayName() == backendId;
- });
+ auto it = std::find_if(_registeredStorageBackends.begin(),
+ _registeredStorageBackends.end(),
+ [backendId](const DeferredSharedPtr<Storage>& backend) { return backend->displayName() == backendId; });
return it != _registeredStorageBackends.end() ? *it : nullptr;
}
-
-bool Core::initStorage(const QString &backend, const QVariantMap &settings,
- const QProcessEnvironment &environment, bool loadFromEnvironment, bool setup)
+bool Core::initStorage(
+ const QString& backend, const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment, bool setup)
{
if (backend.isEmpty()) {
quWarning() << "No storage backend selected!";
case Storage::IsReady:
// delete all other backends
_registeredStorageBackends.clear();
- connect(storage.get(), &Storage::bufferInfoUpdated,
- this, &Core::bufferInfoUpdated);
+ connect(storage.get(), &Storage::bufferInfoUpdated, this, &Core::bufferInfoUpdated);
break;
}
_storage = std::move(storage);
return true;
}
-
void Core::syncStorage()
{
if (_storage)
_storage->sync();
}
-
/*** Storage Access ***/
-bool Core::createNetwork(UserId user, NetworkInfo &info)
+bool Core::createNetwork(UserId user, NetworkInfo& info)
{
NetworkId networkId = instance()->_storage->createNetwork(user, info);
if (!networkId.isValid())
return true;
}
-
/*** Authenticators ***/
// Authentication handling, now independent from storage.
authenticator->deleteLater();
}
-
void Core::registerAuthenticators()
{
if (_registeredAuthenticators.empty()) {
}
}
-
-DeferredSharedPtr<Authenticator> Core::authenticator(const QString &backendId) const
+DeferredSharedPtr<Authenticator> Core::authenticator(const QString& backendId) const
{
- auto it = std::find_if(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
- [backendId](const DeferredSharedPtr<Authenticator> &authenticator) {
+ auto it = std::find_if(_registeredAuthenticators.begin(),
+ _registeredAuthenticators.end(),
+ [backendId](const DeferredSharedPtr<Authenticator>& authenticator) {
return authenticator->backendId() == backendId;
});
return it != _registeredAuthenticators.end() ? *it : nullptr;
}
-
// FIXME: Apparently, this is the legacy way of initting storage backends?
// If there's a not-legacy way, it should be used here
-bool Core::initAuthenticator(const QString &backend, const QVariantMap &settings,
- const QProcessEnvironment &environment, bool loadFromEnvironment,
- bool setup)
+bool Core::initAuthenticator(
+ const QString& backend, const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment, bool setup)
{
if (backend.isEmpty()) {
quWarning() << "No authenticator selected!";
return true;
}
-
/*** Network Management ***/
bool Core::sslSupported()
{
#ifdef HAVE_SSL
- auto *sslServer = qobject_cast<SslServer *>(&instance()->_server);
+ auto* sslServer = qobject_cast<SslServer*>(&instance()->_server);
return sslServer && sslServer->isCertValid();
#else
return false;
#endif
}
-
bool Core::reloadCerts()
{
#ifdef HAVE_SSL
- auto *sslServerv4 = qobject_cast<SslServer *>(&_server);
+ auto* sslServerv4 = qobject_cast<SslServer*>(&_server);
bool retv4 = sslServerv4->reloadCerts();
- auto *sslServerv6 = qobject_cast<SslServer *>(&_v6server);
+ auto* sslServerv6 = qobject_cast<SslServer*>(&_v6server);
bool retv6 = sslServerv6->reloadCerts();
return retv4 && retv6;
#endif
}
-
void Core::cacheSysIdent()
{
if (isConfigured()) {
}
}
-
QString Core::strictSysIdent(UserId user) const
{
if (_authUserNames.contains(user)) {
// ...something very weird is going on if we ended up here (an active CoreSession without a corresponding database entry?)
qWarning().nospace() << "Unable to find authusername for UserId " << user << ", this should never happen!";
- return "unknown"; // Should we just terminate the program instead?
+ return "unknown"; // Should we just terminate the program instead?
}
-
bool Core::startListening()
{
// in mono mode we only start a local port if a port is specified in the cli call
const QString listen = Quassel::optionValue("listen");
const QStringList listen_list = listen.split(",", QString::SkipEmptyParts);
if (listen_list.size() > 0) {
- foreach(const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
+ foreach (const QString listen_term, listen_list) { // TODO: handle multiple interfaces for same TCP version gracefully
QHostAddress addr;
if (!addr.setAddress(listen_term)) {
- qCritical() << qPrintable(
- tr("Invalid listen address %1")
- .arg(listen_term)
- );
+ qCritical() << qPrintable(tr("Invalid listen address %1").arg(listen_term));
}
else {
switch (addr.protocol()) {
case QAbstractSocket::IPv6Protocol:
if (_v6server.listen(addr, port)) {
- quInfo() << qPrintable(
- tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
- .arg(addr.toString())
- .arg(_v6server.serverPort())
- .arg(Quassel::buildInfo().protocolVersion)
- );
+ quInfo() << qPrintable(tr("Listening for GUI clients on IPv6 %1 port %2 using protocol version %3")
+ .arg(addr.toString())
+ .arg(_v6server.serverPort())
+ .arg(Quassel::buildInfo().protocolVersion));
success = true;
}
else
quWarning() << qPrintable(
- tr("Could not open IPv6 interface %1:%2: %3")
- .arg(addr.toString())
- .arg(port)
- .arg(_v6server.errorString()));
+ tr("Could not open IPv6 interface %1:%2: %3").arg(addr.toString()).arg(port).arg(_v6server.errorString()));
break;
case QAbstractSocket::IPv4Protocol:
if (_server.listen(addr, port)) {
- quInfo() << qPrintable(
- tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
- .arg(addr.toString())
- .arg(_server.serverPort())
- .arg(Quassel::buildInfo().protocolVersion)
- );
+ quInfo() << qPrintable(tr("Listening for GUI clients on IPv4 %1 port %2 using protocol version %3")
+ .arg(addr.toString())
+ .arg(_server.serverPort())
+ .arg(Quassel::buildInfo().protocolVersion));
success = true;
}
else {
// if v6 succeeded on Any, the port will be already in use - don't display the error then
if (!success || _server.serverError() != QAbstractSocket::AddressInUseError)
quWarning() << qPrintable(
- tr("Could not open IPv4 interface %1:%2: %3")
- .arg(addr.toString())
- .arg(port)
- .arg(_server.errorString()));
+ tr("Could not open IPv4 interface %1:%2: %3").arg(addr.toString()).arg(port).arg(_server.errorString()));
}
break;
default:
- qCritical() << qPrintable(
- tr("Invalid listen address %1, unknown network protocol")
- .arg(listen_term)
- );
+ qCritical() << qPrintable(tr("Invalid listen address %1, unknown network protocol").arg(listen_term));
break;
}
}
return success;
}
-
-void Core::stopListening(const QString &reason)
+void Core::stopListening(const QString& reason)
{
if (_identServer) {
_identServer->stopListening(reason);
}
}
-
void Core::incomingConnection()
{
- auto *server = qobject_cast<QTcpServer *>(sender());
+ auto* server = qobject_cast<QTcpServer*>(sender());
Q_ASSERT(server);
while (server->hasPendingConnections()) {
- QTcpSocket *socket = server->nextPendingConnection();
+ QTcpSocket* socket = server->nextPendingConnection();
- auto *handler = new CoreAuthHandler(socket, this);
+ auto* handler = new CoreAuthHandler(socket, this);
_connectingClients.insert(handler);
connect(handler, &AuthHandler::disconnected, this, &Core::clientDisconnected);
connect(handler, &AuthHandler::socketError, this, &Core::socketError);
connect(handler, &CoreAuthHandler::handshakeComplete, this, &Core::setupClientSession);
- quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
+ quInfo() << qPrintable(tr("Client connected from")) << qPrintable(socket->peerAddress().toString());
if (!_configured) {
stopListening(tr("Closing server for basic setup."));
}
}
-
// Potentially called during the initialization phase (before handing the connection off to the session)
void Core::clientDisconnected()
{
- auto *handler = qobject_cast<CoreAuthHandler *>(sender());
+ auto* handler = qobject_cast<CoreAuthHandler*>(sender());
Q_ASSERT(handler);
quInfo() << qPrintable(tr("Non-authed client disconnected:")) << qPrintable(handler->socket()->peerAddress().toString());
// Suggestion: kill sessions if they are not connected to any network and client.
}
-
-void Core::setupClientSession(RemotePeer *peer, UserId uid)
+void Core::setupClientSession(RemotePeer* peer, UserId uid)
{
- auto *handler = qobject_cast<CoreAuthHandler *>(sender());
+ auto* handler = qobject_cast<CoreAuthHandler*>(sender());
Q_ASSERT(handler);
// From now on everything is handled by the client session
QCoreApplication::postEvent(this, new AddClientEvent(peer, uid));
}
-
-void Core::customEvent(QEvent *event)
+void Core::customEvent(QEvent* event)
{
if (event->type() == AddClientEventId) {
- auto *addClientEvent = static_cast<AddClientEvent *>(event);
+ auto* addClientEvent = static_cast<AddClientEvent*>(event);
addClientHelper(addClientEvent->peer, addClientEvent->userId);
return;
}
}
-
-void Core::addClientHelper(RemotePeer *peer, UserId uid)
+void Core::addClientHelper(RemotePeer* peer, UserId uid)
{
// Find or create session for validated user
- SessionThread *session = sessionForUser(uid);
+ SessionThread* session = sessionForUser(uid);
session->addClient(peer);
}
-
void Core::connectInternalPeer(QPointer<InternalPeer> peer)
{
if (_initialized && peer) {
}
}
-
void Core::setupInternalClientSession(QPointer<InternalPeer> clientPeer)
{
if (!_configured) {
return;
}
- auto *corePeer = new InternalPeer(this);
+ auto* corePeer = new InternalPeer(this);
corePeer->setPeer(clientPeer);
clientPeer->setPeer(corePeer);
// Find or create session for validated user
- SessionThread *sessionThread = sessionForUser(uid);
+ SessionThread* sessionThread = sessionForUser(uid);
sessionThread->addClient(corePeer);
}
-
-SessionThread *Core::sessionForUser(UserId uid, bool restore)
+SessionThread* Core::sessionForUser(UserId uid, bool restore)
{
if (_sessions.contains(uid))
return _sessions[uid];
return (_sessions[uid] = new SessionThread(uid, restore, strictIdentEnabled(), this));
}
-
-void Core::socketError(QAbstractSocket::SocketError err, const QString &errorString)
+void Core::socketError(QAbstractSocket::SocketError err, const QString& errorString)
{
quWarning() << QString("Socket error %1: %2").arg(err).arg(errorString);
}
-
QVariantList Core::backendInfo()
{
instance()->registerStorageBackends();
QVariantList backendInfos;
- for (auto &&backend : instance()->_registeredStorageBackends) {
+ for (auto&& backend : instance()->_registeredStorageBackends) {
QVariantMap v;
- v["BackendId"] = backend->backendId();
+ v["BackendId"] = backend->backendId();
v["DisplayName"] = backend->displayName();
v["Description"] = backend->description();
- v["SetupData"] = backend->setupData(); // ignored by legacy clients
+ v["SetupData"] = backend->setupData(); // ignored by legacy clients
// TODO Protocol Break: Remove legacy (cf. authenticatorInfo())
- const auto &setupData = backend->setupData();
+ const auto& setupData = backend->setupData();
QStringList setupKeys;
QVariantMap setupDefaults;
for (int i = 0; i + 2 < setupData.size(); i += 3) {
setupKeys << setupData[i].toString();
setupDefaults[setupData[i].toString()] = setupData[i + 2];
}
- v["SetupKeys"] = setupKeys;
+ v["SetupKeys"] = setupKeys;
v["SetupDefaults"] = setupDefaults;
// TODO Protocol Break: Remove
- v["IsDefault"] = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list
+ v["IsDefault"] = (backend->backendId() == "SQLite"); // newer clients will just use the first in the list
backendInfos << v;
}
return backendInfos;
}
-
QVariantList Core::authenticatorInfo()
{
instance()->registerAuthenticators();
QVariantList authInfos;
- for(auto &&backend : instance()->_registeredAuthenticators) {
+ for (auto&& backend : instance()->_registeredAuthenticators) {
QVariantMap v;
- v["BackendId"] = backend->backendId();
+ v["BackendId"] = backend->backendId();
v["DisplayName"] = backend->displayName();
v["Description"] = backend->description();
- v["SetupData"] = backend->setupData();
+ v["SetupData"] = backend->setupData();
authInfos << v;
}
return authInfos;
}
// migration / backend selection
-bool Core::selectBackend(const QString &backend)
+bool Core::selectBackend(const QString& backend)
{
// reregister all storage backends
registerStorageBackends();
auto storage = storageBackend(backend);
if (!storage) {
QStringList backends;
- std::transform(_registeredStorageBackends.begin(), _registeredStorageBackends.end(),
- std::back_inserter(backends), [](const DeferredSharedPtr<Storage>& backend) {
- return backend->displayName();
- });
+ std::transform(_registeredStorageBackends.begin(),
+ _registeredStorageBackends.end(),
+ std::back_inserter(backends),
+ [](const DeferredSharedPtr<Storage>& backend) { return backend->displayName(); });
quWarning() << qPrintable(tr("Unsupported storage backend: %1").arg(backend));
quWarning() << qPrintable(tr("Supported backends are:")) << qPrintable(backends.join(", "));
return false;
// TODO: I am not sure if this function is implemented correctly.
// There is currently no concept of migraiton between auth backends.
-bool Core::selectAuthenticator(const QString &backend)
+bool Core::selectAuthenticator(const QString& backend)
{
// Register all authentication backends.
registerAuthenticators();
auto auther = authenticator(backend);
if (!auther) {
QStringList authenticators;
- std::transform(_registeredAuthenticators.begin(), _registeredAuthenticators.end(),
- std::back_inserter(authenticators), [](const DeferredSharedPtr<Authenticator>& authenticator) {
- return authenticator->displayName();
- });
+ std::transform(_registeredAuthenticators.begin(),
+ _registeredAuthenticators.end(),
+ std::back_inserter(authenticators),
+ [](const DeferredSharedPtr<Authenticator>& authenticator) { return authenticator->displayName(); });
quWarning() << qPrintable(tr("Unsupported authenticator: %1").arg(backend));
quWarning() << qPrintable(tr("Supported authenticators are:")) << qPrintable(authenticators.join(", "));
return false;
return true;
}
-
bool Core::createUser()
{
QTextStream out(stdout);
}
}
-
-bool Core::changeUserPass(const QString &username)
+bool Core::changeUserPass(const QString& username)
{
QTextStream out(stdout);
QTextStream in(stdin);
}
}
-
-bool Core::changeUserPassword(UserId userId, const QString &password)
+bool Core::changeUserPassword(UserId userId, const QString& password)
{
if (!isConfigured() || !userId.isValid())
return false;
return true;
}
-
-std::unique_ptr<AbstractSqlMigrationReader> Core::getMigrationReader(Storage *storage)
+std::unique_ptr<AbstractSqlMigrationReader> Core::getMigrationReader(Storage* storage)
{
if (!storage)
return nullptr;
- auto *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
+ auto* sqlStorage = qobject_cast<AbstractSqlStorage*>(storage);
if (!sqlStorage) {
qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
return nullptr;
return sqlStorage->createMigrationReader();
}
-
-std::unique_ptr<AbstractSqlMigrationWriter> Core::getMigrationWriter(Storage *storage)
+std::unique_ptr<AbstractSqlMigrationWriter> Core::getMigrationWriter(Storage* storage)
{
if (!storage)
return nullptr;
- auto *sqlStorage = qobject_cast<AbstractSqlStorage *>(storage);
+ auto* sqlStorage = qobject_cast<AbstractSqlStorage*>(storage);
if (!sqlStorage) {
qDebug() << "Core::migrateDb(): only SQL based backends can be migrated!";
return nullptr;
return sqlStorage->createMigrationWriter();
}
-
-bool Core::saveBackendSettings(const QString &backend, const QVariantMap &settings)
+bool Core::saveBackendSettings(const QString& backend, const QVariantMap& settings)
{
QVariantMap dbsettings;
dbsettings["Backend"] = backend;
return s.sync();
}
-
-void Core::saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings)
+void Core::saveAuthenticatorSettings(const QString& backend, const QVariantMap& settings)
{
QVariantMap dbsettings;
dbsettings["Authenticator"] = backend;
// Generic version of promptForSettings that doesn't care what *type* of
// backend it runs over.
template<typename Backend>
-QVariantMap Core::promptForSettings(const Backend *backend)
+QVariantMap Core::promptForSettings(const Backend* backend)
{
QVariantMap settings;
const QVariantList& setupData = backend->setupData();
for (int i = 0; i + 2 < setupData.size(); i += 3) {
QString key = setupData[i].toString();
- out << setupData[i+1].toString() << " [" << setupData[i+2].toString() << "]: " << flush;
+ out << setupData[i + 1].toString() << " [" << setupData[i + 2].toString() << "]: " << flush;
bool noEcho = key.toLower().contains("password");
if (noEcho) {
enableStdInEcho();
}
- QVariant value{setupData[i+2]};
+ QVariant value{setupData[i + 2]};
if (!input.isEmpty()) {
switch (value.type()) {
case QVariant::Int:
return settings;
}
-
#ifdef Q_OS_WIN
void Core::stdInEcho(bool on)
{
#include <QDateTime>
#include <QPointer>
#include <QString>
-#include <QVariant>
#include <QTimer>
+#include <QVariant>
#ifdef HAVE_SSL
-# include <QSslSocket>
-# include "sslserver.h"
+# include <QSslSocket>
+
+# include "sslserver.h"
#else
-# include <QTcpSocket>
-# include <QTcpServer>
+# include <QTcpServer>
+# include <QTcpSocket>
#endif
#include "authenticator.h"
*/
void shutdown();
-
/*** Storage access ***/
// These methods are threadsafe.
* \param password The user's uncrypted password
* \return The user's ID if valid; 0 otherwise
*/
- static inline UserId validateUser(const QString &userName, const QString &password) {
+ static inline UserId validateUser(const QString& userName, const QString& password)
+ {
return instance()->_storage->validateUser(userName, password);
}
* \param password The user's uncrypted password
* \return The user's ID if valid; 0 otherwise
*/
- static inline UserId authenticateUser(const QString &userName, const QString &password) {
+ static inline UserId authenticateUser(const QString& userName, const QString& password)
+ {
return instance()->_authenticator->validateUser(userName, password);
}
* \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
* \return The user's ID if valid; 0 otherwise
*/
- static inline UserId addUser(const QString &userName, const QString &password, const QString &authenticator = "Database") {
+ static inline UserId addUser(const QString& userName, const QString& password, const QString& authenticator = "Database")
+ {
return instance()->_storage->addUser(userName, password, authenticator);
}
* \param authenticator The name of the auth provider service used to log the user in, defaults to "Database".
* \return True if the userid was configured with the passed authenticator, false otherwise.
*/
- static inline bool checkAuthProvider(const UserId userid, const QString &authenticator) {
+ static inline bool checkAuthProvider(const UserId userid, const QString& authenticator)
+ {
return instance()->_storage->getUserAuthenticator(userid) == authenticator;
}
* \param password The user's unencrypted new password
* \return true, if the password change was successful
*/
- static bool changeUserPassword(UserId userId, const QString &password);
+ static bool changeUserPassword(UserId userId, const QString& password);
//! Check if we can change a user password.
/**
* \param settingName The Name of the Setting
* \param data The Value
*/
- static inline void setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
+ static inline void setUserSetting(UserId userId, const QString& settingName, const QVariant& data)
{
instance()->_storage->setUserSetting(userId, settingName, data);
}
-
//! Retrieve a persistent user setting
/**
* \param userId The users Id
* \param defaultValue Value to return in case it's unset.
* \return the Value of the Setting or the default value if it is unset.
*/
- static inline QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultValue = QVariant())
+ static inline QVariant getUserSetting(UserId userId, const QString& settingName, const QVariant& defaultValue = QVariant())
{
return instance()->_storage->getUserSetting(userId, settingName, defaultValue);
}
-
/* Identity handling */
- static inline IdentityId createIdentity(UserId user, CoreIdentity &identity)
+ static inline IdentityId createIdentity(UserId user, CoreIdentity& identity)
{
return instance()->_storage->createIdentity(user, identity);
}
+ static bool updateIdentity(UserId user, const CoreIdentity& identity) { return instance()->_storage->updateIdentity(user, identity); }
- static bool updateIdentity(UserId user, const CoreIdentity &identity)
- {
- return instance()->_storage->updateIdentity(user, identity);
- }
-
-
- static void removeIdentity(UserId user, IdentityId identityId)
- {
- instance()->_storage->removeIdentity(user, identityId);
- }
-
-
- static QList<CoreIdentity> identities(UserId user)
- {
- return instance()->_storage->identities(user);
- }
+ static void removeIdentity(UserId user, IdentityId identityId) { instance()->_storage->removeIdentity(user, identityId); }
+ static QList<CoreIdentity> identities(UserId user) { return instance()->_storage->identities(user); }
//! Create a Network in the Storage and store it's Id in the given NetworkInfo
/** \note This method is thredsafe.
* \param networkInfo a NetworkInfo definition to store the newly created ID in
* \return true if successfull.
*/
- static bool createNetwork(UserId user, NetworkInfo &info);
+ static bool createNetwork(UserId user, NetworkInfo& info);
//! Apply the changes to NetworkInfo info to the storage engine
/** \note This method is thredsafe.
* \param networkInfo The Updated NetworkInfo
* \return true if successfull.
*/
- static inline bool updateNetwork(UserId user, const NetworkInfo &info)
- {
- return instance()->_storage->updateNetwork(user, info);
- }
-
+ static inline bool updateNetwork(UserId user, const NetworkInfo& info) { return instance()->_storage->updateNetwork(user, info); }
//! Permanently remove a Network and all the data associated with it.
/** \note This method is thredsafe.
* \param networkId The network to delete
* \return true if successfull.
*/
- static inline bool removeNetwork(UserId user, const NetworkId &networkId)
+ static inline bool removeNetwork(UserId user, const NetworkId& networkId)
{
return instance()->_storage->removeNetwork(user, networkId);
}
-
//! Returns a list of all NetworkInfos for the given UserId user
/** \note This method is thredsafe.
*
* \param user The core user
* \return QList<NetworkInfo>.
*/
- static inline QList<NetworkInfo> networks(UserId user)
- {
- return instance()->_storage->networks(user);
- }
-
+ static inline QList<NetworkInfo> networks(UserId user) { return instance()->_storage->networks(user); }
//! Get a list of Networks to restore
/** Return a list of networks the user was connected at the time of core shutdown
*
* \param user The User Id in question
*/
- static inline QList<NetworkId> connectedNetworks(UserId user)
- {
- return instance()->_storage->connectedNetworks(user);
- }
-
+ static inline QList<NetworkId> connectedNetworks(UserId user) { return instance()->_storage->connectedNetworks(user); }
//! Update the connected state of a network
/** \note This method is threadsafe
* \param networkId The Id of the network
* \param isConnected whether the network is connected or not
*/
- static inline void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
+ static inline void setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected)
{
return instance()->_storage->setNetworkConnected(user, networkId, isConnected);
}
-
//! Get a hash of channels with their channel keys for a given network
/** The keys are channel names and values are passwords (possibly empty)
* \note This method is threadsafe
* \param user The id of the networks owner
* \param networkId The Id of the network
*/
- static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId)
+ static inline QHash<QString, QString> persistentChannels(UserId user, const NetworkId& networkId)
{
return instance()->_storage->persistentChannels(user, networkId);
}
-
//! Update the connected state of a channel
/** \note This method is threadsafe
*
* \param channel The name of the channel
* \param isJoined whether the channel is connected or not
*/
- static inline void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
+ static inline void setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined)
{
return instance()->_storage->setChannelPersistent(user, networkId, channel, isJoined);
}
-
//! Get a hash of buffers with their ciphers for a given network
/** The keys are channel names and values are ciphers (possibly empty)
* \note This method is threadsafe
* \param user The id of the networks owner
* \param networkId The Id of the network
*/
- static inline QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId &networkId)
+ static inline QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId& networkId)
{
return instance()->_storage->bufferCiphers(user, networkId);
}
-
//! Update the cipher of a buffer
/** \note This method is threadsafe
*
* \param bufferName The Cname of the buffer
* \param cipher The cipher for the buffer
*/
- static inline void setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher)
+ static inline void setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher)
{
return instance()->_storage->setBufferCipher(user, networkId, bufferName, cipher);
}
-
//! Update the key of a channel
/** \note This method is threadsafe
*
* \param channel The name of the channel
* \param key The key of the channel (possibly empty)
*/
- static inline void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
+ static inline void setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key)
{
return instance()->_storage->setPersistentChannelKey(user, networkId, channel, key);
}
-
//! retrieve last known away message for session restore
/** \note This method is threadsafe
*
* \param user The Id of the networks owner
* \param networkId The Id of the network
*/
- static inline QString awayMessage(UserId user, NetworkId networkId)
- {
- return instance()->_storage->awayMessage(user, networkId);
- }
-
+ static inline QString awayMessage(UserId user, NetworkId networkId) { return instance()->_storage->awayMessage(user, networkId); }
//! Make away message persistent for session restore
/** \note This method is threadsafe
* \param networkId The Id of the network
* \param awayMsg The current away message of own user
*/
- static inline void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
+ static inline void setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg)
{
return instance()->_storage->setAwayMessage(user, networkId, awayMsg);
}
-
//! retrieve last known user mode for session restore
/** \note This method is threadsafe
*
* \param user The Id of the networks owner
* \param networkId The Id of the network
*/
- static inline QString userModes(UserId user, NetworkId networkId)
- {
- return instance()->_storage->userModes(user, networkId);
- }
-
+ static inline QString userModes(UserId user, NetworkId networkId) { return instance()->_storage->userModes(user, networkId); }
//! Make our user modes persistent for session restore
/** \note This method is threadsafe
* \param networkId The Id of the network
* \param userModes The current user modes of own user
*/
- static inline void setUserModes(UserId user, NetworkId networkId, const QString &userModes)
+ static inline void setUserModes(UserId user, NetworkId networkId, const QString& userModes)
{
return instance()->_storage->setUserModes(user, networkId, userModes);
}
-
//! Get the unique BufferInfo for the given combination of network and buffername for a user.
/** \note This method is threadsafe.
*
* \param create Whether or not the buffer should be created if it doesnt exist
* \return The BufferInfo corresponding to the given network and buffer name, or 0 if not found
*/
- static inline BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true)
+ static inline BufferInfo bufferInfo(
+ UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer = "", bool create = true)
{
return instance()->_storage->bufferInfo(user, networkId, type, buffer, create);
}
-
//! Get the unique BufferInfo for a bufferId
/** \note This method is threadsafe
* \param user The core user who owns this buffername
* \param bufferId The id of the buffer
* \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
*/
- static inline BufferInfo getBufferInfo(UserId user, const BufferId &bufferId)
+ static inline BufferInfo getBufferInfo(UserId user, const BufferId& bufferId)
{
return instance()->_storage->getBufferInfo(user, bufferId);
}
-
//! Store a Message in the storage backend and set it's unique Id.
/** \note This method is threadsafe.
*
* \param message The message object to be stored
* \return true on success
*/
- static inline bool storeMessage(Message &message)
- {
- return instance()->_storage->logMessage(message);
- }
-
+ static inline bool storeMessage(Message& message) { return instance()->_storage->logMessage(message); }
//! Store a list of Messages in the storage backend and set their unique Id.
/** \note This method is threadsafe.
* \param messages The list message objects to be stored
* \return true on success
*/
- static inline bool storeMessages(MessageList &messages)
- {
- return instance()->_storage->logMessages(messages);
- }
-
+ static inline bool storeMessages(MessageList& messages) { return instance()->_storage->logMessages(messages); }
//! Request a certain number messages stored in a given buffer.
/** \param buffer The buffer we request messages from
return instance()->_storage->requestMsgs(user, bufferId, first, last, limit);
}
-
//! Request a certain number messages stored in a given buffer, matching certain filters
/** \param buffer The buffer we request messages from
* \param first if != -1 return only messages with a MsgId >= first
* \param type The Message::Types that should be returned
* \return The requested list of messages
*/
- static inline QList<Message> requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1,
- int limit = -1, Message::Types type = Message::Types{-1},
+ static inline QList<Message> requestMsgsFiltered(UserId user,
+ BufferId bufferId,
+ MsgId first = -1,
+ MsgId last = -1,
+ int limit = -1,
+ Message::Types type = Message::Types{-1},
Message::Flags flags = Message::Flags{-1})
{
return instance()->_storage->requestMsgsFiltered(user, bufferId, first, last, limit, type, flags);
}
-
//! Request a certain number of messages across all buffers
/** \param first if != -1 return only messages with a MsgId >= first
* \param last if != -1 return only messages with a MsgId < last
return instance()->_storage->requestAllMsgs(user, first, last, limit);
}
-
//! Request a certain number of messages across all buffers, matching certain filters
/** \param first if != -1 return only messages with a MsgId >= first
* \param last if != -1 return only messages with a MsgId < last
* \param type The Message::Types that should be returned
* \return The requested list of messages
*/
- static inline QList<Message> requestAllMsgsFiltered(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1,
+ static inline QList<Message> requestAllMsgsFiltered(UserId user,
+ MsgId first = -1,
+ MsgId last = -1,
+ int limit = -1,
Message::Types type = Message::Types{-1},
Message::Flags flags = Message::Flags{-1})
{
return instance()->_storage->requestAllMsgsFiltered(user, first, last, limit, type, flags);
}
-
//! Request a list of all buffers known to a user.
/** This method is used to get a list of all buffers we have stored a backlog from.
* \note This method is threadsafe.
* \param user The user whose buffers we request
* \return A list of the BufferInfos for all buffers as requested
*/
- static inline QList<BufferInfo> requestBuffers(UserId user)
- {
- return instance()->_storage->requestBuffers(user);
- }
-
+ static inline QList<BufferInfo> requestBuffers(UserId user) { return instance()->_storage->requestBuffers(user); }
//! Request a list of BufferIds for a given NetworkId
/** \note This method is threadsafe.
return instance()->_storage->requestBufferIdsForNetwork(user, networkId);
}
-
//! Remove permanently a buffer and it's content from the storage backend
/** This call cannot be reverted!
* \note This method is threadsafe.
* \param bufferId The bufferId
* \return true if successfull
*/
- static inline bool removeBuffer(const UserId &user, const BufferId &bufferId)
+ static inline bool removeBuffer(const UserId& user, const BufferId& bufferId)
{
return instance()->_storage->removeBuffer(user, bufferId);
}
-
//! Rename a Buffer
/** \note This method is threadsafe.
* \param user The id of the buffer owner
* \param newName The new name of the buffer
* \return true if successfull
*/
- static inline bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
+ static inline bool renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName)
{
return instance()->_storage->renameBuffer(user, bufferId, newName);
}
-
//! Merge the content of two Buffers permanently. This cannot be reversed!
/** \note This method is threadsafe.
* \param user The id of the buffer owner
* \param bufferId2 The buffer that is about to be removed
* \return true if successfulln
*/
- static inline bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
+ static inline bool mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2)
{
return instance()->_storage->mergeBuffersPermanently(user, bufferId1, bufferId2);
}
-
//! Update the LastSeenDate for a Buffer
/** This Method is used to make the LastSeenDate of a Buffer persistent
* \note This method is threadsafe.
* \param bufferId The buffer id
* \param MsgId The Message id of the message that has been just seen
*/
- static inline void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
+ static inline void setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId)
{
return instance()->_storage->setBufferLastSeenMsg(user, bufferId, msgId);
}
-
//! Get a usable sysident for the given user in oidentd-strict mode
/** \param user The user to retrieve the sysident for
* \return The authusername
*/
QString strictSysIdent(UserId user) const;
-
//! Get a Hash of all last seen message ids
/** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds
* \note This method is threadsafe.
*
* \param user The Owner of the buffers
*/
- static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user)
- {
- return instance()->_storage->bufferLastSeenMsgIds(user);
- }
-
+ static inline QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user) { return instance()->_storage->bufferLastSeenMsgIds(user); }
//! Update the MarkerLineMsgId for a Buffer
/** This Method is used to make the marker line position of a Buffer persistent
* \param bufferId The buffer id
* \param MsgId The Message id where the marker line should be placed
*/
- static inline void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
+ static inline void setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId)
{
return instance()->_storage->setBufferMarkerLineMsg(user, bufferId, msgId);
}
-
//! Get a Hash of all marker line message ids
/** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds
* \note This method is threadsafe.
*
* \param user The Owner of the buffers
*/
- static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user)
- {
- return instance()->_storage->bufferMarkerLineMsgIds(user);
- }
+ static inline QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user) { return instance()->_storage->bufferMarkerLineMsgIds(user); }
//! Update the BufferActivity for a Buffer
/** This Method is used to make the activity state of a Buffer persistent
* \param bufferId The buffer id
* \param MsgId The Message id where the marker line should be placed
*/
- static inline void setBufferActivity(UserId user, BufferId bufferId, Message::Types activity) {
+ static inline void setBufferActivity(UserId user, BufferId bufferId, Message::Types activity)
+ {
return instance()->_storage->setBufferActivity(user, bufferId, activity);
}
-
//! Get a Hash of all buffer activity states
/** This Method is called when the Quassel Core is started to restore the BufferActivity
* \note This method is threadsafe.
*
* \param user The Owner of the buffers
*/
- static inline QHash<BufferId, Message::Types> bufferActivities(UserId user) {
- return instance()->_storage->bufferActivities(user);
- }
+ static inline QHash<BufferId, Message::Types> bufferActivities(UserId user) { return instance()->_storage->bufferActivities(user); }
//! Get the bitset of buffer activity states for a buffer
/** This method is used to load the activity state of a buffer when its last seen message changes.
* \param bufferId The buffer
* \param lastSeenMsgId The last seen message
*/
- static inline Message::Types bufferActivity(BufferId bufferId, MsgId lastSeenMsgId) {
+ static inline Message::Types bufferActivity(BufferId bufferId, MsgId lastSeenMsgId)
+ {
return instance()->_storage->bufferActivity(bufferId, lastSeenMsgId);
}
* \param bufferId The buffer id
* \param MsgId The Message id where the marker line should be placed
*/
- static inline void setHighlightCount(UserId user, BufferId bufferId, int highlightCount) {
+ static inline void setHighlightCount(UserId user, BufferId bufferId, int highlightCount)
+ {
return instance()->_storage->setHighlightCount(user, bufferId, highlightCount);
}
-
//! Get a Hash of all highlight count states
/** This Method is called when the Quassel Core is started to restore the highlight count
* \note This method is threadsafe.
*
* \param user The Owner of the buffers
*/
- static inline QHash<BufferId, int> highlightCounts(UserId user) {
- return instance()->_storage->highlightCounts(user);
- }
+ static inline QHash<BufferId, int> highlightCounts(UserId user) { return instance()->_storage->highlightCounts(user); }
//! Get the highlight count states for a buffer
/** This method is used to load the highlight count of a buffer when its last seen message changes.
* \note This method is threadsafe.
* \param bufferId The buffer
* \param lastSeenMsgId The last seen message
*/
- static inline int highlightCount(BufferId bufferId, MsgId lastSeenMsgId) {
+ static inline int highlightCount(BufferId bufferId, MsgId lastSeenMsgId)
+ {
return instance()->_storage->highlightCount(bufferId, lastSeenMsgId);
}
static QVariantList backendInfo();
static QVariantList authenticatorInfo();
- static QString setup(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
+ static QString setup(const QString& adminUser,
+ const QString& adminPassword,
+ const QString& backend,
+ const QVariantMap& setupData,
+ const QString& authenticator,
+ const QVariantMap& authSetupMap);
- static inline QTimer *syncTimer() { return &instance()->_storageSyncTimer; }
+ static inline QTimer* syncTimer() { return &instance()->_storageSyncTimer; }
- inline OidentdConfigGenerator *oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
- inline IdentServer *identServer() const { return _identServer; }
+ inline OidentdConfigGenerator* oidentdConfigGenerator() const { return _oidentdConfigGenerator; }
+ inline IdentServer* identServer() const { return _identServer; }
static const int AddClientEventId;
signals:
//! Sent when a BufferInfo is updated in storage.
- void bufferInfoUpdated(UserId user, const BufferInfo &info);
+ void bufferInfoUpdated(UserId user, const BufferInfo& info);
//! Relay from CoreSession::sessionState(). Used for internal connection only
- void sessionStateReceived(const Protocol::SessionState &sessionState);
+ void sessionStateReceived(const Protocol::SessionState& sessionState);
//! Emitted when database schema upgrade starts or ends
void dbUpgradeInProgress(bool inProgress);
//! Emitted when a fatal error was encountered during async initialization
- void exitRequested(int exitCode, const QString &reason);
+ void exitRequested(int exitCode, const QString& reason);
//! Emitted once core shutdown is complete
void shutdownComplete();
void cacheSysIdent();
- QString setupCore(const QString &adminUser, const QString &adminPassword, const QString &backend, const QVariantMap &setupData, const QString &authenticator, const QVariantMap &authSetupMap);
+ QString setupCore(const QString& adminUser,
+ const QString& adminPassword,
+ const QString& backend,
+ const QVariantMap& setupData,
+ const QString& authenticator,
+ const QVariantMap& authSetupMap);
void connectInternalPeer(QPointer<InternalPeer> peer);
protected:
- void customEvent(QEvent *event) override;
+ void customEvent(QEvent* event) override;
private slots:
bool startListening();
- void stopListening(const QString &msg = QString());
+ void stopListening(const QString& msg = QString());
void incomingConnection();
void clientDisconnected();
- bool initStorage(const QString &backend, const QVariantMap &settings,
- const QProcessEnvironment &environment, bool loadFromEnvironment,
+ bool initStorage(const QString& backend,
+ const QVariantMap& settings,
+ const QProcessEnvironment& environment,
+ bool loadFromEnvironment,
bool setup = false);
- bool initAuthenticator(const QString &backend, const QVariantMap &settings,
- const QProcessEnvironment &environment, bool loadFromEnvironment,
+ bool initAuthenticator(const QString& backend,
+ const QVariantMap& settings,
+ const QProcessEnvironment& environment,
+ bool loadFromEnvironment,
bool setup = false);
- void socketError(QAbstractSocket::SocketError err, const QString &errorString);
- void setupClientSession(RemotePeer *, UserId);
+ void socketError(QAbstractSocket::SocketError err, const QString& errorString);
+ void setupClientSession(RemotePeer*, UserId);
- bool changeUserPass(const QString &username);
+ bool changeUserPass(const QString& username);
- void onSessionShutdown(SessionThread *session);
+ void onSessionShutdown(SessionThread* session);
private:
- SessionThread *sessionForUser(UserId userId, bool restoreState = false);
- void addClientHelper(RemotePeer *peer, UserId uid);
- //void processCoreSetup(QTcpSocket *socket, QVariantMap &msg);
+ SessionThread* sessionForUser(UserId userId, bool restoreState = false);
+ void addClientHelper(RemotePeer* peer, UserId uid);
+ // void processCoreSetup(QTcpSocket *socket, QVariantMap &msg);
QString setupCoreForInternalUsage();
void setupInternalClientSession(QPointer<InternalPeer> peer);
void registerStorageBackends();
void registerAuthenticators();
- DeferredSharedPtr<Storage> storageBackend(const QString& backendId) const;
+ DeferredSharedPtr<Storage> storageBackend(const QString& backendId) const;
DeferredSharedPtr<Authenticator> authenticator(const QString& authenticatorId) const;
- bool selectBackend(const QString &backend);
- bool selectAuthenticator(const QString &backend);
+ bool selectBackend(const QString& backend);
+ bool selectAuthenticator(const QString& backend);
- bool saveBackendSettings(const QString &backend, const QVariantMap &settings);
- void saveAuthenticatorSettings(const QString &backend, const QVariantMap &settings);
+ bool saveBackendSettings(const QString& backend, const QVariantMap& settings);
+ void saveAuthenticatorSettings(const QString& backend, const QVariantMap& settings);
void saveState();
void restoreState();
template<typename Backend>
- QVariantMap promptForSettings(const Backend *backend);
+ QVariantMap promptForSettings(const Backend* backend);
private:
- static Core *_instance;
- QSet<CoreAuthHandler *> _connectingClients;
- QHash<UserId, SessionThread *> _sessions;
- DeferredSharedPtr<Storage> _storage; ///< Active storage backend
+ static Core* _instance;
+ QSet<CoreAuthHandler*> _connectingClients;
+ QHash<UserId, SessionThread*> _sessions;
+ DeferredSharedPtr<Storage> _storage; ///< Active storage backend
DeferredSharedPtr<Authenticator> _authenticator; ///< Active authenticator
QMap<UserId, QString> _authUserNames;
QTcpServer _server, _v6server;
#endif
- OidentdConfigGenerator *_oidentdConfigGenerator {nullptr};
+ OidentdConfigGenerator* _oidentdConfigGenerator{nullptr};
- std::vector<DeferredSharedPtr<Storage>> _registeredStorageBackends;
+ std::vector<DeferredSharedPtr<Storage>> _registeredStorageBackends;
std::vector<DeferredSharedPtr<Authenticator>> _registeredAuthenticators;
QDateTime _startTime;
- IdentServer *_identServer {nullptr};
+ IdentServer* _identServer{nullptr};
bool _initialized{false};
bool _configured{false};
/// Whether or not strict ident mode is enabled, locking users' idents to Quassel username
bool _strictIdentEnabled;
- static std::unique_ptr<AbstractSqlMigrationReader> getMigrationReader(Storage *storage);
- static std::unique_ptr<AbstractSqlMigrationWriter> getMigrationWriter(Storage *storage);
+ static std::unique_ptr<AbstractSqlMigrationReader> getMigrationReader(Storage* storage);
+ static std::unique_ptr<AbstractSqlMigrationWriter> getMigrationWriter(Storage* storage);
static void stdInEcho(bool on);
static inline void enableStdInEcho() { stdInEcho(true); }
static inline void disableStdInEcho() { stdInEcho(false); }
#include "corenetwork.h"
#include "coresession.h"
-CoreAliasManager::CoreAliasManager(CoreSession *parent)
+CoreAliasManager::CoreAliasManager(CoreSession* parent)
: AliasManager(parent)
{
- auto *session = qobject_cast<CoreSession *>(parent);
+ auto* session = qobject_cast<CoreSession*>(parent);
if (!session) {
qWarning() << "CoreAliasManager: unable to load Aliases. Parent is not a Coresession!";
loadDefaults();
connect(this, &SyncableObject::updatedRemotely, this, &CoreAliasManager::save);
}
-
void CoreAliasManager::save() const
{
- auto *session = qobject_cast<CoreSession *>(parent());
+ auto* session = qobject_cast<CoreSession*>(parent());
if (!session) {
qWarning() << "CoreAliasManager: unable to save Aliases. Parent is not a Coresession!";
return;
Core::setUserSetting(session->user(), "Aliases", initAliases());
}
-
-const Network *CoreAliasManager::network(NetworkId id) const
+const Network* CoreAliasManager::network(NetworkId id) const
{
- return qobject_cast<CoreSession *>(parent())->network(id);
+ return qobject_cast<CoreSession*>(parent())->network(id);
}
-
void CoreAliasManager::loadDefaults()
{
- foreach(Alias alias, AliasManager::defaults()) {
+ foreach (Alias alias, AliasManager::defaults()) {
addAlias(alias.name, alias.expansion);
}
}
Q_OBJECT
public:
- explicit CoreAliasManager(CoreSession *parent);
+ explicit CoreAliasManager(CoreSession* parent);
protected:
- const Network *network(NetworkId) const override;
+ const Network* network(NetworkId) const override;
private slots:
void save() const;
#include "coreapplication.h"
-CoreApplication::CoreApplication(int &argc, char **argv)
+CoreApplication::CoreApplication(int& argc, char** argv)
: QCoreApplication(argc, argv)
{
Quassel::registerQuitHandler([this]() {
});
}
-
void CoreApplication::init()
{
_core = std::make_unique<Core>();
_core->init();
}
-
void CoreApplication::onShutdownComplete()
{
connect(_core.get(), &QObject::destroyed, QCoreApplication::instance(), &QCoreApplication::quit);
Q_OBJECT
public:
- CoreApplication(int &argc, char **argv);
+ CoreApplication(int& argc, char** argv);
void init();
#include "coreauthhandler.h"
#ifdef HAVE_SSL
-# include <QSslSocket>
+# include <QSslSocket>
#endif
#include "core.h"
using namespace Protocol;
-CoreAuthHandler::CoreAuthHandler(QTcpSocket *socket, QObject *parent)
- : AuthHandler(parent),
- _peer(nullptr),
- _magicReceived(false),
- _legacy(false),
- _clientRegistered(false),
- _connectionFeatures(0)
+CoreAuthHandler::CoreAuthHandler(QTcpSocket* socket, QObject* parent)
+ : AuthHandler(parent)
+ , _peer(nullptr)
+ , _magicReceived(false)
+ , _legacy(false)
+ , _clientRegistered(false)
+ , _connectionFeatures(0)
{
setSocket(socket);
connect(socket, &QIODevice::readyRead, this, &CoreAuthHandler::onReadyRead);
// TODO: Timeout for the handshake phase
-
}
-
void CoreAuthHandler::onReadyRead()
{
if (socket()->bytesAvailable() < 4)
// no magic, assume legacy protocol
qDebug() << "Legacy client detected, switching to compatibility mode";
_legacy = true;
- RemotePeer *peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0), this, socket(), Compressor::NoCompression, this);
+ RemotePeer* peer = PeerFactory::createPeer(PeerFactory::ProtoDescriptor(Protocol::LegacyProtocol, 0),
+ this,
+ socket(),
+ Compressor::NoCompression,
+ this);
connect(peer, &RemotePeer::protocolVersionMismatch, this, &CoreAuthHandler::onProtocolVersionMismatch);
setPeer(peer);
return;
if (features & Protocol::Compression)
_connectionFeatures |= Protocol::Compression;
- socket()->read((char*)&magic, 4); // read the 4 bytes we've just peeked at
+ socket()->read((char*)&magic, 4); // read the 4 bytes we've just peeked at
}
// read the list of protocols supported by the client
- while (socket()->bytesAvailable() >= 4 && _supportedProtos.size() < 16) { // sanity check
+ while (socket()->bytesAvailable() >= 4 && _supportedProtos.size() < 16) { // sanity check
quint32 data;
socket()->read((char*)&data, 4);
data = qFromBigEndian<quint32>(data);
auto type = static_cast<Protocol::Type>(data & 0xff);
- auto protoFeatures = static_cast<quint16>(data>>8 & 0xffff);
+ auto protoFeatures = static_cast<quint16>(data >> 8 & 0xffff);
_supportedProtos.append(PeerFactory::ProtoDescriptor(type, protoFeatures));
- if (data >= 0x80000000) { // last protocol
+ if (data >= 0x80000000) { // last protocol
Compressor::CompressionLevel level;
if (_connectionFeatures & Protocol::Compression)
level = Compressor::BestCompression;
else
level = Compressor::NoCompression;
- RemotePeer *peer = PeerFactory::createPeer(_supportedProtos, this, socket(), level, this);
+ RemotePeer* peer = PeerFactory::createPeer(_supportedProtos, this, socket(), level, this);
if (!peer) {
qWarning() << "Received invalid handshake data from client" << socket()->peerAddress().toString();
close();
setPeer(peer);
// inform the client
- quint32 reply = peer->protocol() | peer->enabledFeatures()<<8 | _connectionFeatures<<24;
+ quint32 reply = peer->protocol() | peer->enabledFeatures() << 8 | _connectionFeatures << 24;
reply = qToBigEndian<quint32>(reply);
socket()->write((char*)&reply, 4);
socket()->flush();
if (!_legacy && (_connectionFeatures & Protocol::Encryption))
- startSsl(); // legacy peer enables it later
+ startSsl(); // legacy peer enables it later
return;
}
}
}
-
-void CoreAuthHandler::setPeer(RemotePeer *peer)
+void CoreAuthHandler::setPeer(RemotePeer* peer)
{
qDebug().nospace() << "Using " << qPrintable(peer->protocolName()) << "...";
qWarning() << qPrintable(tr("Client")) << _peer->description() << qPrintable(tr("too old, rejecting."));
QString errorString = tr("<b>Your Quassel Client is too old!</b><br>"
"This core needs at least client/core protocol version %1 (got: %2).<br>"
- "Please consider upgrading your client.").arg(expected, actual);
+ "Please consider upgrading your client.")
+ .arg(expected, actual);
_peer->dispatch(ClientDenied(errorString));
_peer->close();
}
-
bool CoreAuthHandler::checkClientRegistered()
{
if (!_clientRegistered) {
- qWarning() << qPrintable(tr("Client")) << qPrintable(socket()->peerAddress().toString()) << qPrintable(tr("did not send a registration message before trying to login, rejecting."));
- _peer->dispatch(ClientDenied(tr("<b>Client not initialized!</b><br>You need to send a registration message before trying to login.")));
+ qWarning() << qPrintable(tr("Client")) << qPrintable(socket()->peerAddress().toString())
+ << qPrintable(tr("did not send a registration message before trying to login, rejecting."));
+ _peer->dispatch(
+ ClientDenied(tr("<b>Client not initialized!</b><br>You need to send a registration message before trying to login.")));
_peer->close();
return false;
}
return true;
}
-
-void CoreAuthHandler::handle(const RegisterClient &msg)
+void CoreAuthHandler::handle(const RegisterClient& msg)
{
bool useSsl;
if (_legacy)
_clientRegistered = true;
}
-
-void CoreAuthHandler::handle(const SetupData &msg)
+void CoreAuthHandler::handle(const SetupData& msg)
{
if (!checkClientRegistered())
return;
_peer->dispatch(SetupDone());
}
-
-void CoreAuthHandler::handle(const Login &msg)
+void CoreAuthHandler::handle(const Login& msg)
{
if (!checkClientRegistered())
return;
if (!Core::isConfigured()) {
- qWarning() << qPrintable(tr("Client")) << qPrintable(socket()->peerAddress().toString()) << qPrintable(tr("attempted to login before the core was configured, rejecting."));
- _peer->dispatch(ClientDenied(tr("<b>Attempted to login before core was configured!</b><br>The core must be configured before attempting to login.")));
+ qWarning() << qPrintable(tr("Client")) << qPrintable(socket()->peerAddress().toString())
+ << qPrintable(tr("attempted to login before the core was configured, rejecting."));
+ _peer->dispatch(ClientDenied(
+ tr("<b>Attempted to login before core was configured!</b><br>The core must be configured before attempting to login.")));
return;
}
if (uid == 0) {
quInfo() << qPrintable(tr("Invalid login attempt from %1 as \"%2\"").arg(socket()->peerAddress().toString(), msg.user));
- _peer->dispatch(LoginFailed(tr("<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.")));
+ _peer->dispatch(LoginFailed(tr(
+ "<b>Invalid username or password!</b><br>The username/password combination you supplied could not be found in the database.")));
return;
}
_peer->dispatch(LoginSuccess());
- quInfo() << qPrintable(tr("Client %1 initialized and authenticated successfully as \"%2\" (UserId: %3).").arg(socket()->peerAddress().toString(), msg.user, QString::number(uid.toInt())));
+ quInfo() << qPrintable(tr("Client %1 initialized and authenticated successfully as \"%2\" (UserId: %3).")
+ .arg(socket()->peerAddress().toString(), msg.user, QString::number(uid.toInt())));
- const auto &clientFeatures = _peer->features();
+ const auto& clientFeatures = _peer->features();
auto unsupported = clientFeatures.toStringList(false);
if (!unsupported.isEmpty()) {
if (unsupported.contains("NoFeatures"))
disconnect(socket(), nullptr, this, nullptr);
disconnect(_peer, nullptr, this, nullptr);
- _peer->setParent(nullptr); // Core needs to take care of this one now!
+ _peer->setParent(nullptr); // Core needs to take care of this one now!
- socket()->flush(); // Make sure all data is sent before handing over the peer (and socket) to the session thread (bug 682)
+ socket()->flush(); // Make sure all data is sent before handing over the peer (and socket) to the session thread (bug 682)
emit handshakeComplete(_peer, uid);
}
-
/*** SSL Stuff ***/
void CoreAuthHandler::startSsl()
{
- #ifdef HAVE_SSL
- auto *sslSocket = qobject_cast<QSslSocket *>(socket());
+#ifdef HAVE_SSL
+ auto* sslSocket = qobject_cast<QSslSocket*>(socket());
Q_ASSERT(sslSocket);
- qDebug() << qPrintable(tr("Starting encryption for Client:")) << _peer->description();
- connect(sslSocket, selectOverload<const QList<QSslError> &>(&QSslSocket::sslErrors), this, &CoreAuthHandler::onSslErrors);
- sslSocket->flush(); // ensure that the write cache is flushed before we switch to ssl (bug 682)
+ qDebug() << qPrintable(tr("Starting encryption for Client:")) << _peer->description();
+ connect(sslSocket, selectOverload<const QList<QSslError>&>(&QSslSocket::sslErrors), this, &CoreAuthHandler::onSslErrors);
+ sslSocket->flush(); // ensure that the write cache is flushed before we switch to ssl (bug 682)
sslSocket->startServerEncryption();
- #endif /* HAVE_SSL */
+#endif /* HAVE_SSL */
}
-
#ifdef HAVE_SSL
void CoreAuthHandler::onSslErrors()
{
- auto *sslSocket = qobject_cast<QSslSocket *>(socket());
+ auto* sslSocket = qobject_cast<QSslSocket*>(socket());
Q_ASSERT(sslSocket);
sslSocket->ignoreSslErrors();
}
#endif
-
Q_OBJECT
public:
- CoreAuthHandler(QTcpSocket *socket, QObject *parent = nullptr);
+ CoreAuthHandler(QTcpSocket* socket, QObject* parent = nullptr);
signals:
- void handshakeComplete(RemotePeer *peer, UserId uid);
+ void handshakeComplete(RemotePeer* peer, UserId uid);
private:
using AuthHandler::handle;
- void handle(const Protocol::RegisterClient &msg) override;
- void handle(const Protocol::SetupData &msg) override;
- void handle(const Protocol::Login &msg) override;
+ void handle(const Protocol::RegisterClient& msg) override;
+ void handle(const Protocol::SetupData& msg) override;
+ void handle(const Protocol::Login& msg) override;
- void setPeer(RemotePeer *peer);
+ void setPeer(RemotePeer* peer);
void startSsl();
bool checkClientRegistered();
void onProtocolVersionMismatch(int actual, int expected);
private:
- RemotePeer *_peer;
+ RemotePeer* _peer;
bool _magicReceived;
bool _legacy;
***************************************************************************/
#include "corebacklogmanager.h"
-#include "core.h"
-#include "coresession.h"
#include <QDebug>
-CoreBacklogManager::CoreBacklogManager(CoreSession *coreSession)
- : BacklogManager(coreSession),
- _coreSession(coreSession)
-{
-}
+#include "core.h"
+#include "coresession.h"
+CoreBacklogManager::CoreBacklogManager(CoreSession* coreSession)
+ : BacklogManager(coreSession)
+ , _coreSession(coreSession)
+{}
QVariantList CoreBacklogManager::requestBacklog(BufferId bufferId, MsgId first, MsgId last, int limit, int additional)
{
return backlog;
}
-
QVariantList CoreBacklogManager::requestBacklogFiltered(BufferId bufferId, MsgId first, MsgId last, int limit, int additional, int type, int flags)
{
QVariantList backlog;
return backlog;
}
-
QVariantList CoreBacklogManager::requestBacklogAll(MsgId first, MsgId last, int limit, int additional)
{
QVariantList backlog;
return backlog;
}
-
-QVariantList CoreBacklogManager::requestBacklogAllFiltered(MsgId first, MsgId last, int limit, int additional, int type,
- int flags)
+QVariantList CoreBacklogManager::requestBacklogAllFiltered(MsgId first, MsgId last, int limit, int additional, int type, int flags)
{
QVariantList backlog;
QList<Message> msgList;
Q_OBJECT
public:
- CoreBacklogManager(CoreSession *coreSession = nullptr);
+ CoreBacklogManager(CoreSession* coreSession = nullptr);
- CoreSession *coreSession() { return _coreSession; }
+ CoreSession* coreSession() { return _coreSession; }
public slots:
QVariantList requestBacklog(BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0) override;
- QVariantList requestBacklogFiltered(BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1,
- int additional = 0, int type = -1, int flags = -1) override;
+ QVariantList requestBacklogFiltered(
+ BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0, int type = -1, int flags = -1) override;
QVariantList requestBacklogAll(MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0) override;
- QVariantList requestBacklogAllFiltered(MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0,
- int type = -1, int flags = -1) override;
+ QVariantList requestBacklogAllFiltered(
+ MsgId first = -1, MsgId last = -1, int limit = -1, int additional = 0, int type = -1, int flags = -1) override;
private:
- CoreSession *_coreSession;
+ CoreSession* _coreSession;
};
#include "corebasichandler.h"
-#include "util.h"
#include "logmessage.h"
+#include "util.h"
-CoreBasicHandler::CoreBasicHandler(CoreNetwork *parent)
- : BasicHandler(parent),
- _network(parent)
+CoreBasicHandler::CoreBasicHandler(CoreNetwork* parent)
+ : BasicHandler(parent)
+ , _network(parent)
{
connect(this, &CoreBasicHandler::displayMsg, network(), &CoreNetwork::onDisplayMsg);
connect(this, &CoreBasicHandler::putRawLine, network(), &CoreNetwork::putRawLine);
- connect(this, selectOverload<const QString&, const QList<QByteArray>&, const QByteArray&, bool>(&CoreBasicHandler::putCmd),
- network(), selectOverload<const QString&, const QList<QByteArray>&, const QByteArray&, bool>(&CoreNetwork::putCmd));
- connect(this, selectOverload<const QString&, const QList<QList<QByteArray>>&, const QByteArray&, bool>(&CoreBasicHandler::putCmd),
- network(), selectOverload<const QString&, const QList<QList<QByteArray>>&, const QByteArray&, bool>(&CoreNetwork::putCmd));
+ connect(this,
+ selectOverload<const QString&, const QList<QByteArray>&, const QByteArray&, bool>(&CoreBasicHandler::putCmd),
+ network(),
+ selectOverload<const QString&, const QList<QByteArray>&, const QByteArray&, bool>(&CoreNetwork::putCmd));
+ connect(this,
+ selectOverload<const QString&, const QList<QList<QByteArray>>&, const QByteArray&, bool>(&CoreBasicHandler::putCmd),
+ network(),
+ selectOverload<const QString&, const QList<QList<QByteArray>>&, const QByteArray&, bool>(&CoreNetwork::putCmd));
}
-
-QString CoreBasicHandler::serverDecode(const QByteArray &string)
+QString CoreBasicHandler::serverDecode(const QByteArray& string)
{
return network()->serverDecode(string);
}
-
-QStringList CoreBasicHandler::serverDecode(const QList<QByteArray> &stringlist)
+QStringList CoreBasicHandler::serverDecode(const QList<QByteArray>& stringlist)
{
QStringList list;
- foreach(QByteArray s, stringlist) list << network()->serverDecode(s);
+ foreach (QByteArray s, stringlist)
+ list << network()->serverDecode(s);
return list;
}
-
-QString CoreBasicHandler::channelDecode(const QString &bufferName, const QByteArray &string)
+QString CoreBasicHandler::channelDecode(const QString& bufferName, const QByteArray& string)
{
return network()->channelDecode(bufferName, string);
}
-
-QStringList CoreBasicHandler::channelDecode(const QString &bufferName, const QList<QByteArray> &stringlist)
+QStringList CoreBasicHandler::channelDecode(const QString& bufferName, const QList<QByteArray>& stringlist)
{
QStringList list;
- foreach(QByteArray s, stringlist) list << network()->channelDecode(bufferName, s);
+ foreach (QByteArray s, stringlist)
+ list << network()->channelDecode(bufferName, s);
return list;
}
-
-QString CoreBasicHandler::userDecode(const QString &userNick, const QByteArray &string)
+QString CoreBasicHandler::userDecode(const QString& userNick, const QByteArray& string)
{
return network()->userDecode(userNick, string);
}
-
-QStringList CoreBasicHandler::userDecode(const QString &userNick, const QList<QByteArray> &stringlist)
+QStringList CoreBasicHandler::userDecode(const QString& userNick, const QList<QByteArray>& stringlist)
{
QStringList list;
- foreach(QByteArray s, stringlist) list << network()->userDecode(userNick, s);
+ foreach (QByteArray s, stringlist)
+ list << network()->userDecode(userNick, s);
return list;
}
-
/*** ***/
-QByteArray CoreBasicHandler::serverEncode(const QString &string)
+QByteArray CoreBasicHandler::serverEncode(const QString& string)
{
return network()->serverEncode(string);
}
-
-QList<QByteArray> CoreBasicHandler::serverEncode(const QStringList &stringlist)
+QList<QByteArray> CoreBasicHandler::serverEncode(const QStringList& stringlist)
{
QList<QByteArray> list;
- foreach(QString s, stringlist) list << network()->serverEncode(s);
+ foreach (QString s, stringlist)
+ list << network()->serverEncode(s);
return list;
}
-
-QByteArray CoreBasicHandler::channelEncode(const QString &bufferName, const QString &string)
+QByteArray CoreBasicHandler::channelEncode(const QString& bufferName, const QString& string)
{
return network()->channelEncode(bufferName, string);
}
-
-QList<QByteArray> CoreBasicHandler::channelEncode(const QString &bufferName, const QStringList &stringlist)
+QList<QByteArray> CoreBasicHandler::channelEncode(const QString& bufferName, const QStringList& stringlist)
{
QList<QByteArray> list;
- foreach(QString s, stringlist) list << network()->channelEncode(bufferName, s);
+ foreach (QString s, stringlist)
+ list << network()->channelEncode(bufferName, s);
return list;
}
-
-QByteArray CoreBasicHandler::userEncode(const QString &userNick, const QString &string)
+QByteArray CoreBasicHandler::userEncode(const QString& userNick, const QString& string)
{
return network()->userEncode(userNick, string);
}
-
-QList<QByteArray> CoreBasicHandler::userEncode(const QString &userNick, const QStringList &stringlist)
+QList<QByteArray> CoreBasicHandler::userEncode(const QString& userNick, const QStringList& stringlist)
{
QList<QByteArray> list;
- foreach(QString s, stringlist) list << network()->userEncode(userNick, s);
+ foreach (QString s, stringlist)
+ list << network()->userEncode(userNick, s);
return list;
}
-
// ====================
// protected:
// ====================
-BufferInfo::Type CoreBasicHandler::typeByTarget(const QString &target) const
+BufferInfo::Type CoreBasicHandler::typeByTarget(const QString& target) const
{
if (target.isEmpty())
return BufferInfo::StatusBuffer;
return BufferInfo::QueryBuffer;
}
-
-void CoreBasicHandler::putCmd(const QString &cmd, const QByteArray ¶m, const QByteArray &prefix, const bool prepend)
+void CoreBasicHandler::putCmd(const QString& cmd, const QByteArray& param, const QByteArray& prefix, const bool prepend)
{
QList<QByteArray> list;
list << param;
#include <QStringList>
#include "basichandler.h"
-#include "message.h"
-
#include "corenetwork.h"
+#include "message.h"
class CoreSession;
Q_OBJECT
public:
- CoreBasicHandler(CoreNetwork *parent = nullptr);
-
- QString serverDecode(const QByteArray &string);
- QStringList serverDecode(const QList<QByteArray> &stringlist);
- QString channelDecode(const QString &bufferName, const QByteArray &string);
- QStringList channelDecode(const QString &bufferName, const QList<QByteArray> &stringlist);
- QString userDecode(const QString &userNick, const QByteArray &string);
- QStringList userDecode(const QString &userNick, const QList<QByteArray> &stringlist);
-
- QByteArray serverEncode(const QString &string);
- QList<QByteArray> serverEncode(const QStringList &stringlist);
- QByteArray channelEncode(const QString &bufferName, const QString &string);
- QList<QByteArray> channelEncode(const QString &bufferName, const QStringList &stringlist);
- QByteArray userEncode(const QString &userNick, const QString &string);
- QList<QByteArray> userEncode(const QString &userNick, const QStringList &stringlist);
+ CoreBasicHandler(CoreNetwork* parent = nullptr);
+
+ QString serverDecode(const QByteArray& string);
+ QStringList serverDecode(const QList<QByteArray>& stringlist);
+ QString channelDecode(const QString& bufferName, const QByteArray& string);
+ QStringList channelDecode(const QString& bufferName, const QList<QByteArray>& stringlist);
+ QString userDecode(const QString& userNick, const QByteArray& string);
+ QStringList userDecode(const QString& userNick, const QList<QByteArray>& stringlist);
+
+ QByteArray serverEncode(const QString& string);
+ QList<QByteArray> serverEncode(const QStringList& stringlist);
+ QByteArray channelEncode(const QString& bufferName, const QString& string);
+ QList<QByteArray> channelEncode(const QString& bufferName, const QStringList& stringlist);
+ QByteArray userEncode(const QString& userNick, const QString& string);
+ QList<QByteArray> userEncode(const QString& userNick, const QStringList& stringlist);
signals:
- void displayMsg(Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
+ void displayMsg(Message::Type,
+ BufferInfo::Type,
+ const QString& target,
+ const QString& text,
+ const QString& sender = "",
+ Message::Flags flags = Message::None);
/**
* Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority.
*
* @see CoreNetwork::putRawLine()
*/
- void putRawLine(const QByteArray &msg, const bool prepend = false);
+ void putRawLine(const QByteArray& msg, const bool prepend = false);
/**
* Sends the command with encoded parameters, with optional prefix or high priority.
*
- * @see CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix = QByteArray(), const bool prepend = false)
+ * @see CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix = QByteArray(), const bool
+ * prepend = false)
*/
- void putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix = {}, bool prepend = false);
+ void putCmd(const QString& cmd, const QList<QByteArray>& params, const QByteArray& prefix = {}, bool prepend = false);
/**
* Sends the command for each set of encoded parameters, with optional prefix or high priority.
*
- * @see CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix = QByteArray(), const bool prepend = false)
+ * @see CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix = QByteArray(), const
+ * bool prepend = false)
*/
- void putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix = {}, bool prepend = false);
+ void putCmd(const QString& cmd, const QList<QList<QByteArray>>& params, const QByteArray& prefix = {}, bool prepend = false);
protected:
/**
* maintain PING/PONG replies, the other side will close the connection.
* @endparmblock
*/
- void putCmd(const QString &cmd, const QByteArray ¶m, const QByteArray &prefix = QByteArray(), const bool prepend = false);
+ void putCmd(const QString& cmd, const QByteArray& param, const QByteArray& prefix = QByteArray(), const bool prepend = false);
- inline CoreNetwork *network() const { return _network; }
- inline CoreSession *coreSession() const { return _network->coreSession(); }
+ inline CoreNetwork* network() const { return _network; }
+ inline CoreSession* coreSession() const { return _network->coreSession(); }
- BufferInfo::Type typeByTarget(const QString &target) const;
+ BufferInfo::Type typeByTarget(const QString& target) const;
private:
- CoreNetwork *_network;
+ CoreNetwork* _network;
};
-
#endif
#include "corebuffersyncer.h"
#include "core.h"
-#include "coresession.h"
#include "corenetwork.h"
+#include "coresession.h"
#include "ircchannel.h"
class PurgeEvent : public QEvent
{
public:
- PurgeEvent() : QEvent(QEvent::User) {}
+ PurgeEvent()
+ : QEvent(QEvent::User)
+ {}
};
-CoreBufferSyncer::CoreBufferSyncer(CoreSession *parent)
- : BufferSyncer(Core::bufferLastSeenMsgIds(parent->user()), Core::bufferMarkerLineMsgIds(parent->user()), Core::bufferActivities(parent->user()), Core::highlightCounts(parent->user()), parent),
- _coreSession(parent),
- _purgeBuffers(false)
+CoreBufferSyncer::CoreBufferSyncer(CoreSession* parent)
+ : BufferSyncer(Core::bufferLastSeenMsgIds(parent->user()),
+ Core::bufferMarkerLineMsgIds(parent->user()),
+ Core::bufferActivities(parent->user()),
+ Core::highlightCounts(parent->user()),
+ parent)
+ , _coreSession(parent)
+ , _purgeBuffers(false)
{
connect(parent, &CoreSession::displayMsg, this, &CoreBufferSyncer::addBufferActivity);
connect(parent, &CoreSession::displayMsg, this, &CoreBufferSyncer::addCoreHighlight);
}
-
-void CoreBufferSyncer::requestSetLastSeenMsg(BufferId buffer, const MsgId &msgId)
+void CoreBufferSyncer::requestSetLastSeenMsg(BufferId buffer, const MsgId& msgId)
{
if (setLastSeenMsg(buffer, msgId)) {
int activity = Core::bufferActivity(buffer, msgId);
}
}
-
-void CoreBufferSyncer::requestSetMarkerLine(BufferId buffer, const MsgId &msgId)
+void CoreBufferSyncer::requestSetMarkerLine(BufferId buffer, const MsgId& msgId)
{
if (setMarkerLine(buffer, msgId))
dirtyMarkerLineBuffers << buffer;
}
-
void CoreBufferSyncer::storeDirtyIds()
{
UserId userId = _coreSession->user();
MsgId msgId;
- foreach(BufferId bufferId, dirtyLastSeenBuffers) {
+ foreach (BufferId bufferId, dirtyLastSeenBuffers) {
msgId = lastSeenMsg(bufferId);
if (msgId.isValid())
Core::setBufferLastSeenMsg(userId, bufferId, msgId);
}
- foreach(BufferId bufferId, dirtyMarkerLineBuffers) {
+ foreach (BufferId bufferId, dirtyMarkerLineBuffers) {
msgId = markerLine(bufferId);
if (msgId.isValid())
Core::setBufferMarkerLineMsg(userId, bufferId, msgId);
}
- foreach(BufferId bufferId, dirtyActivities) {
+ foreach (BufferId bufferId, dirtyActivities) {
Core::setBufferActivity(userId, bufferId, activity(bufferId));
}
- foreach(BufferId bufferId, dirtyHighlights) {
+ foreach (BufferId bufferId, dirtyHighlights) {
Core::setHighlightCount(userId, bufferId, highlightCount(bufferId));
}
dirtyHighlights.clear();
}
-
void CoreBufferSyncer::removeBuffer(BufferId bufferId)
{
BufferInfo bufferInfo = Core::getBufferInfo(_coreSession->user(), bufferId);
}
if (bufferInfo.type() == BufferInfo::ChannelBuffer) {
- CoreNetwork *net = _coreSession->network(bufferInfo.networkId());
+ CoreNetwork* net = _coreSession->network(bufferInfo.networkId());
if (!net) {
qWarning() << "CoreBufferSyncer::removeBuffer(): Received BufferInfo with unknown networkId!";
return;
}
- IrcChannel *chan = net->ircChannel(bufferInfo.bufferName());
+ IrcChannel* chan = net->ircChannel(bufferInfo.bufferName());
if (chan) {
qWarning() << "CoreBufferSyncer::removeBuffer(): Unable to remove Buffer for joined Channel:" << bufferInfo.bufferName();
return;
BufferSyncer::removeBuffer(bufferId);
}
-
void CoreBufferSyncer::renameBuffer(BufferId bufferId, QString newName)
{
BufferInfo bufferInfo = Core::getBufferInfo(_coreSession->user(), bufferId);
BufferSyncer::renameBuffer(bufferId, newName);
}
-
void CoreBufferSyncer::mergeBuffersPermanently(BufferId bufferId1, BufferId bufferId2)
{
BufferInfo bufferInfo1 = Core::getBufferInfo(_coreSession->user(), bufferId1);
BufferInfo bufferInfo2 = Core::getBufferInfo(_coreSession->user(), bufferId2);
if (!bufferInfo1.isValid() || !bufferInfo2.isValid()) {
- qWarning() << "CoreBufferSyncer::mergeBuffersPermanently(): invalid BufferIds:" << bufferId1 << bufferId2 << "for User:" << _coreSession->user();
+ qWarning() << "CoreBufferSyncer::mergeBuffersPermanently(): invalid BufferIds:" << bufferId1 << bufferId2
+ << "for User:" << _coreSession->user();
return;
}
if ((bufferInfo1.type() != BufferInfo::QueryBuffer && bufferInfo1.type() != BufferInfo::ChannelBuffer)
|| (bufferInfo2.type() != BufferInfo::QueryBuffer && bufferInfo2.type() != BufferInfo::ChannelBuffer)) {
- qWarning() << "CoreBufferSyncer::mergeBuffersPermanently(): only QueryBuffers and/or ChannelBuffers can be merged!" << bufferId1 << bufferId2;
- return;
+ qWarning() << "CoreBufferSyncer::mergeBuffersPermanently(): only QueryBuffers and/or ChannelBuffers can be merged!" << bufferId1
+ << bufferId2;
+ return;
}
if (Core::mergeBuffersPermanently(_coreSession->user(), bufferId1, bufferId2)) {
}
}
-
-void CoreBufferSyncer::customEvent(QEvent *event)
+void CoreBufferSyncer::customEvent(QEvent* event)
{
if (event->type() != QEvent::User)
return;
event->accept();
}
-
void CoreBufferSyncer::requestPurgeBufferIds()
{
if (_purgeBuffers)
QCoreApplication::postEvent(this, new PurgeEvent());
}
-
void CoreBufferSyncer::purgeBufferIds()
{
_purgeBuffers = false;
QList<BufferInfo> bufferInfos = Core::requestBuffers(_coreSession->user());
QSet<BufferId> actualBuffers;
- foreach(BufferInfo bufferInfo, bufferInfos) {
+ foreach (BufferInfo bufferInfo, bufferInfos) {
actualBuffers << bufferInfo.bufferId();
}
QSet<BufferId> storedIds = lastSeenBufferIds().toSet() + markerLineBufferIds().toSet();
- foreach(BufferId bufferId, storedIds) {
+ foreach (BufferId bufferId, storedIds) {
if (!actualBuffers.contains(bufferId)) {
BufferSyncer::removeBuffer(bufferId);
}
}
}
-void CoreBufferSyncer::setBufferActivity(BufferId buffer, int activity) {
+void CoreBufferSyncer::setBufferActivity(BufferId buffer, int activity)
+{
BufferSyncer::setBufferActivity(buffer, activity);
dirtyActivities << buffer;
}
-void CoreBufferSyncer::setHighlightCount(BufferId buffer, int highlightCount) {
+void CoreBufferSyncer::setHighlightCount(BufferId buffer, int highlightCount)
+{
BufferSyncer::setHighlightCount(buffer, highlightCount);
dirtyHighlights << buffer;
}
Q_OBJECT
public:
- explicit CoreBufferSyncer(CoreSession *parent);
+ explicit CoreBufferSyncer(CoreSession* parent);
public slots:
- void requestSetLastSeenMsg(BufferId buffer, const MsgId &msgId) override;
- void requestSetMarkerLine(BufferId buffer, const MsgId &msgId) override;
+ void requestSetLastSeenMsg(BufferId buffer, const MsgId& msgId) override;
+ void requestSetMarkerLine(BufferId buffer, const MsgId& msgId) override;
inline void requestRemoveBuffer(BufferId buffer) override { removeBuffer(buffer); }
void removeBuffer(BufferId bufferId) override;
- void addBufferActivity(const Message &message) {
+ void addBufferActivity(const Message& message)
+ {
auto oldActivity = activity(message.bufferId());
if (!oldActivity.testFlag(message.type())) {
- setBufferActivity(message.bufferId(), (int) (oldActivity | message.type()));
+ setBufferActivity(message.bufferId(), (int)(oldActivity | message.type()));
}
}
- void addCoreHighlight(const Message &message) {
+ void addCoreHighlight(const Message& message)
+ {
auto oldHighlightCount = highlightCount(message.bufferId());
if (message.flags().testFlag(Message::Flag::Highlight) && !message.flags().testFlag(Message::Flag::Self)) {
setHighlightCount(message.bufferId(), oldHighlightCount + 1);
void requestPurgeBufferIds() override;
- inline void requestMarkBufferAsRead(BufferId buffer) override {
+ inline void requestMarkBufferAsRead(BufferId buffer) override
+ {
int activity = Message::Types();
setBufferActivity(buffer, activity);
setHighlightCount(buffer, 0);
void storeDirtyIds();
protected:
- void customEvent(QEvent *event) override;
+ void customEvent(QEvent* event) override;
private:
- CoreSession *_coreSession;
+ CoreSession* _coreSession;
bool _purgeBuffers;
QSet<BufferId> dirtyLastSeenBuffers;
#include "corebufferviewconfig.h"
-CoreBufferViewConfig::CoreBufferViewConfig(int bufferViewId, QObject *parent)
+CoreBufferViewConfig::CoreBufferViewConfig(int bufferViewId, QObject* parent)
: BufferViewConfig(bufferViewId, parent)
{
setAllowClientUpdates(true);
}
-
-CoreBufferViewConfig::CoreBufferViewConfig(int bufferViewId, const QVariantMap &properties, QObject *parent)
+CoreBufferViewConfig::CoreBufferViewConfig(int bufferViewId, const QVariantMap& properties, QObject* parent)
: BufferViewConfig(bufferViewId, properties, parent)
{
setAllowClientUpdates(true);
Q_OBJECT
public:
- CoreBufferViewConfig(int bufferViewId, QObject *parent = nullptr);
- CoreBufferViewConfig(int bufferViewId, const QVariantMap &properties, QObject *parent = nullptr);
+ CoreBufferViewConfig(int bufferViewId, QObject* parent = nullptr);
+ CoreBufferViewConfig(int bufferViewId, const QVariantMap& properties, QObject* parent = nullptr);
public slots:
- inline void requestSetBufferViewName(const QString &bufferViewName) override { setBufferViewName(bufferViewName); }
- inline void requestRemoveBuffer(const BufferId &bufferId) override { removeBuffer(bufferId); }
- inline void requestRemoveBufferPermanently(const BufferId &bufferId) override { removeBufferPermanently(bufferId); }
- inline void requestAddBuffer(const BufferId &bufferId, int pos) override { addBuffer(bufferId, pos); }
- inline void requestMoveBuffer(const BufferId &bufferId, int pos) override { moveBuffer(bufferId, pos); }
+ inline void requestSetBufferViewName(const QString& bufferViewName) override { setBufferViewName(bufferViewName); }
+ inline void requestRemoveBuffer(const BufferId& bufferId) override { removeBuffer(bufferId); }
+ inline void requestRemoveBufferPermanently(const BufferId& bufferId) override { removeBufferPermanently(bufferId); }
+ inline void requestAddBuffer(const BufferId& bufferId, int pos) override { addBuffer(bufferId, pos); }
+ inline void requestMoveBuffer(const BufferId& bufferId, int pos) override { moveBuffer(bufferId, pos); }
};
#include "corebufferviewmanager.h"
-#include "corebufferviewconfig.h"
-
#include "core.h"
+#include "corebufferviewconfig.h"
#include "coresession.h"
-CoreBufferViewManager::CoreBufferViewManager(SignalProxy *proxy, CoreSession *parent)
- : BufferViewManager(proxy, parent),
- _coreSession(parent)
+CoreBufferViewManager::CoreBufferViewManager(SignalProxy* proxy, CoreSession* parent)
+ : BufferViewManager(proxy, parent)
+ , _coreSession(parent)
{
QVariantMap views = Core::getUserSetting(_coreSession->user(), "BufferViews").toMap();
QVariantMap::iterator iter = views.begin();
QVariantMap::iterator iterEnd = views.end();
- CoreBufferViewConfig *config = nullptr;
+ CoreBufferViewConfig* config = nullptr;
while (iter != iterEnd) {
config = new CoreBufferViewConfig(iter.key().toInt(), iter.value().toMap(), this);
addBufferViewConfig(config);
}
}
-
void CoreBufferViewManager::saveBufferViews()
{
QVariantMap views;
Core::setUserSetting(_coreSession->user(), "BufferViews", views);
}
-
-void CoreBufferViewManager::requestCreateBufferView(const QVariantMap &properties)
+void CoreBufferViewManager::requestCreateBufferView(const QVariantMap& properties)
{
QString bufferViewName = properties["bufferViewName"].toString();
int maxId = -1;
addBufferViewConfig(new CoreBufferViewConfig(maxId, properties, this));
}
-
-void CoreBufferViewManager::requestCreateBufferViews(const QVariantList &properties)
+void CoreBufferViewManager::requestCreateBufferViews(const QVariantList& properties)
{
QVariantList::const_iterator iter = properties.constBegin();
QVariantList::const_iterator iterEnd = properties.constEnd();
}
}
-
void CoreBufferViewManager::requestDeleteBufferView(int bufferViewId)
{
deleteBufferViewConfig(bufferViewId);
}
-
-void CoreBufferViewManager::requestDeleteBufferViews(const QVariantList &bufferViews)
+void CoreBufferViewManager::requestDeleteBufferViews(const QVariantList& bufferViews)
{
- foreach(QVariant bufferView, bufferViews) {
+ foreach (QVariant bufferView, bufferViews) {
deleteBufferViewConfig(bufferView.toInt());
}
}
Q_OBJECT
public:
- CoreBufferViewManager(SignalProxy *proxy, CoreSession *parent);
+ CoreBufferViewManager(SignalProxy* proxy, CoreSession* parent);
public slots:
- void requestCreateBufferView(const QVariantMap &properties) override;
- void requestCreateBufferViews(const QVariantList &properties) override;
+ void requestCreateBufferView(const QVariantMap& properties) override;
+ void requestCreateBufferViews(const QVariantList& properties) override;
void requestDeleteBufferView(int bufferViewId) override;
- void requestDeleteBufferViews(const QVariantList &bufferViews) override;
+ void requestDeleteBufferViews(const QVariantList& bufferViews) override;
void saveBufferViews();
private:
- CoreSession *_coreSession;
+ CoreSession* _coreSession;
};
constexpr auto settingsKey = "DccConfig";
-CoreDccConfig::CoreDccConfig(CoreSession *session)
+CoreDccConfig::CoreDccConfig(CoreSession* session)
: DccConfig(session)
, _coreSession{session}
{
connect(this, &SyncableObject::updatedRemotely, this, &CoreDccConfig::save);
}
-
void CoreDccConfig::save()
{
Core::setUserSetting(_coreSession->user(), settingsKey, toVariantMap());
*
* @param[in] session Pointer to the parent CoreSession (takes ownership)
*/
- CoreDccConfig(CoreSession *session);
+ CoreDccConfig(CoreSession* session);
public slots:
/**
void save();
private:
- CoreSession *_coreSession {nullptr}; ///< Pointer to the parent CoreSession
+ CoreSession* _coreSession{nullptr}; ///< Pointer to the parent CoreSession
};
Q_OBJECT
public:
- CoreEventManager(CoreSession *session)
+ CoreEventManager(CoreSession* session)
: EventManager(session)
, _coreSession(session)
{}
protected:
- inline Network *networkById(NetworkId id) const override { return _coreSession->network(id); }
+ inline Network* networkById(NetworkId id) const override { return _coreSession->network(id); }
private:
- CoreSession *_coreSession;
+ CoreSession* _coreSession;
};
#endif
constexpr auto settingsKey = "HighlightRuleList";
-CoreHighlightRuleManager::CoreHighlightRuleManager(CoreSession *session)
+CoreHighlightRuleManager::CoreHighlightRuleManager(CoreSession* session)
: HighlightRuleManager(session)
, _coreSession{session}
{
Core::setUserSetting(_coreSession->user(), settingsKey, toVariantMap());
}
-bool CoreHighlightRuleManager::match(const RawMessage &msg, const QString ¤tNick,
- const QStringList &identityNicks)
+bool CoreHighlightRuleManager::match(const RawMessage& msg, const QString& currentNick, const QStringList& identityNicks)
{
- return match(msg.networkId, msg.text, msg.sender, msg.type, msg.flags, msg.target, currentNick,
- identityNicks);
+ return match(msg.networkId, msg.text, msg.sender, msg.type, msg.flags, msg.target, currentNick, identityNicks);
}
*
* @param[in] session Pointer to the parent CoreSession (takes ownership)
*/
- explicit CoreHighlightRuleManager(CoreSession *session);
+ explicit CoreHighlightRuleManager(CoreSession* session);
- bool match(const RawMessage &msg, const QString ¤tNick, const QStringList &identityNicks);
+ bool match(const RawMessage& msg, const QString& currentNick, const QStringList& identityNicks);
public slots:
inline void requestToggleHighlightRule(int highlightRule) override { toggleHighlightRule(highlightRule); }
inline void requestRemoveHighlightRule(int highlightRule) override { removeHighlightRule(highlightRule); }
- inline void requestAddHighlightRule(int id, const QString &name, bool isRegEx, bool isCaseSensitive,
- bool isEnabled, bool isInverse, const QString &sender,
- const QString &chanName) override
+ inline void requestAddHighlightRule(int id,
+ const QString& name,
+ bool isRegEx,
+ bool isCaseSensitive,
+ bool isEnabled,
+ bool isInverse,
+ const QString& sender,
+ const QString& chanName) override
{
addHighlightRule(id, name, isRegEx, isCaseSensitive, isEnabled, isInverse, sender, chanName);
}
void save();
private:
- CoreSession *_coreSession {nullptr}; ///< Pointer to the parent CoreSession
+ CoreSession* _coreSession{nullptr}; ///< Pointer to the parent CoreSession
};
#include "signalproxy.h"
-CoreIdentity::CoreIdentity(IdentityId id, QObject *parent)
+CoreIdentity::CoreIdentity(IdentityId id, QObject* parent)
: Identity(id, parent)
#ifdef HAVE_SSL
, _certManager(*this)
#endif
}
-
-CoreIdentity::CoreIdentity(const Identity &other, QObject *parent)
+CoreIdentity::CoreIdentity(const Identity& other, QObject* parent)
: Identity(other, parent)
#ifdef HAVE_SSL
, _certManager(*this)
#endif
}
-
-CoreIdentity::CoreIdentity(const CoreIdentity &other, QObject *parent)
+CoreIdentity::CoreIdentity(const CoreIdentity& other, QObject* parent)
: Identity(other, parent)
#ifdef HAVE_SSL
- , _sslKey(other._sslKey),
- _sslCert(other._sslCert),
- _certManager(*this)
+ , _sslKey(other._sslKey)
+ , _sslCert(other._sslCert)
+ , _certManager(*this)
#endif
{
#ifdef HAVE_SSL
#endif
}
-
-void CoreIdentity::synchronize(SignalProxy *proxy)
+void CoreIdentity::synchronize(SignalProxy* proxy)
{
proxy->synchronize(this);
#ifdef HAVE_SSL
#endif
}
-
#ifdef HAVE_SSL
-void CoreIdentity::setSslKey(const QByteArray &encoded)
+void CoreIdentity::setSslKey(const QByteArray& encoded)
{
QSslKey key(encoded, QSsl::Rsa);
if (key.isNull())
setSslKey(key);
}
-
-void CoreIdentity::setSslCert(const QByteArray &encoded)
+void CoreIdentity::setSslCert(const QByteArray& encoded)
{
setSslCert(QSslCertificate(encoded));
}
-
#endif
-CoreIdentity &CoreIdentity::operator=(const CoreIdentity &identity)
+CoreIdentity& CoreIdentity::operator=(const CoreIdentity& identity)
{
Identity::operator=(identity);
#ifdef HAVE_SSL
return *this;
}
-
#ifdef HAVE_SSL
// ========================================
// CoreCertManager
// ========================================
-CoreCertManager::CoreCertManager(CoreIdentity &identity)
- : CertManager(identity.id()),
- identity(identity)
+CoreCertManager::CoreCertManager(CoreIdentity& identity)
+ : CertManager(identity.id())
+ , identity(identity)
{
setAllowClientUpdates(true);
}
-
void CoreCertManager::setId(IdentityId id)
{
renameObject(QString::number(id.toInt()));
}
-
-void CoreCertManager::setSslKey(const QByteArray &encoded)
+void CoreCertManager::setSslKey(const QByteArray& encoded)
{
identity.setSslKey(encoded);
CertManager::setSslKey(encoded);
}
-
-void CoreCertManager::setSslCert(const QByteArray &encoded)
+void CoreCertManager::setSslCert(const QByteArray& encoded)
{
identity.setSslCert(encoded);
CertManager::setSslCert(encoded);
}
-
-#endif //HAVE_SSL
+#endif // HAVE_SSL
#include "identity.h"
#ifdef HAVE_SSL
-#include <QSslKey>
-#include <QSslCertificate>
-#endif //HAVE_SSL
+# include <QSslCertificate>
+# include <QSslKey>
+#endif // HAVE_SSL
class SignalProxy;
Q_OBJECT
public:
- CoreCertManager(CoreIdentity &identity);
+ CoreCertManager(CoreIdentity& identity);
-#ifdef HAVE_SSL
- const QSslKey &sslKey() const override;
- const QSslCertificate &sslCert() const override;
+# ifdef HAVE_SSL
+ const QSslKey& sslKey() const override;
+ const QSslCertificate& sslCert() const override;
public slots:
- void setSslKey(const QByteArray &encoded) override;
- void setSslCert(const QByteArray &encoded) override;
-#endif
+ void setSslKey(const QByteArray& encoded) override;
+ void setSslCert(const QByteArray& encoded) override;
+# endif
void setId(IdentityId id);
private:
- CoreIdentity &identity;
+ CoreIdentity& identity;
};
-
-#endif //HAVE_SSL
+#endif // HAVE_SSL
// =========================================
// CoreIdentity
Q_OBJECT
public:
- CoreIdentity(IdentityId id, QObject *parent = nullptr);
- CoreIdentity(const Identity &other, QObject *parent = nullptr);
- CoreIdentity(const CoreIdentity &other, QObject *parent = nullptr);
+ CoreIdentity(IdentityId id, QObject* parent = nullptr);
+ CoreIdentity(const Identity& other, QObject* parent = nullptr);
+ CoreIdentity(const CoreIdentity& other, QObject* parent = nullptr);
- void synchronize(SignalProxy *proxy);
+ void synchronize(SignalProxy* proxy);
#ifdef HAVE_SSL
- inline const QSslKey &sslKey() const { return _sslKey; }
- inline void setSslKey(const QSslKey &key) { _sslKey = key; }
- void setSslKey(const QByteArray &encoded);
- inline const QSslCertificate &sslCert() const { return _sslCert; }
- inline void setSslCert(const QSslCertificate &cert) { _sslCert = cert; }
- void setSslCert(const QByteArray &encoded);
+ inline const QSslKey& sslKey() const { return _sslKey; }
+ inline void setSslKey(const QSslKey& key) { _sslKey = key; }
+ void setSslKey(const QByteArray& encoded);
+ inline const QSslCertificate& sslCert() const { return _sslCert; }
+ inline void setSslCert(const QSslCertificate& cert) { _sslCert = cert; }
+ void setSslCert(const QByteArray& encoded);
#endif /* HAVE_SSL */
- CoreIdentity &operator=(const CoreIdentity &identity);
+ CoreIdentity& operator=(const CoreIdentity& identity);
private:
#ifdef HAVE_SSL
#endif
};
-
#ifdef HAVE_SSL
-inline const QSslKey &CoreCertManager::sslKey() const
+inline const QSslKey& CoreCertManager::sslKey() const
{
return identity.sslKey();
}
-
-inline const QSslCertificate &CoreCertManager::sslCert() const
+inline const QSslCertificate& CoreCertManager::sslCert() const
{
return identity.sslCert();
}
#include "core.h"
#include "coresession.h"
-CoreIgnoreListManager::CoreIgnoreListManager(CoreSession *parent)
+CoreIgnoreListManager::CoreIgnoreListManager(CoreSession* parent)
: IgnoreListManager(parent)
{
- auto *session = qobject_cast<CoreSession *>(parent);
+ auto* session = qobject_cast<CoreSession*>(parent);
if (!session) {
qWarning() << "CoreIgnoreListManager: unable to load IgnoreList. Parent is not a Coresession!";
- //loadDefaults();
+ // loadDefaults();
return;
}
// we store our settings whenever they change
connect(this, &SyncableObject::updatedRemotely, this, &CoreIgnoreListManager::save);
- //if(isEmpty())
- //loadDefaults();
+ // if(isEmpty())
+ // loadDefaults();
}
-
-IgnoreListManager::StrictnessType CoreIgnoreListManager::match(const RawMessage &rawMsg, const QString &networkName)
+IgnoreListManager::StrictnessType CoreIgnoreListManager::match(const RawMessage& rawMsg, const QString& networkName)
{
- //StrictnessType _match(const QString &msgContents, const QString &msgSender, Message::Type msgType, const QString &network, const QString &bufferName);
+ // StrictnessType _match(const QString &msgContents, const QString &msgSender, Message::Type msgType, const QString &network, const QString &bufferName);
return _match(rawMsg.text, rawMsg.sender, rawMsg.type, networkName, rawMsg.target);
}
-
void CoreIgnoreListManager::save() const
{
- auto *session = qobject_cast<CoreSession *>(parent());
+ auto* session = qobject_cast<CoreSession*>(parent());
if (!session) {
qWarning() << "CoreIgnoreListManager: unable to save IgnoreList. Parent is not a Coresession!";
return;
Core::setUserSetting(session->user(), "IgnoreList", initIgnoreList());
}
-
-//void CoreIgnoreListManager::loadDefaults() {
+// void CoreIgnoreListManager::loadDefaults() {
// foreach(IgnoreListItem item, IgnoreListManager::defaults()) {
// addIgnoreListItem(item.contents(), item.isRegEx(), item.strictness(), item.scope(),
// item.scopeRule());
Q_OBJECT
public:
- explicit CoreIgnoreListManager(CoreSession *parent);
+ explicit CoreIgnoreListManager(CoreSession* parent);
- StrictnessType match(const RawMessage &rawMsg, const QString &networkName);
+ StrictnessType match(const RawMessage& rawMsg, const QString& networkName);
public slots:
- inline void requestToggleIgnoreRule(const QString &ignoreRule) override { toggleIgnoreRule(ignoreRule); }
- inline void requestRemoveIgnoreListItem(const QString &ignoreRule) override { removeIgnoreListItem(ignoreRule); }
- inline void requestAddIgnoreListItem(int type, const QString &ignoreRule, bool isRegEx, int strictness,
- int scope, const QString &scopeRule, bool isActive) override
+ inline void requestToggleIgnoreRule(const QString& ignoreRule) override { toggleIgnoreRule(ignoreRule); }
+ inline void requestRemoveIgnoreListItem(const QString& ignoreRule) override { removeIgnoreListItem(ignoreRule); }
+ inline void requestAddIgnoreListItem(
+ int type, const QString& ignoreRule, bool isRegEx, int strictness, int scope, const QString& scopeRule, bool isActive) override
{
addIgnoreListItem(type, ignoreRule, isRegEx, strictness, scope, scopeRule, isActive);
}
-
private slots:
void save() const;
-//private:
-// void loadDefaults();
+ // private:
+ // void loadDefaults();
};
***************************************************************************/
#include "coreircchannel.h"
+
#include "corenetwork.h"
-CoreIrcChannel::CoreIrcChannel(const QString &channelname, Network *network)
- : IrcChannel(channelname, network),
- _receivedWelcomeMsg(false)
+CoreIrcChannel::CoreIrcChannel(const QString& channelname, Network* network)
+ : IrcChannel(channelname, network)
+ , _receivedWelcomeMsg(false)
{
#ifdef HAVE_QCA2
_cipher = nullptr;
// Get the cipher key from CoreNetwork if present
- auto *coreNetwork = qobject_cast<CoreNetwork *>(network);
+ auto* coreNetwork = qobject_cast<CoreNetwork*>(network);
if (coreNetwork) {
QByteArray key = coreNetwork->readChannelCipherKey(channelname);
if (!key.isEmpty()) {
#endif
}
-
CoreIrcChannel::~CoreIrcChannel()
{
#ifdef HAVE_QCA2
// exists. There is no need to store the empty key if no cipher exists; no
// key was present when instantiating and no key was set during the
// channel's lifetime.
- auto *coreNetwork = qobject_cast<CoreNetwork *>(network());
+ auto* coreNetwork = qobject_cast<CoreNetwork*>(network());
if (coreNetwork && _cipher) {
coreNetwork->storeChannelCipherKey(name(), _cipher->key());
}
#endif
}
-
#ifdef HAVE_QCA2
-Cipher *CoreIrcChannel::cipher() const
+Cipher* CoreIrcChannel::cipher() const
{
if (!_cipher)
_cipher = new Cipher();
return _cipher;
}
-
void CoreIrcChannel::setEncrypted(bool e)
{
IrcChannel::setEncrypted(e);
}
}
-
#endif
#include "ircchannel.h"
#ifdef HAVE_QCA2
-# include "cipher.h"
+# include "cipher.h"
#endif
class CoreIrcChannel : public IrcChannel
Q_OBJECT
public:
- CoreIrcChannel(const QString &channelname, Network *network);
+ CoreIrcChannel(const QString& channelname, Network* network);
~CoreIrcChannel() override;
#ifdef HAVE_QCA2
- Cipher *cipher() const;
+ Cipher* cipher() const;
void setEncrypted(bool);
#endif
bool _receivedWelcomeMsg;
#ifdef HAVE_QCA2
- mutable Cipher *_cipher;
+ mutable Cipher* _cipher;
#endif
};
constexpr auto kTimeoutMs = 5000;
-QVariantList CoreIrcListHelper::requestChannelList(const NetworkId &netId, const QStringList &channelFilters)
+QVariantList CoreIrcListHelper::requestChannelList(const NetworkId& netId, const QStringList& channelFilters)
{
if (_finishedChannelLists.contains(netId))
return _finishedChannelLists.take(netId);
return QVariantList();
}
-
-bool CoreIrcListHelper::addChannel(const NetworkId &netId, const QString &channelName, quint32 userCount, const QString &topic)
+bool CoreIrcListHelper::addChannel(const NetworkId& netId, const QString& channelName, quint32 userCount, const QString& topic)
{
if (!_channelLists.contains(netId))
return false;
return true;
}
-
-bool CoreIrcListHelper::dispatchQuery(const NetworkId &netId, const QString &query)
+bool CoreIrcListHelper::dispatchQuery(const NetworkId& netId, const QString& query)
{
- CoreNetwork *network = coreSession()->network(netId);
+ CoreNetwork* network = coreSession()->network(netId);
if (network) {
_channelLists[netId] = QList<ChannelDescription>();
network->userInputHandler()->handleList(BufferInfo(), query);
}
}
-
-bool CoreIrcListHelper::endOfChannelList(const NetworkId &netId)
+bool CoreIrcListHelper::endOfChannelList(const NetworkId& netId)
{
if (_queryTimeoutByNetId.contains(netId)) {
// If we recieved an actual RPL_LISTEND, remove the timer
}
else if (_channelLists.contains(netId)) {
QVariantList channelList;
- foreach(ChannelDescription channel, _channelLists[netId]) {
+ foreach (ChannelDescription channel, _channelLists[netId]) {
QVariantList channelVariant;
- channelVariant << channel.channelName
- << channel.userCount
- << channel.topic;
+ channelVariant << channel.channelName << channel.userCount << channel.topic;
channelList << qVariantFromValue<QVariant>(channelVariant);
}
_finishedChannelLists[netId] = channelList;
}
}
-
-void CoreIrcListHelper::timerEvent(QTimerEvent *event)
+void CoreIrcListHelper::timerEvent(QTimerEvent* event)
{
if (!_queryTimeoutByTimerId.contains(event->timerId())) {
IrcListHelper::timerEvent(event);
#include <memory>
-#include "irclisthelper.h"
-
#include "coresession.h"
+#include "irclisthelper.h"
class QBasicTimer;
class QTimerEvent;
Q_OBJECT
public:
- inline CoreIrcListHelper(CoreSession *coreSession) : IrcListHelper(coreSession), _coreSession(coreSession) {};
+ inline CoreIrcListHelper(CoreSession* coreSession)
+ : IrcListHelper(coreSession)
+ , _coreSession(coreSession){};
- inline CoreSession *coreSession() const { return _coreSession; }
+ inline CoreSession* coreSession() const { return _coreSession; }
- inline bool requestInProgress(const NetworkId &netId) const { return _channelLists.contains(netId); }
+ inline bool requestInProgress(const NetworkId& netId) const { return _channelLists.contains(netId); }
public slots:
- QVariantList requestChannelList(const NetworkId &netId, const QStringList &channelFilters) override;
- bool addChannel(const NetworkId &netId, const QString &channelName, quint32 userCount, const QString &topic);
- bool endOfChannelList(const NetworkId &netId);
+ QVariantList requestChannelList(const NetworkId& netId, const QStringList& channelFilters) override;
+ bool addChannel(const NetworkId& netId, const QString& channelName, quint32 userCount, const QString& topic);
+ bool endOfChannelList(const NetworkId& netId);
protected:
- void timerEvent(QTimerEvent *event) override;
+ void timerEvent(QTimerEvent* event) override;
private:
- bool dispatchQuery(const NetworkId &netId, const QString &query);
+ bool dispatchQuery(const NetworkId& netId, const QString& query);
private:
- CoreSession *_coreSession;
+ CoreSession* _coreSession;
QHash<NetworkId, QString> _queuedQuery;
- QHash<NetworkId, QList<ChannelDescription> > _channelLists;
+ QHash<NetworkId, QList<ChannelDescription>> _channelLists;
QHash<NetworkId, QVariantList> _finishedChannelLists;
QHash<int, NetworkId> _queryTimeoutByTimerId;
QHash<NetworkId, std::shared_ptr<QBasicTimer>> _queryTimeoutByNetId;
***************************************************************************/
#include "coreircuser.h"
+
#include "corenetwork.h"
-CoreIrcUser::CoreIrcUser(const QString &hostmask, Network *network) : IrcUser(hostmask, network)
+CoreIrcUser::CoreIrcUser(const QString& hostmask, Network* network)
+ : IrcUser(hostmask, network)
{
#ifdef HAVE_QCA2
_cipher = nullptr;
// Get the cipher key from CoreNetwork if present
- auto *coreNetwork = qobject_cast<CoreNetwork *>(network);
+ auto* coreNetwork = qobject_cast<CoreNetwork*>(network);
if (coreNetwork) {
QByteArray key = coreNetwork->readChannelCipherKey(nick().toLower());
if (!key.isEmpty()) {
#endif
}
-
CoreIrcUser::~CoreIrcUser()
{
#ifdef HAVE_QCA2
// exists. There is no need to store the empty key if no cipher exists; no
// key was present when instantiating and no key was set during the
// channel's lifetime.
- auto *coreNetwork = qobject_cast<CoreNetwork *>(network());
+ auto* coreNetwork = qobject_cast<CoreNetwork*>(network());
if (coreNetwork && _cipher) {
coreNetwork->storeChannelCipherKey(nick().toLower(), _cipher->key());
}
#endif
}
-
#ifdef HAVE_QCA2
-Cipher *CoreIrcUser::cipher() const
+Cipher* CoreIrcUser::cipher() const
{
if (!_cipher)
_cipher = new Cipher();
return _cipher;
}
-
#endif
#include "ircuser.h"
#ifdef HAVE_QCA2
-# include "cipher.h"
+# include "cipher.h"
#endif
class CoreIrcUser : public IrcUser
Q_OBJECT
public:
- CoreIrcUser(const QString &hostmask, Network *network);
+ CoreIrcUser(const QString& hostmask, Network* network);
~CoreIrcUser() override;
#ifdef HAVE_QCA2
- Cipher *cipher() const;
+ Cipher* cipher() const;
#endif
#ifdef HAVE_QCA2
private:
- mutable Cipher *_cipher;
+ mutable Cipher* _cipher;
#endif
};
// IRCv3 capabilities
#include "irccap.h"
-CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session)
- : Network(networkid, session),
- _coreSession(session),
- _userInputHandler(new CoreUserInputHandler(this)),
- _autoReconnectCount(0),
- _quitRequested(false),
- _disconnectExpected(false),
-
- _previousConnectionAttemptFailed(false),
- _lastUsedServerIndex(0),
+CoreNetwork::CoreNetwork(const NetworkId& networkid, CoreSession* session)
+ : Network(networkid, session)
+ , _coreSession(session)
+ , _userInputHandler(new CoreUserInputHandler(this))
+ , _autoReconnectCount(0)
+ , _quitRequested(false)
+ , _disconnectExpected(false)
+ ,
+
+ _previousConnectionAttemptFailed(false)
+ , _lastUsedServerIndex(0)
+ ,
_requestedUserModes('-')
{
setAutoWhoInterval(networkConfig()->autoWhoInterval());
QHash<QString, QString> channels = coreSession()->persistentChannels(networkId());
- foreach(QString chan, channels.keys()) {
+ foreach (QString chan, channels.keys()) {
_channelKeys[chan.toLower()] = channels[chan];
}
QHash<QString, QByteArray> bufferCiphers = coreSession()->bufferCiphers(networkId());
- foreach(QString buffer, bufferCiphers.keys()) {
+ foreach (QString buffer, bufferCiphers.keys()) {
storeChannelCipherKey(buffer.toLower(), bufferCiphers[buffer]);
}
}
}
-
CoreNetwork::~CoreNetwork()
{
// Ensure we don't get any more signals from the socket while shutting down
disconnect(&socket, nullptr, this, nullptr);
if (!forceDisconnect()) {
qWarning() << QString{"Could not disconnect from network %1 (network ID: %2, user ID: %3)"}
- .arg(networkName()).arg(networkId().toInt()).arg(userId().toInt());
+ .arg(networkName())
+ .arg(networkId().toInt())
+ .arg(userId().toInt());
}
}
-
bool CoreNetwork::forceDisconnect(int msecs)
{
if (socket.state() == QAbstractSocket::UnconnectedState) {
return true;
}
-
-QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const
+QString CoreNetwork::channelDecode(const QString& bufferName, const QByteArray& string) const
{
if (!bufferName.isEmpty()) {
- IrcChannel *channel = ircChannel(bufferName);
+ IrcChannel* channel = ircChannel(bufferName);
if (channel)
return channel->decodeString(string);
}
return decodeString(string);
}
-
-QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const
+QString CoreNetwork::userDecode(const QString& userNick, const QByteArray& string) const
{
- IrcUser *user = ircUser(userNick);
+ IrcUser* user = ircUser(userNick);
if (user)
return user->decodeString(string);
return decodeString(string);
}
-
-QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const
+QByteArray CoreNetwork::channelEncode(const QString& bufferName, const QString& string) const
{
if (!bufferName.isEmpty()) {
- IrcChannel *channel = ircChannel(bufferName);
+ IrcChannel* channel = ircChannel(bufferName);
if (channel)
return channel->encodeString(string);
}
return encodeString(string);
}
-
-QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const
+QByteArray CoreNetwork::userEncode(const QString& userNick, const QString& string) const
{
- IrcUser *user = ircUser(userNick);
+ IrcUser* user = ircUser(userNick);
if (user)
return user->encodeString(string);
return encodeString(string);
}
-
void CoreNetwork::connectToIrc(bool reconnecting)
{
if (_shuttingDown) {
qWarning() << "Server list empty, ignoring connect request!";
return;
}
- CoreIdentity *identity = identityPtr();
+ CoreIdentity* identity = identityPtr();
if (!identity) {
qWarning() << "Invalid identity configures, ignoring connect request!";
return;
// Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users
// connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry.
- if (! server.useProxy) {
- //Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
- //hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
+ if (!server.useProxy) {
+ // Avoid hostname lookups when a proxy is specified. The lookups won't use the proxy and may therefore leak the DNS
+ // hostname of the server. Qt's DNS cache also isn't used by the proxy so we don't need to refresh the entry.
QHostInfo::fromName(server.host);
}
#ifdef HAVE_SSL
if (server.useSsl) {
- CoreIdentity *identity = identityPtr();
+ CoreIdentity* identity = identityPtr();
if (identity) {
socket.setLocalCertificate(identity->sslCert());
socket.setPrivateKey(identity->sslKey());
#endif
}
-
-void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect)
+void CoreNetwork::disconnectFromIrc(bool requested, const QString& reason, bool withReconnect)
{
// Disconnecting from the network, should expect a socket close or error
_disconnectExpected = true;
- _quitRequested = requested; // see socketDisconnected();
+ _quitRequested = requested; // see socketDisconnected();
if (!withReconnect) {
_autoReconnectTimer.stop();
- _autoReconnectCount = 0; // prohibiting auto reconnect
+ _autoReconnectCount = 0; // prohibiting auto reconnect
}
disablePingTimeout();
_msgQueue.clear();
- IrcUser *me_ = me();
+ IrcUser* me_ = me();
if (me_) {
QString awayMsg;
if (me_->isAway())
else
_quitReason = reason;
- showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
+ showMessage(Message::Server,
+ BufferInfo::StatusBuffer,
+ "",
+ tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason));
if (socket.state() == QAbstractSocket::UnconnectedState) {
onSocketDisconnected();
}
}
}
-
void CoreNetwork::onSocketCloseTimeout()
{
qWarning() << QString{"Timed out quitting network %1 (network ID: %2, user ID: %3)"}
- .arg(networkName()).arg(networkId().toInt()).arg(userId().toInt());
+ .arg(networkName())
+ .arg(networkId().toInt())
+ .arg(userId().toInt());
socket.abort();
}
-
void CoreNetwork::shutdown()
{
_shuttingDown = true;
disconnectFromIrc(false, {}, false);
}
-
-void CoreNetwork::userInput(const BufferInfo &buf, QString msg)
+void CoreNetwork::userInput(const BufferInfo& buf, QString msg)
{
userInputHandler()->handleUserInput(buf, msg);
}
-
-void CoreNetwork::putRawLine(const QByteArray &s, bool prepend)
+void CoreNetwork::putRawLine(const QByteArray& s, bool prepend)
{
if (_tokenBucket > 0 || (_skipMessageRates && _msgQueue.isEmpty())) {
// If there's tokens remaining, ...
// Or rate limits don't apply AND no messages are in queue (to prevent out-of-order), ...
// Send the message now.
writeToSocket(s);
- } else {
+ }
+ else {
// Otherwise, queue the message for later
if (prepend) {
// Jump to the start, skipping other messages
_msgQueue.prepend(s);
- } else {
+ }
+ else {
// Add to back, waiting in order
_msgQueue.append(s);
}
}
}
-
-void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix, const bool prepend)
+void CoreNetwork::putCmd(const QString& cmd, const QList<QByteArray>& params, const QByteArray& prefix, const bool prepend)
{
QByteArray msg;
putRawLine(msg, prepend);
}
-
-void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix, const bool prependAll)
+void CoreNetwork::putCmd(const QString& cmd, const QList<QList<QByteArray>>& params, const QByteArray& prefix, const bool prependAll)
{
QListIterator<QList<QByteArray>> i(params);
while (i.hasNext()) {
}
}
-
-void CoreNetwork::setChannelJoined(const QString &channel)
+void CoreNetwork::setChannelJoined(const QString& channel)
{
- queueAutoWhoOneshot(channel); // check this new channel first
+ queueAutoWhoOneshot(channel); // check this new channel first
Core::setChannelPersistent(userId(), networkId(), channel, true);
Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]);
}
-
-void CoreNetwork::setChannelParted(const QString &channel)
+void CoreNetwork::setChannelParted(const QString& channel)
{
removeChannelKey(channel);
_autoWhoQueue.removeAll(channel.toLower());
Core::setChannelPersistent(userId(), networkId(), channel, false);
}
-
-void CoreNetwork::addChannelKey(const QString &channel, const QString &key)
+void CoreNetwork::addChannelKey(const QString& channel, const QString& key)
{
if (key.isEmpty()) {
removeChannelKey(channel);
}
}
-
-void CoreNetwork::removeChannelKey(const QString &channel)
+void CoreNetwork::removeChannelKey(const QString& channel)
{
_channelKeys.remove(channel.toLower());
}
-
#ifdef HAVE_QCA2
-Cipher *CoreNetwork::cipher(const QString &target)
+Cipher* CoreNetwork::cipher(const QString& target)
{
if (target.isEmpty())
return nullptr;
if (!Cipher::neededFeaturesAvailable())
return nullptr;
- auto *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target));
+ auto* channel = qobject_cast<CoreIrcChannel*>(ircChannel(target));
if (channel) {
return channel->cipher();
}
- auto *user = qobject_cast<CoreIrcUser *>(ircUser(target));
+ auto* user = qobject_cast<CoreIrcUser*>(ircUser(target));
if (user) {
return user->cipher();
- } else if (!isChannelName(target)) {
+ }
+ else if (!isChannelName(target)) {
return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher();
}
return nullptr;
}
-
-QByteArray CoreNetwork::cipherKey(const QString &target) const
+QByteArray CoreNetwork::cipherKey(const QString& target) const
{
- auto *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
+ auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
if (c)
return c->cipher()->key();
- auto *u = qobject_cast<CoreIrcUser*>(ircUser(target));
+ auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
if (u)
return u->cipher()->key();
return QByteArray();
}
-
-void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key)
+void CoreNetwork::setCipherKey(const QString& target, const QByteArray& key)
{
- auto *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
+ auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
if (c) {
c->setEncrypted(c->cipher()->setKey(key));
coreSession()->setBufferCipher(networkId(), target, key);
return;
}
- auto *u = qobject_cast<CoreIrcUser*>(ircUser(target));
+ auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
if (!u && !isChannelName(target))
u = qobject_cast<CoreIrcUser*>(newIrcUser(target));
}
}
-
-bool CoreNetwork::cipherUsesCBC(const QString &target)
+bool CoreNetwork::cipherUsesCBC(const QString& target)
{
- auto *c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
+ auto* c = qobject_cast<CoreIrcChannel*>(ircChannel(target));
if (c)
return c->cipher()->usesCBC();
- auto *u = qobject_cast<CoreIrcUser*>(ircUser(target));
+ auto* u = qobject_cast<CoreIrcUser*>(ircUser(target));
if (u)
return u->cipher()->usesCBC();
}
#endif /* HAVE_QCA2 */
-bool CoreNetwork::setAutoWhoDone(const QString &name)
+bool CoreNetwork::setAutoWhoDone(const QString& name)
{
QString chanOrNick = name.toLower();
if (_autoWhoPending.value(chanOrNick, 0) <= 0)
return true;
}
-
-void CoreNetwork::setMyNick(const QString &mynick)
+void CoreNetwork::setMyNick(const QString& mynick)
{
Network::setMyNick(mynick);
if (connectionState() == Network::Initializing)
networkInitialized();
}
-
void CoreNetwork::onSocketHasData()
{
while (socket.canReadLine()) {
s.chop(2);
else if (s.endsWith("\n"))
s.chop(1);
- NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
+ NetworkDataEvent* event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s);
event->setTimestamp(QDateTime::currentDateTimeUtc());
emit newEvent(event);
}
}
-
void CoreNetwork::onSocketError(QAbstractSocket::SocketError error)
{
// Ignore socket closed errors if expected
}
}
-
void CoreNetwork::onSocketInitialized()
{
- CoreIdentity *identity = identityPtr();
+ CoreIdentity* identity = identityPtr();
if (!identity) {
qCritical() << "Identity invalid!";
disconnectFromIrc();
}
putRawLine(serverEncode(QString("NICK %1").arg(nick)));
// Only allow strict-compliant idents when strict mode is enabled
- putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(
- coreSession()->strictCompliantIdent(identity),
- identity->realName())));
+ putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(coreSession()->strictCompliantIdent(identity), identity->realName())));
}
-
void CoreNetwork::onSocketDisconnected()
{
disablePingTimeout();
_tokenBucketTimer.stop();
- IrcUser *me_ = me();
+ IrcUser* me_ = me();
if (me_) {
- foreach(QString channel, me_->channels())
- showMessage(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
+ foreach (QString channel, me_->channels())
+ showMessage(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask());
}
setConnected(false);
}
}
-
void CoreNetwork::onSocketStateChanged(QAbstractSocket::SocketState socketState)
{
Network::ConnectionState state;
setConnectionState(state);
}
-
void CoreNetwork::networkInitialized()
{
setConnectionState(Network::Initialized);
if (networkConfig()->autoWhoEnabled()) {
_autoWhoCycleTimer.start();
_autoWhoTimer.start();
- startAutoWhoCycle(); // FIXME wait for autojoin to be completed
+ startAutoWhoCycle(); // FIXME wait for autojoin to be completed
}
- Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
+ Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer
Core::setNetworkConnected(userId(), networkId(), true);
}
-
void CoreNetwork::sendPerform()
{
BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId());
}
// restore old user modes if server default mode is set.
- IrcUser *me_ = me();
+ IrcUser* me_ = me();
if (me_) {
if (!me_->userModes().isEmpty()) {
restoreUserModes();
}
// send perform list
- foreach(QString line, perform()) {
- if (!line.isEmpty()) userInput(statusBuf, line);
+ foreach (QString line, perform()) {
+ if (!line.isEmpty())
+ userInput(statusBuf, line);
}
// rejoin channels we've been in
if (rejoinChannels()) {
QStringList channels, keys;
- foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) {
+ foreach (QString chan, coreSession()->persistentChannels(networkId()).keys()) {
QString key = channelKey(chan);
if (!key.isEmpty()) {
channels.prepend(chan);
}
}
-
void CoreNetwork::restoreUserModes()
{
- IrcUser *me_ = me();
+ IrcUser* me_ = me();
Q_ASSERT(me_);
disconnect(me_, &IrcUser::userModesSet, this, &CoreNetwork::restoreUserModes);
putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes)));
}
-
-void CoreNetwork::updateIssuedModes(const QString &requestedModes)
+void CoreNetwork::updateIssuedModes(const QString& requestedModes)
{
QString addModes;
QString removeModes;
QString addModesOld = _requestedUserModes.section('-', 0, 0);
QString removeModesOld = _requestedUserModes.section('-', 1);
- addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
- addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
+ addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate
+ addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update
addModes += addModesOld;
- removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
- removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
+ removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate
+ removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update
removeModes += removeModesOld;
_requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes);
}
-
void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes)
{
QString persistentUserModes = Core::userModes(userId(), networkId());
Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove));
}
-
void CoreNetwork::resetPersistentModes()
{
_requestedUserModes = QString('-');
Core::setUserModes(userId(), networkId(), QString());
}
-
void CoreNetwork::setUseAutoReconnect(bool use)
{
Network::setUseAutoReconnect(use);
_autoReconnectTimer.stop();
}
-
void CoreNetwork::setAutoReconnectInterval(quint32 interval)
{
Network::setAutoReconnectInterval(interval);
_autoReconnectTimer.setInterval(interval * 1000);
}
-
void CoreNetwork::setAutoReconnectRetries(quint16 retries)
{
Network::setAutoReconnectRetries(retries);
}
}
-
void CoreNetwork::doAutoReconnect()
{
if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) {
connectToIrc(true);
}
-
void CoreNetwork::sendPing()
{
qint64 now = QDateTime::currentDateTime().toMSecsSinceEpoch();
qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings."
<< "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite();
}
- if ((int)_pingCount >= networkConfig()->maxPingCount()
- && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
+ if ((int)_pingCount >= networkConfig()->maxPingCount() && (now - _lastPingTime) <= (_pingTimer.interval() + (1 * 1000))) {
// In transitioning to 64-bit time, the interval no longer needs converted down to seconds.
// However, to reduce the risk of breaking things by changing past behavior, we still allow
// up to 1 second missed instead of enforcing a stricter 1 millisecond allowance.
// the second check compares the actual elapsed time since the last ping and the pingTimer interval
// if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked
// and unable to even handle a ping answer. So we ignore those misses.
- disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */);
+ disconnectFromIrc(false,
+ QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000),
+ true /* withReconnect */);
}
else {
_lastPingTime = now;
_pingCount++;
// Don't send pings until the network is initialized
- if(_sendPings) {
+ if (_sendPings) {
// Mark as waiting for a reply
_pongReplyPending = true;
// Send default timestamp ping
}
}
-
void CoreNetwork::enablePingTimeout(bool enable)
{
if (!enable)
}
}
-
void CoreNetwork::disablePingTimeout()
{
_pingTimer.stop();
resetPongReplyPending();
}
-
void CoreNetwork::setPingInterval(int interval)
{
_pingTimer.setInterval(interval * 1000);
}
-
void CoreNetwork::setPongTimestampValid(bool validTimestamp)
{
_pongTimestampValid = validTimestamp;
}
-
/******** Custom Rate Limiting ********/
void CoreNetwork::updateRateLimiting(const bool forceUnlimited)
_burstSize = messageRateBurstSize();
if (_burstSize < 1) {
- qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!"
- << _burstSize;
+ qWarning() << "Invalid messageRateBurstSize data, cannot have zero message burst size!" << _burstSize;
// Can't go slower than one message at a time
_burstSize = 1;
}
// TODO If testing shows this isn't needed, it can be simplified to a direct call.
// Hesitant to change it without a wide variety of situations to verify behavior.
_tokenBucketTimer.start(100);
- } else {
+ }
+ else {
// No rate limiting, disable the timer
_tokenBucketTimer.stop();
}
- } else {
+ }
+ else {
// Rate limiting enabled, enable the timer
_tokenBucketTimer.start(_messageDelay);
}
- } else {
+ }
+ else {
// Custom message rates disabled. Go for the default.
_skipMessageRates = false; // Enable rate-limiting by default
_tokenBucket = _burstSize;
}
-
/******** IRCv3 Capability Negotiation ********/
-void CoreNetwork::serverCapAdded(const QString &capability)
+void CoreNetwork::serverCapAdded(const QString& capability)
{
// Check if it's a known capability; if so, add it to the list
// Handle special cases first
// Only request SASL if it's enabled
if (networkInfo().useSasl)
queueCap(capability);
- } else if (IrcCap::knownCaps.contains(capability)) {
+ }
+ else if (IrcCap::knownCaps.contains(capability)) {
// Handling for general known capabilities
queueCap(capability);
}
}
-void CoreNetwork::serverCapAcknowledged(const QString &capability)
+void CoreNetwork::serverCapAcknowledged(const QString& capability)
{
// This may be called multiple times in certain situations.
if (saslMaybeSupports(IrcCap::SaslMech::EXTERNAL)) {
// EXTERNAL authentication supported, send request
putRawLine(serverEncode("AUTHENTICATE EXTERNAL"));
- } else {
+ }
+ else {
showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL EXTERNAL authentication not supported"));
sendNextCap();
}
- } else {
+ }
+ else {
#endif
if (saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
// PLAIN authentication supported, send request
// Only working with PLAIN atm, blowfish later
putRawLine(serverEncode("AUTHENTICATE PLAIN"));
- } else {
+ }
+ else {
showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL PLAIN authentication not supported"));
sendNextCap();
}
}
}
-void CoreNetwork::serverCapRemoved(const QString &capability)
+void CoreNetwork::serverCapRemoved(const QString& capability)
{
// This may be called multiple times in certain situations.
}
}
-void CoreNetwork::queueCap(const QString &capability)
+void CoreNetwork::queueCap(const QString& capability)
{
// IRCv3 specs all use lowercase capability names
QString _capLowercase = capability.toLower();
- if(capsRequiringConfiguration.contains(_capLowercase)) {
+ if (capsRequiringConfiguration.contains(_capLowercase)) {
// The capability requires additional configuration before being acknowledged (e.g. SASL),
// so we should negotiate it separately from all other capabilities. Otherwise new
// capabilities will be requested while still configuring the previous one.
if (!_capsQueuedIndividual.contains(_capLowercase)) {
_capsQueuedIndividual.append(_capLowercase);
}
- } else {
+ }
+ else {
// The capability doesn't need any special configuration, so it should be safe to try
// bundling together with others. "Should" being the imperative word, as IRC servers can do
// anything.
if (!_capsQueuedIndividual.empty()) {
// We have an individual capability available. Take the first and pass it back.
return _capsQueuedIndividual.takeFirst();
- } else if (!_capsQueuedBundled.empty()) {
+ }
+ else if (!_capsQueuedBundled.empty()) {
// We have capabilities available that can be grouped. Try to fit in as many as within the
// maximum length.
// See CoreNetwork::maxCapRequestLength
_capsQueuedLastBundle.append(nextCap);
// Then remove it from the queue
_capsQueuedBundled.removeFirst();
- } else {
+ }
+ else {
// We've reached the length limit for a single capability request, stop adding more
break;
}
}
// Return this space-separated set of capabilities, removing any extra spaces
return capBundle.trimmed();
- } else {
+ }
+ else {
// No capabilities left to negotiate, return an empty string.
return QString();
}
// Add most recently tried capability set to individual list, re-requesting them one at a time
_capsQueuedIndividual.append(_capsQueuedLastBundle);
// Warn of this issue to explain the slower login. Servers usually shouldn't trigger this.
- showMessage(Message::Server, BufferInfo::StatusBuffer, "",
- tr("Could not negotiate some capabilities, retrying individually (%1)...")
- .arg(_capsQueuedLastBundle.join(", ")));
+ showMessage(Message::Server,
+ BufferInfo::StatusBuffer,
+ "",
+ tr("Could not negotiate some capabilities, retrying individually (%1)...").arg(_capsQueuedLastBundle.join(", ")));
// Capabilities are already removed from the capability bundle queue via takeQueuedCaps(), no
// need to remove them here.
// Clear the most recently tried set to reduce risk that mistakes elsewhere causes retrying
// Build a list of queued capabilities, starting with individual, then bundled, only adding the
// comma separator between the two if needed (both individual and bundled caps exist).
- QString queuedCapsDisplay =
- _capsQueuedIndividual.join(", ")
- + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
- + _capsQueuedBundled.join(", ");
+ QString queuedCapsDisplay = _capsQueuedIndividual.join(", ")
+ + ((!_capsQueuedIndividual.empty() && !_capsQueuedBundled.empty()) ? ", " : "")
+ + _capsQueuedBundled.join(", ");
showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Negotiating capabilities (requesting: %1)...").arg(queuedCapsDisplay));
sendNextCap();
if (capNegotiationInProgress()) {
// Request the next set of capabilities and remove them from the list
putRawLine(serverEncode(QString("CAP REQ :%1").arg(takeQueuedCaps())));
- } else {
+ }
+ else {
// No pending desired capabilities, capability negotiation finished
// If SASL requested but not available, print a warning
if (networkInfo().useSasl && !capEnabled(IrcCap::SASL))
showMessage(Message::Error, BufferInfo::StatusBuffer, "", tr("SASL authentication currently not supported by server"));
if (_capNegotiationActive) {
- showMessage(Message::Server, BufferInfo::StatusBuffer, "", tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
+ showMessage(Message::Server,
+ BufferInfo::StatusBuffer,
+ "",
+ tr("Capability negotiation finished (enabled: %1)").arg(capsEnabled().join(", ")));
_capNegotiationActive = false;
}
_autoWhoQueue = channels();
}
-void CoreNetwork::queueAutoWhoOneshot(const QString &name)
+void CoreNetwork::queueAutoWhoOneshot(const QString& name)
{
// Prepend so these new channels/nicks are the first to be checked
// Don't allow duplicates
}
}
-
void CoreNetwork::setAutoWhoDelay(int delay)
{
_autoWhoTimer.setInterval(delay * 1000);
}
-
void CoreNetwork::setAutoWhoInterval(int interval)
{
_autoWhoCycleTimer.setInterval(interval * 1000);
}
-
void CoreNetwork::setAutoWhoEnabled(bool enabled)
{
if (enabled && isConnected() && !_autoWhoTimer.isActive())
}
}
-
void CoreNetwork::sendAutoWho()
{
// Don't send autowho if there are still some pending
while (!_autoWhoQueue.isEmpty()) {
QString chanOrNick = _autoWhoQueue.takeFirst();
// Check if it's a known channel or nick
- IrcChannel *ircchan = ircChannel(chanOrNick);
- IrcUser *ircuser = ircUser(chanOrNick);
+ IrcChannel* ircchan = ircChannel(chanOrNick);
+ IrcUser* ircuser = ircUser(chanOrNick);
if (ircchan) {
// Apply channel limiting rules
// If using away-notify, don't impose channel size limits in order to capture away
// state of everyone. Auto-who won't run on a timer so network impact is minimal.
- if (networkConfig()->autoWhoNickLimit() > 0
- && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
+ if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()
&& !capEnabled(IrcCap::AWAY_NOTIFY))
continue;
_autoWhoPending[chanOrNick.toLower()]++;
- } else if (ircuser) {
+ }
+ else if (ircuser) {
// Checking a nick, add it to the pending list
_autoWhoPending[ircuser->nick().toLower()]++;
- } else {
+ }
+ else {
// Not a channel or a nick, skip it
qDebug() << "Skipping who polling of unknown channel or nick" << chanOrNick;
continue;
// See http://faerion.sourceforge.net/doc/irc/whox.var
// And https://github.com/quakenet/snircd/blob/master/doc/readme.who
// And https://github.com/hexchat/hexchat/blob/57478b65758e6b697b1d82ce21075e74aa475efc/src/common/proto-irc.c#L752
- putRawLine(serverEncode(QString("WHO %1 n%chtsunfra,%2")
- .arg(serverEncode(chanOrNick),
- QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
- } else {
+ putRawLine(serverEncode(
+ QString("WHO %1 n%chtsunfra,%2").arg(serverEncode(chanOrNick), QString::number(IrcCap::ACCOUNT_NOTIFY_WHOX_NUM))));
+ }
+ else {
// Fall back to normal WHO
//
// Note: According to RFC 1459, "WHO <phrase>" can fall back to searching realname,
break;
}
- if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()
- && !capEnabled(IrcCap::AWAY_NOTIFY)) {
+ if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive() && !capEnabled(IrcCap::AWAY_NOTIFY)) {
// Timer was stopped, means a new cycle is due immediately
// Don't run a new cycle if using away-notify; server will notify as appropriate
_autoWhoCycleTimer.start();
startAutoWhoCycle();
- } else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
+ }
+ else if (capEnabled(IrcCap::AWAY_NOTIFY) && _autoWhoCycleTimer.isActive()) {
// Don't run another who cycle if away-notify is enabled
_autoWhoCycleTimer.stop();
}
}
-
#ifdef HAVE_SSL
-void CoreNetwork::onSslErrors(const QList<QSslError> &sslErrors)
+void CoreNetwork::onSslErrors(const QList<QSslError>& sslErrors)
{
Server server = usedServer();
if (server.sslVerify) {
// Disconnect, triggering a reconnect in case it's a temporary issue with certificate
// validity, network trouble, etc.
disconnectFromIrc(false, QString("Encrypted connection not verified"), true /* withReconnect */);
- } else {
+ }
+ else {
// Treat the SSL error as a warning, continue to connect anyways
QString sslErrorMessage = tr("Encrypted connection couldn't be verified, continuing "
"since verification is not required");
}
}
-
#endif // HAVE_SSL
void CoreNetwork::checkTokenBucket()
fillBucketAndProcessQueue();
}
-
void CoreNetwork::fillBucketAndProcessQueue()
{
// If there's less tokens than burst size, refill the token bucket by 1
}
}
-
-void CoreNetwork::writeToSocket(const QByteArray &data)
+void CoreNetwork::writeToSocket(const QByteArray& data)
{
// Log the message if enabled and network ID matches or allows all
- if (_debugLogRawIrc
- && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
+ if (_debugLogRawIrc && (_debugLogRawNetId == -1 || networkId().toInt() == _debugLogRawNetId)) {
// Include network ID
qDebug() << "IRC net" << networkId() << ">>" << data;
}
}
}
-
Network::Server CoreNetwork::usedServer() const
{
if (_lastUsedServerIndex < serverList().count())
return Network::Server();
}
-
void CoreNetwork::requestConnect() const
{
if (_shuttingDown) {
qWarning() << "Requesting connect while already being connected!";
return;
}
- QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection);
+ QMetaObject::invokeMethod(const_cast<CoreNetwork*>(this), "connectToIrc", Qt::QueuedConnection);
}
-
void CoreNetwork::requestDisconnect() const
{
if (_shuttingDown) {
userInputHandler()->handleQuit(BufferInfo(), QString());
}
-
-void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info)
+void CoreNetwork::requestSetNetworkInfo(const NetworkInfo& info)
{
Network::Server currentServer = usedServer();
setNetworkInfo(info);
}
}
-
-QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, const std::function<QList<QByteArray>(QString &)> &cmdGenerator)
+QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString& cmd,
+ const QString& message,
+ const std::function<QList<QByteArray>(QString&)>& cmdGenerator)
{
QString wrkMsg(message);
QList<QList<QByteArray>> msgsToSend;
wrkMsg.remove(0, splitPos);
msgsToSend.append(splitMsgEnc);
}
- else{
+ else {
// If the entire remaining message is short enough to be sent all at once, remove
// it from the wrkMsg and add it to the list of messages to be sent.
wrkMsg.remove(0, splitPos);
#pragma once
-#include "network.h"
#include "coreircchannel.h"
#include "coreircuser.h"
+#include "network.h"
// IRCv3 capabilities
-#include "irccap.h"
-
#include <QTimer>
+#include "irccap.h"
+
#ifdef HAVE_SSL
-# include <QSslSocket>
-# include <QSslError>
+# include <QSslError>
+# include <QSslSocket>
#else
-# include <QTcpSocket>
+# include <QTcpSocket>
#endif
#ifdef HAVE_QCA2
-# include "cipher.h"
+# include "cipher.h"
#endif
-#include "coresession.h"
-
#include <functional>
+#include "coresession.h"
+
class CoreIdentity;
class CoreUserInputHandler;
class CoreIgnoreListManager;
Q_OBJECT
public:
- CoreNetwork(const NetworkId &networkid, CoreSession *session);
+ CoreNetwork(const NetworkId& networkid, CoreSession* session);
~CoreNetwork() override;
- inline CoreIdentity *identityPtr() const { return coreSession()->identity(identity()); }
- inline CoreSession *coreSession() const { return _coreSession; }
- inline CoreNetworkConfig *networkConfig() const { return coreSession()->networkConfig(); }
+ inline CoreIdentity* identityPtr() const { return coreSession()->identity(identity()); }
+ inline CoreSession* coreSession() const { return _coreSession; }
+ inline CoreNetworkConfig* networkConfig() const { return coreSession()->networkConfig(); }
- inline CoreUserInputHandler *userInputHandler() const { return _userInputHandler; }
- inline CoreIgnoreListManager *ignoreListManager() { return coreSession()->ignoreListManager(); }
+ inline CoreUserInputHandler* userInputHandler() const { return _userInputHandler; }
+ inline CoreIgnoreListManager* ignoreListManager() { return coreSession()->ignoreListManager(); }
//! Decode a string using the server (network) decoding.
- inline QString serverDecode(const QByteArray &string) const { return decodeServerString(string); }
+ inline QString serverDecode(const QByteArray& string) const { return decodeServerString(string); }
//! Decode a string using a channel-specific encoding if one is set (and use the standard encoding else).
- QString channelDecode(const QString &channelName, const QByteArray &string) const;
+ QString channelDecode(const QString& channelName, const QByteArray& string) const;
//! Decode a string using an IrcUser-specific encoding, if one exists (using the standaed encoding else).
- QString userDecode(const QString &userNick, const QByteArray &string) const;
+ QString userDecode(const QString& userNick, const QByteArray& string) const;
//! Encode a string using the server (network) encoding.
- inline QByteArray serverEncode(const QString &string) const { return encodeServerString(string); }
+ inline QByteArray serverEncode(const QString& string) const { return encodeServerString(string); }
//! Encode a string using the channel-specific encoding, if set, and use the standard encoding else.
- QByteArray channelEncode(const QString &channelName, const QString &string) const;
+ QByteArray channelEncode(const QString& channelName, const QString& string) const;
//! Encode a string using the user-specific encoding, if set, and use the standard encoding else.
- QByteArray userEncode(const QString &userNick, const QString &string) const;
+ QByteArray userEncode(const QString& userNick, const QString& string) const;
- inline QString channelKey(const QString &channel) const { return _channelKeys.value(channel.toLower(), QString()); }
+ inline QString channelKey(const QString& channel) const { return _channelKeys.value(channel.toLower(), QString()); }
- inline QByteArray readChannelCipherKey(const QString &channel) const { return _cipherKeys.value(channel.toLower()); }
- inline void storeChannelCipherKey(const QString &channel, const QByteArray &key) { _cipherKeys[channel.toLower()] = key; }
+ inline QByteArray readChannelCipherKey(const QString& channel) const { return _cipherKeys.value(channel.toLower()); }
+ inline void storeChannelCipherKey(const QString& channel, const QByteArray& key) { _cipherKeys[channel.toLower()] = key; }
/**
* Checks if the given target has an automatic WHO in progress
* @param name Channel or nickname
* @return True if an automatic WHO is in progress, otherwise false
*/
- inline bool isAutoWhoInProgress(const QString &name) const
- {
- return _autoWhoPending.value(name.toLower(), 0);
- }
+ inline bool isAutoWhoInProgress(const QString& name) const { return _autoWhoPending.value(name.toLower(), 0); }
inline UserId userId() const { return _coreSession->user(); }
*/
inline bool isPongReplyPending() const { return _pongReplyPending; }
- QList<QList<QByteArray>> splitMessage(const QString &cmd, const QString &message, const std::function<QList<QByteArray>(QString &)> &cmdGenerator);
+ QList<QList<QByteArray>> splitMessage(const QString& cmd,
+ const QString& message,
+ const std::function<QList<QByteArray>(QString&)>& cmdGenerator);
// IRCv3 capability negotiation
*
* @param[in] capability Name of the capability
*/
- void queueCap(const QString &capability);
+ void queueCap(const QString& capability);
/**
* Begins capability negotiation if capabilities are queued, otherwise returns.
*
* See: http://ircv3.net/specs/extensions/sasl-3.2.html
*/
- const QStringList capsRequiringConfiguration = QStringList {
- IrcCap::SASL
- };
+ const QStringList capsRequiringConfiguration = QStringList{IrcCap::SASL};
public slots:
- void setMyNick(const QString &mynick) override;
+ void setMyNick(const QString& mynick) override;
void requestConnect() const override;
void requestDisconnect() const override;
- void requestSetNetworkInfo(const NetworkInfo &info) override;
+ void requestSetNetworkInfo(const NetworkInfo& info) override;
void setUseAutoReconnect(bool) override;
void setAutoReconnectInterval(quint32) override;
* @param reason Reason for quitting, defaulting to the user-configured quit reason
* @param withReconnect Reconnect to the network after disconnecting (e.g. ping timeout)
*/
- void disconnectFromIrc(bool requested = true, const QString &reason = QString(), bool withReconnect = false);
+ void disconnectFromIrc(bool requested = true, const QString& reason = QString(), bool withReconnect = false);
/**
* Forcibly close the IRC server socket, waiting for it to close.
*/
bool forceDisconnect(int msecs = 1000);
- void userInput(const BufferInfo &bufferInfo, QString msg);
+ void userInput(const BufferInfo& bufferInfo, QString msg);
/**
* Sends the raw (encoded) line, adding to the queue if needed, optionally with higher priority.
* PING/PONG replies, the other side will close the connection.
* @endparmblock
*/
- void putRawLine(const QByteArray &input, bool prepend = false);
+ void putRawLine(const QByteArray& input, bool prepend = false);
/**
* Sends the command with encoded parameters, with optional prefix or high priority.
* maintain PING/PONG replies, the other side will close the connection.
* @endparmblock
*/
- void putCmd(const QString &cmd, const QList<QByteArray> ¶ms, const QByteArray &prefix = {}, bool prepend = false);
+ void putCmd(const QString& cmd, const QList<QByteArray>& params, const QByteArray& prefix = {}, bool prepend = false);
/**
* Sends the command for each set of encoded parameters, with optional prefix or high priority.
* cannot maintain PING/PONG replies, the other side will close the connection.
* @endparmblock
*/
- void putCmd(const QString &cmd, const QList<QList<QByteArray>> ¶ms, const QByteArray &prefix = {}, bool prependAll = false);
+ void putCmd(const QString& cmd, const QList<QList<QByteArray>>& params, const QByteArray& prefix = {}, bool prependAll = false);
- void setChannelJoined(const QString &channel);
- void setChannelParted(const QString &channel);
- void addChannelKey(const QString &channel, const QString &key);
- void removeChannelKey(const QString &channel);
+ void setChannelJoined(const QString& channel);
+ void setChannelParted(const QString& channel);
+ void addChannelKey(const QString& channel, const QString& key);
+ void removeChannelKey(const QString& channel);
// Blowfish stuff
#ifdef HAVE_QCA2
- Cipher *cipher(const QString &recipient);
- QByteArray cipherKey(const QString &recipient) const;
- void setCipherKey(const QString &recipient, const QByteArray &key);
- bool cipherUsesCBC(const QString &target);
+ Cipher* cipher(const QString& recipient);
+ QByteArray cipherKey(const QString& recipient) const;
+ void setCipherKey(const QString& recipient, const QByteArray& key);
+ bool cipherUsesCBC(const QString& target);
#endif
// Custom rate limiting (can be connected to signals)
*
* @param[in] capability Name of the capability
*/
- void serverCapAdded(const QString &capability);
+ void serverCapAdded(const QString& capability);
/**
* Indicates a capability was acknowledged (enabled by the IRC server).
*
* @param[in] capability Name of the capability
*/
- void serverCapAcknowledged(const QString &capability);
+ void serverCapAcknowledged(const QString& capability);
/**
* Indicates a capability was removed from the list of available capabilities.
*
* @param[in] capability Name of the capability
*/
- void serverCapRemoved(const QString &capability);
+ void serverCapRemoved(const QString& capability);
/**
* Sends the next capability from the queue.
*
* @param[in] name Channel or nickname
*/
- void queueAutoWhoOneshot(const QString &name);
+ void queueAutoWhoOneshot(const QString& name);
/**
* Checks if the given target has an automatic WHO in progress, and sets it as done if so
* @param name Channel or nickname
* @return True if an automatic WHO is in progress (and should be silenced), otherwise false
*/
- bool setAutoWhoDone(const QString &name);
+ bool setAutoWhoDone(const QString& name);
- void updateIssuedModes(const QString &requestedModes);
+ void updateIssuedModes(const QString& requestedModes);
void updatePersistentModes(QString addModes, QString removeModes);
void resetPersistentModes();
*/
inline void resetPongReplyPending() { _pongReplyPending = false; }
- void onDisplayMsg(Message::Type msgType, BufferInfo::Type bufferType, const QString &target, const QString &text, const QString &sender, Message::Flags flags)
+ void onDisplayMsg(Message::Type msgType,
+ BufferInfo::Type bufferType,
+ const QString& target,
+ const QString& text,
+ const QString& sender,
+ Message::Flags flags)
{
emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
}
-
signals:
void recvRawServerMsg(QString);
void displayStatusMsg(QString);
- void displayMsg(NetworkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender, Message::Flags flags);
+ void displayMsg(
+ NetworkId, Message::Type, BufferInfo::Type, const QString& target, const QString& text, const QString& sender, Message::Flags flags);
void disconnected(NetworkId networkId);
- void connectionError(const QString &errorMsg);
+ void connectionError(const QString& errorMsg);
void quitRequested(NetworkId networkId);
- void sslErrors(const QVariant &errorData);
-
- void newEvent(Event *event);
- void socketInitialized(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId);
- void socketDisconnected(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId);
+ void sslErrors(const QVariant& errorData);
+
+ void newEvent(Event* event);
+ void socketInitialized(const CoreIdentity* identity,
+ const QHostAddress& localAddress,
+ quint16 localPort,
+ const QHostAddress& peerAddress,
+ quint16 peerPort,
+ qint64 socketId);
+ void socketDisconnected(const CoreIdentity* identity,
+ const QHostAddress& localAddress,
+ quint16 localPort,
+ const QHostAddress& peerAddress,
+ quint16 peerPort,
+ qint64 socketId);
protected:
- inline IrcChannel *ircChannelFactory(const QString &channelname) override { return new CoreIrcChannel(channelname, this); }
- inline IrcUser *ircUserFactory(const QString &hostmask) override { return new CoreIrcUser(hostmask, this); }
+ inline IrcChannel* ircChannelFactory(const QString& channelname) override { return new CoreIrcChannel(channelname, this); }
+ inline IrcUser* ircUserFactory(const QString& hostmask) override { return new CoreIrcUser(hostmask, this); }
protected slots:
// TODO: remove cached cipher keys, when appropriate
- //virtual void removeIrcUser(IrcUser *ircuser);
- //virtual void removeIrcChannel(IrcChannel *ircChannel);
- //virtual void removeChansAndUsers();
+ // virtual void removeIrcUser(IrcUser *ircuser);
+ // virtual void removeIrcChannel(IrcChannel *ircChannel);
+ // virtual void removeChansAndUsers();
private slots:
void onSocketHasData();
void startAutoWhoCycle();
#ifdef HAVE_SSL
- void onSslErrors(const QList<QSslError> &errors);
+ void onSslErrors(const QList<QSslError>& errors);
#endif
/**
*/
void fillBucketAndProcessQueue();
- void writeToSocket(const QByteArray &data);
+ void writeToSocket(const QByteArray& data);
private:
void showMessage(Message::Type msgType,
BufferInfo::Type bufferType,
- const QString &target,
- const QString &text,
- const QString &sender = "",
+ const QString& target,
+ const QString& text,
+ const QString& sender = "",
Message::Flags flags = Message::None)
{
emit displayMsg(networkId(), msgType, bufferType, target, text, sender, flags);
}
private:
- CoreSession *_coreSession;
+ CoreSession* _coreSession;
- bool _debugLogRawIrc; ///< If true, include raw IRC socket messages in the debug log
- qint32 _debugLogRawNetId; ///< Network ID for logging raw IRC socket messages, or -1 for all
+ bool _debugLogRawIrc; ///< If true, include raw IRC socket messages in the debug log
+ qint32 _debugLogRawNetId; ///< Network ID for logging raw IRC socket messages, or -1 for all
#ifdef HAVE_SSL
QSslSocket socket;
#endif
qint64 _socketId{0};
- CoreUserInputHandler *_userInputHandler;
+ CoreUserInputHandler* _userInputHandler;
- QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
+ QHash<QString, QString> _channelKeys; // stores persistent channels and their passwords, if any
QTimer _autoReconnectTimer;
int _autoReconnectCount;
bool _pongTimestampValid = false; ///< If true, IRC server responds to PING by quoting in PONG
// This tracks whether or not a server responds to PING with a PONG of what was sent, or if it
// does something else. If false, PING reply hiding should be more aggressive.
- bool _pongReplyPending = false; ///< If true, at least one PING sent without a PONG reply
+ bool _pongReplyPending = false; ///< If true, at least one PING sent without a PONG reply
QStringList _autoWhoQueue;
QHash<QString, int> _autoWhoPending;
// If this happens, we need a way to retry each capability individually in order to avoid having
// one failing capability (e.g. SASL) block all other capabilities.
- bool _capNegotiationActive; /// Whether or not full capability negotiation was started
+ bool _capNegotiationActive; /// Whether or not full capability negotiation was started
// Avoid displaying repeat "negotiation finished" messages
- bool _capInitialNegotiationEnded; /// Whether or not initial capability negotiation finished
+ bool _capInitialNegotiationEnded; /// Whether or not initial capability negotiation finished
// Avoid sending repeat "CAP END" replies when registration is already ended
/**
QTimer _tokenBucketTimer;
// No need for int type as one cannot travel into the past (at least not yet, Doc)
- quint32 _messageDelay; /// Token refill speed in ms
- quint32 _burstSize; /// Size of the token bucket
- quint32 _tokenBucket; /// The virtual bucket that holds the tokens
- QList<QByteArray> _msgQueue; /// Queue of messages waiting to be sent
- bool _skipMessageRates; /// If true, skip all message rate limits
+ quint32 _messageDelay; /// Token refill speed in ms
+ quint32 _burstSize; /// Size of the token bucket
+ quint32 _tokenBucket; /// The virtual bucket that holds the tokens
+ QList<QByteArray> _msgQueue; /// Queue of messages waiting to be sent
+ bool _skipMessageRates; /// If true, skip all message rate limits
- QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
+ QString _requestedUserModes; // 2 strings separated by a '-' character. first part are requested modes to add, the second to remove
// List of blowfish keys for channels
QHash<QString, QByteArray> _cipherKeys;
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "corenetworkconfig.h"
+
#include "core.h"
#include "coresession.h"
-#include "corenetworkconfig.h"
-CoreNetworkConfig::CoreNetworkConfig(const QString &objectName, CoreSession *session)
+CoreNetworkConfig::CoreNetworkConfig(const QString& objectName, CoreSession* session)
: NetworkConfig(objectName, session)
{
setAllowClientUpdates(true);
fromVariantMap(Core::getUserSetting(session->user(), objectName).toMap());
}
-
void CoreNetworkConfig::save()
{
- auto *session = qobject_cast<CoreSession *>(parent());
+ auto* session = qobject_cast<CoreSession*>(parent());
if (!session) {
qWarning() << Q_FUNC_INFO << "No CoreSession set, cannot save network configuration!";
return;
Q_OBJECT
public:
- CoreNetworkConfig(const QString &objectName, CoreSession *parent);
+ CoreNetworkConfig(const QString& objectName, CoreSession* parent);
void save();
#include <QtScript>
#include "core.h"
-#include "coreuserinputhandler.h"
-#include "corebuffersyncer.h"
#include "corebacklogmanager.h"
+#include "corebuffersyncer.h"
#include "corebufferviewmanager.h"
#include "coredccconfig.h"
#include "coreeventmanager.h"
#include "corenetworkconfig.h"
#include "coresessioneventprocessor.h"
#include "coretransfermanager.h"
+#include "coreuserinputhandler.h"
#include "coreusersettings.h"
#include "ctcpparser.h"
#include "eventstringifier.h"
#include "storage.h"
#include "util.h"
-
class ProcessMessagesEvent : public QEvent
{
public:
- ProcessMessagesEvent() : QEvent(QEvent::User) {}
+ ProcessMessagesEvent()
+ : QEvent(QEvent::User)
+ {}
};
-
-CoreSession::CoreSession(UserId uid, bool restoreState, bool strictIdentEnabled, QObject *parent)
- : QObject(parent),
- _user(uid),
- _strictIdentEnabled(strictIdentEnabled),
- _signalProxy(new SignalProxy(SignalProxy::Server, this)),
- _aliasManager(this),
- _bufferSyncer(new CoreBufferSyncer(this)),
- _backlogManager(new CoreBacklogManager(this)),
- _bufferViewManager(new CoreBufferViewManager(_signalProxy, this)),
- _dccConfig(new CoreDccConfig(this)),
- _ircListHelper(new CoreIrcListHelper(this)),
- _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this)),
- _coreInfo(new CoreInfo(this)),
- _transferManager(new CoreTransferManager(this)),
- _eventManager(new CoreEventManager(this)),
- _eventStringifier(new EventStringifier(this)),
- _sessionEventProcessor(new CoreSessionEventProcessor(this)),
- _ctcpParser(new CtcpParser(this)),
- _ircParser(new IrcParser(this)),
- scriptEngine(new QScriptEngine(this)),
- _processMessages(false),
- _ignoreListManager(this),
- _highlightRuleManager(this)
-{
- SignalProxy *p = signalProxy();
+CoreSession::CoreSession(UserId uid, bool restoreState, bool strictIdentEnabled, QObject* parent)
+ : QObject(parent)
+ , _user(uid)
+ , _strictIdentEnabled(strictIdentEnabled)
+ , _signalProxy(new SignalProxy(SignalProxy::Server, this))
+ , _aliasManager(this)
+ , _bufferSyncer(new CoreBufferSyncer(this))
+ , _backlogManager(new CoreBacklogManager(this))
+ , _bufferViewManager(new CoreBufferViewManager(_signalProxy, this))
+ , _dccConfig(new CoreDccConfig(this))
+ , _ircListHelper(new CoreIrcListHelper(this))
+ , _networkConfig(new CoreNetworkConfig("GlobalNetworkConfig", this))
+ , _coreInfo(new CoreInfo(this))
+ , _transferManager(new CoreTransferManager(this))
+ , _eventManager(new CoreEventManager(this))
+ , _eventStringifier(new EventStringifier(this))
+ , _sessionEventProcessor(new CoreSessionEventProcessor(this))
+ , _ctcpParser(new CtcpParser(this))
+ , _ircParser(new IrcParser(this))
+ , scriptEngine(new QScriptEngine(this))
+ , _processMessages(false)
+ , _ignoreListManager(this)
+ , _highlightRuleManager(this)
+{
+ SignalProxy* p = signalProxy();
p->setHeartBeatInterval(30);
- p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
+ p->setMaxHeartBeatCount(60); // 30 mins until we throw a dead socket out
connect(p, &SignalProxy::peerRemoved, this, &CoreSession::removeClient);
p->attachSignal(this, SIGNAL(displayMsg(Message)));
p->attachSignal(this, SIGNAL(displayStatusMsg(QString, QString)));
- p->attachSignal(this, SIGNAL(identityCreated(const Identity &)));
+ p->attachSignal(this, SIGNAL(identityCreated(const Identity&)));
p->attachSignal(this, SIGNAL(identityRemoved(IdentityId)));
- p->attachSlot(SIGNAL(createIdentity(const Identity &, const QVariantMap &)), this, SLOT(createIdentity(const Identity &, const QVariantMap &)));
+ p->attachSlot(SIGNAL(createIdentity(const Identity&, const QVariantMap&)),
+ this,
+ SLOT(createIdentity(const Identity&, const QVariantMap&)));
p->attachSlot(SIGNAL(removeIdentity(IdentityId)), this, SLOT(removeIdentity(IdentityId)));
p->attachSignal(this, SIGNAL(networkCreated(NetworkId)));
p->attachSignal(this, SIGNAL(networkRemoved(NetworkId)));
- p->attachSlot(SIGNAL(createNetwork(const NetworkInfo &, const QStringList &)), this, SLOT(createNetwork(const NetworkInfo &, const QStringList &)));
+ p->attachSlot(SIGNAL(createNetwork(const NetworkInfo&, const QStringList&)),
+ this,
+ SLOT(createNetwork(const NetworkInfo&, const QStringList&)));
p->attachSlot(SIGNAL(removeNetwork(NetworkId)), this, SLOT(removeNetwork(NetworkId)));
- p->attachSlot(SIGNAL(changePassword(PeerPtr,QString,QString,QString)), this, SLOT(changePassword(PeerPtr,QString,QString,QString)));
- p->attachSignal(this, SIGNAL(passwordChanged(PeerPtr,bool)));
+ p->attachSlot(SIGNAL(changePassword(PeerPtr, QString, QString, QString)), this, SLOT(changePassword(PeerPtr, QString, QString, QString)));
+ p->attachSignal(this, SIGNAL(passwordChanged(PeerPtr, bool)));
p->attachSlot(SIGNAL(kickClient(int)), this, SLOT(kickClient(int)));
p->attachSignal(this, SIGNAL(disconnectFromCore()));
QVariantMap data;
data["quasselVersion"] = Quassel::buildInfo().fancyVersionString;
- data["quasselBuildDate"] = Quassel::buildInfo().commitDate; // "BuildDate" for compatibility
+ data["quasselBuildDate"] = Quassel::buildInfo().commitDate; // "BuildDate" for compatibility
data["startTime"] = Core::instance()->startTime();
data["sessionConnectedClients"] = 0;
_coreInfo->setCoreData(data);
initScriptEngine();
eventManager()->registerObject(ircParser(), EventManager::NormalPriority);
- eventManager()->registerObject(sessionEventProcessor(), EventManager::HighPriority); // needs to process events *before* the stringifier!
+ eventManager()->registerObject(sessionEventProcessor(), EventManager::HighPriority); // needs to process events *before* the stringifier!
eventManager()->registerObject(ctcpParser(), EventManager::NormalPriority);
eventManager()->registerObject(eventStringifier(), EventManager::NormalPriority);
- eventManager()->registerObject(this, EventManager::LowPriority); // for sending MessageEvents to the client
+ eventManager()->registerObject(this, EventManager::LowPriority); // for sending MessageEvents to the client
// some events need to be handled after msg generation
eventManager()->registerObject(sessionEventProcessor(), EventManager::LowPriority, "lateProcess");
eventManager()->registerObject(ctcpParser(), EventManager::LowPriority, "send");
p->synchronize(&_ignoreListManager);
p->synchronize(&_highlightRuleManager);
// Listen to network removed events
- connect(this, &CoreSession::networkRemoved,
- &_highlightRuleManager, &HighlightRuleManager::networkRemoved);
+ connect(this, &CoreSession::networkRemoved, &_highlightRuleManager, &HighlightRuleManager::networkRemoved);
p->synchronize(transferManager());
// Restore session state
if (restoreState)
emit initialized();
}
-
void CoreSession::shutdown()
{
saveSessionState();
// Request disconnect from all connected networks in parallel, and wait until every network
// has emitted the disconnected() signal before deleting the session itself
- for (CoreNetwork *net : _networks.values()) {
+ for (CoreNetwork* net : _networks.values()) {
if (net->socketState() != QAbstractSocket::UnconnectedState) {
_networksPendingDisconnect.insert(net->networkId());
connect(net, &CoreNetwork::disconnected, this, &CoreSession::onNetworkDisconnected);
}
}
-
void CoreSession::onNetworkDisconnected(NetworkId networkId)
{
_networksPendingDisconnect.remove(networkId);
}
}
-
-CoreNetwork *CoreSession::network(NetworkId id) const
+CoreNetwork* CoreSession::network(NetworkId id) const
{
- if (_networks.contains(id)) return _networks[id];
+ if (_networks.contains(id))
+ return _networks[id];
return nullptr;
}
-
-CoreIdentity *CoreSession::identity(IdentityId id) const
+CoreIdentity* CoreSession::identity(IdentityId id) const
{
- if (_identities.contains(id)) return _identities[id];
+ if (_identities.contains(id))
+ return _identities[id];
return nullptr;
}
-
void CoreSession::loadSettings()
{
CoreUserSettings s(user());
// migrate to db
QList<IdentityId> ids = s.identityIds();
QList<NetworkInfo> networkInfos = Core::networks(user());
- foreach(IdentityId id, ids) {
+ foreach (IdentityId id, ids) {
CoreIdentity identity(s.identity(id));
IdentityId newId = Core::createIdentity(user(), identity);
QList<NetworkInfo>::iterator networkIter = networkInfos.begin();
}
// end of migration
- foreach(CoreIdentity identity, Core::identities(user())) {
+ foreach (CoreIdentity identity, Core::identities(user())) {
createIdentity(identity);
}
- foreach(NetworkInfo info, Core::networks(user())) {
+ foreach (NetworkInfo info, Core::networks(user())) {
createNetwork(info);
}
}
-
void CoreSession::saveSessionState() const
{
_bufferSyncer->storeDirtyIds();
_networkConfig->save();
}
-
void CoreSession::restoreSessionState()
{
QList<NetworkId> nets = Core::connectedNetworks(user());
- CoreNetwork *net = nullptr;
- foreach(NetworkId id, nets) {
+ CoreNetwork* net = nullptr;
+ foreach (NetworkId id, nets) {
net = network(id);
Q_ASSERT(net);
net->connectToIrc();
}
}
-
-void CoreSession::addClient(RemotePeer *peer)
+void CoreSession::addClient(RemotePeer* peer)
{
signalProxy()->setTargetPeer(peer);
signalProxy()->setTargetPeer(nullptr);
}
-
-void CoreSession::addClient(InternalPeer *peer)
+void CoreSession::addClient(InternalPeer* peer)
{
signalProxy()->addPeer(peer);
emit sessionStateReceived(sessionState());
}
-
-void CoreSession::removeClient(Peer *peer)
+void CoreSession::removeClient(Peer* peer)
{
- auto *p = qobject_cast<RemotePeer *>(peer);
+ auto* p = qobject_cast<RemotePeer*>(peer);
if (p)
quInfo() << qPrintable(tr("Client")) << p->description() << qPrintable(tr("disconnected (UserId: %1).").arg(user().toInt()));
_coreInfo->setConnectedClientData(signalProxy()->peerCount(), signalProxy()->peerData());
}
-
QHash<QString, QString> CoreSession::persistentChannels(NetworkId id) const
{
return Core::persistentChannels(user(), id);
}
-
QHash<QString, QByteArray> CoreSession::bufferCiphers(NetworkId id) const
{
return Core::bufferCiphers(user(), id);
}
-void CoreSession::setBufferCipher(NetworkId id, const QString &bufferName, const QByteArray &cipher) const
+void CoreSession::setBufferCipher(NetworkId id, const QString& bufferName, const QByteArray& cipher) const
{
Core::setBufferCipher(user(), id, bufferName, cipher);
}
-
// FIXME switch to BufferId
void CoreSession::msgFromClient(BufferInfo bufinfo, QString msg)
{
- CoreNetwork *net = network(bufinfo.networkId());
+ CoreNetwork* net = network(bufinfo.networkId());
if (net) {
net->userInput(bufinfo, msg);
}
}
}
-
// ALL messages coming pass through these functions before going to the GUI.
// So this is the perfect place for storing the backlog and log stuff.
-void CoreSession::recvMessageFromServer(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType,
- const QString &target, const QString &text_, const QString &sender, Message::Flags flags)
+void CoreSession::recvMessageFromServer(NetworkId networkId,
+ Message::Type type,
+ BufferInfo::Type bufferType,
+ const QString& target,
+ const QString& text_,
+ const QString& sender,
+ Message::Flags flags)
{
// U+FDD0 and U+FDD1 are special characters for Qt's text engine, specifically they mark the boundaries of
// text frames in a QTextDocument. This might lead to problems in widgets displaying QTextDocuments (such as
RawMessage rawMsg(networkId, type, bufferType, target, text, sender, flags);
// check for HardStrictness ignore
- CoreNetwork *currentNetwork = network(networkId);
+ CoreNetwork* currentNetwork = network(networkId);
QString networkName = currentNetwork ? currentNetwork->networkName() : QString("");
if (_ignoreListManager.match(rawMsg, networkName) == IgnoreListManager::HardStrictness)
return;
-
if (currentNetwork && _highlightRuleManager.match(rawMsg, currentNetwork->myNick(), currentNetwork->identityPtr()->nicks()))
rawMsg.flags |= Message::Flag::Highlight;
}
}
-
void CoreSession::recvStatusMsgFromServer(QString msg)
{
- auto *net = qobject_cast<CoreNetwork *>(sender());
+ auto* net = qobject_cast<CoreNetwork*>(sender());
Q_ASSERT(net);
emit displayStatusMsg(net->networkName(), msg);
}
-
-void CoreSession::processMessageEvent(MessageEvent *event)
+void CoreSession::processMessageEvent(MessageEvent* event)
{
- recvMessageFromServer(event->networkId(), event->msgType(), event->bufferType(),
- event->target().isNull() ? "" : event->target(),
- event->text().isNull() ? "" : event->text(),
- event->sender().isNull() ? "" : event->sender(),
- event->msgFlags());
+ recvMessageFromServer(event->networkId(),
+ event->msgType(),
+ event->bufferType(),
+ event->target().isNull() ? "" : event->target(),
+ event->text().isNull() ? "" : event->text(),
+ event->sender().isNull() ? "" : event->sender(),
+ event->msgFlags());
}
-
QList<BufferInfo> CoreSession::buffers() const
{
return Core::requestBuffers(user());
}
-
-void CoreSession::customEvent(QEvent *event)
+void CoreSession::customEvent(QEvent* event)
{
if (event->type() != QEvent::User)
return;
event->accept();
}
-
void CoreSession::processMessages()
{
if (_messageQueue.count() == 1) {
- const RawMessage &rawMsg = _messageQueue.first();
+ const RawMessage& rawMsg = _messageQueue.first();
bool createBuffer = !(rawMsg.flags & Message::Redirected);
BufferInfo bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, rawMsg.bufferType, rawMsg.target, createBuffer);
if (!bufferInfo.isValid()) {
Q_ASSERT(!createBuffer);
bufferInfo = Core::bufferInfo(user(), rawMsg.networkId, BufferInfo::StatusBuffer, "");
}
- Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, senderPrefixes(rawMsg.sender, bufferInfo),
- realName(rawMsg.sender, rawMsg.networkId), avatarUrl(rawMsg.sender, rawMsg.networkId),
+ Message msg(bufferInfo,
+ rawMsg.type,
+ rawMsg.text,
+ rawMsg.sender,
+ senderPrefixes(rawMsg.sender, bufferInfo),
+ realName(rawMsg.sender, rawMsg.networkId),
+ avatarUrl(rawMsg.sender, rawMsg.networkId),
rawMsg.flags);
- if(Core::storeMessage(msg))
+ if (Core::storeMessage(msg))
emit displayMsg(msg);
}
else {
- QHash<NetworkId, QHash<QString, BufferInfo> > bufferInfoCache;
+ QHash<NetworkId, QHash<QString, BufferInfo>> bufferInfoCache;
MessageList messages;
- QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
+ QList<RawMessage> redirectedMessages; // list of Messages which don't enforce a buffer creation
BufferInfo bufferInfo;
for (int i = 0; i < _messageQueue.count(); i++) {
- const RawMessage &rawMsg = _messageQueue.at(i);
+ const RawMessage& rawMsg = _messageQueue.at(i);
if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
}
}
bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
}
- Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, senderPrefixes(rawMsg.sender, bufferInfo),
- realName(rawMsg.sender, rawMsg.networkId), avatarUrl(rawMsg.sender, rawMsg.networkId),
+ Message msg(bufferInfo,
+ rawMsg.type,
+ rawMsg.text,
+ rawMsg.sender,
+ senderPrefixes(rawMsg.sender, bufferInfo),
+ realName(rawMsg.sender, rawMsg.networkId),
+ avatarUrl(rawMsg.sender, rawMsg.networkId),
rawMsg.flags);
messages << msg;
}
// recheck if there exists a buffer to store a redirected message in
for (int i = 0; i < redirectedMessages.count(); i++) {
- const RawMessage &rawMsg = redirectedMessages.at(i);
+ const RawMessage& rawMsg = redirectedMessages.at(i);
if (bufferInfoCache.contains(rawMsg.networkId) && bufferInfoCache[rawMsg.networkId].contains(rawMsg.target)) {
bufferInfo = bufferInfoCache[rawMsg.networkId][rawMsg.target];
}
// add the StatusBuffer to the Cache in case there are more Messages for the original target
bufferInfoCache[rawMsg.networkId][rawMsg.target] = bufferInfo;
}
- Message msg(bufferInfo, rawMsg.type, rawMsg.text, rawMsg.sender, senderPrefixes(rawMsg.sender, bufferInfo),
- realName(rawMsg.sender, rawMsg.networkId), avatarUrl(rawMsg.sender, rawMsg.networkId),
+ Message msg(bufferInfo,
+ rawMsg.type,
+ rawMsg.text,
+ rawMsg.sender,
+ senderPrefixes(rawMsg.sender, bufferInfo),
+ realName(rawMsg.sender, rawMsg.networkId),
+ avatarUrl(rawMsg.sender, rawMsg.networkId),
rawMsg.flags);
messages << msg;
}
- if(Core::storeMessages(messages)) {
+ if (Core::storeMessages(messages)) {
// FIXME: extend protocol to a displayMessages(MessageList)
for (int i = 0; i < messages.count(); i++) {
emit displayMsg(messages[i]);
_messageQueue.clear();
}
-QString CoreSession::senderPrefixes(const QString &sender, const BufferInfo &bufferInfo) const
+QString CoreSession::senderPrefixes(const QString& sender, const BufferInfo& bufferInfo) const
{
- CoreNetwork *currentNetwork = network(bufferInfo.networkId());
+ CoreNetwork* currentNetwork = network(bufferInfo.networkId());
if (!currentNetwork) {
return {};
}
return {};
}
- IrcChannel *currentChannel = currentNetwork->ircChannel(bufferInfo.bufferName());
+ IrcChannel* currentChannel = currentNetwork->ircChannel(bufferInfo.bufferName());
if (!currentChannel) {
return {};
}
return currentNetwork->modesToPrefixes(modes);
}
-QString CoreSession::realName(const QString &sender, NetworkId networkId) const
+QString CoreSession::realName(const QString& sender, NetworkId networkId) const
{
- CoreNetwork *currentNetwork = network(networkId);
+ CoreNetwork* currentNetwork = network(networkId);
if (!currentNetwork) {
return {};
}
- IrcUser *currentUser = currentNetwork->ircUser(nickFromMask(sender));
+ IrcUser* currentUser = currentNetwork->ircUser(nickFromMask(sender));
if (!currentUser) {
return {};
}
return currentUser->realName();
}
-QString CoreSession::avatarUrl(const QString &sender, NetworkId networkId) const
+QString CoreSession::avatarUrl(const QString& sender, NetworkId networkId) const
{
Q_UNUSED(sender);
Q_UNUSED(networkId);
QVariantList networkIds;
QVariantList identities;
- foreach(const BufferInfo &id, buffers())
+ foreach (const BufferInfo& id, buffers())
bufferInfos << QVariant::fromValue(id);
- foreach(const NetworkId &id, _networks.keys())
+ foreach (const NetworkId& id, _networks.keys())
networkIds << QVariant::fromValue(id);
- foreach(const Identity *i, _identities.values())
+ foreach (const Identity* i, _identities.values())
identities << QVariant::fromValue(*i);
return Protocol::SessionState(identities, bufferInfos, networkIds);
}
-
void CoreSession::initScriptEngine()
{
signalProxy()->attachSlot(SIGNAL(scriptRequest(QString)), this, SLOT(scriptRequest(QString)));
signalProxy()->attachSignal(this, SIGNAL(scriptResult(QString)));
// FIXME
- //QScriptValue storage_ = scriptEngine->newQObject(storage);
- //scriptEngine->globalObject().setProperty("storage", storage_);
+ // QScriptValue storage_ = scriptEngine->newQObject(storage);
+ // scriptEngine->globalObject().setProperty("storage", storage_);
}
-
void CoreSession::scriptRequest(QString script)
{
emit scriptResult(scriptEngine->evaluate(script).toString());
}
-
/*** Identity Handling ***/
-void CoreSession::createIdentity(const Identity &identity, const QVariantMap &additional)
+void CoreSession::createIdentity(const Identity& identity, const QVariantMap& additional)
{
#ifndef HAVE_SSL
Q_UNUSED(additional)
createIdentity(coreIdentity);
}
-const QString CoreSession::strictCompliantIdent(const CoreIdentity *identity) {
+const QString CoreSession::strictCompliantIdent(const CoreIdentity* identity)
+{
if (_strictIdentEnabled) {
// Strict mode enabled: only allow the user's Quassel username as an ident
return Core::instance()->strictSysIdent(_user);
- } else {
+ }
+ else {
// Strict mode disabled: allow any identity specified
return identity->ident();
}
}
-void CoreSession::createIdentity(const CoreIdentity &identity)
+void CoreSession::createIdentity(const CoreIdentity& identity)
{
- auto *coreIdentity = new CoreIdentity(identity, this);
+ auto* coreIdentity = new CoreIdentity(identity, this);
_identities[identity.id()] = coreIdentity;
// CoreIdentity has its own synchronize method since its "private" sslManager needs to be synced as well
coreIdentity->synchronize(signalProxy());
emit identityCreated(*coreIdentity);
}
-
void CoreSession::updateIdentityBySender()
{
- auto *identity = qobject_cast<CoreIdentity *>(sender());
+ auto* identity = qobject_cast<CoreIdentity*>(sender());
if (!identity)
return;
Core::updateIdentity(user(), *identity);
}
-
void CoreSession::removeIdentity(IdentityId id)
{
- CoreIdentity *identity = _identities.take(id);
+ CoreIdentity* identity = _identities.take(id);
if (identity) {
emit identityRemoved(id);
Core::removeIdentity(user(), id);
}
}
-
/*** Network Handling ***/
-void CoreSession::createNetwork(const NetworkInfo &info_, const QStringList &persistentChans)
+void CoreSession::createNetwork(const NetworkInfo& info_, const QStringList& persistentChans)
{
NetworkInfo info = info_;
int id;
Core::createNetwork(user(), info);
if (!info.networkId.isValid()) {
- qWarning() << qPrintable(tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
+ qWarning() << qPrintable(
+ tr("CoreSession::createNetwork(): Got invalid networkId from Core when trying to create network %1!").arg(info.networkName));
return;
}
if (!_networks.contains(id)) {
// create persistent chans
QRegExp rx(R"(\s*(\S+)(?:\s*(\S+))?\s*)");
- foreach(QString channel, persistentChans) {
+ foreach (QString channel, persistentChans) {
if (!rx.exactMatch(channel)) {
qWarning() << QString("Invalid persistent channel declaration: %1").arg(channel);
continue;
Core::setPersistentChannelKey(user(), info.networkId, rx.cap(1), rx.cap(2));
}
- CoreNetwork *net = new CoreNetwork(id, this);
+ CoreNetwork* net = new CoreNetwork(id, this);
connect(net, &CoreNetwork::displayMsg, this, &CoreSession::recvMessageFromServer);
connect(net, &CoreNetwork::displayStatusMsg, this, &CoreSession::recvStatusMsgFromServer);
connect(net, &CoreNetwork::disconnected, this, &CoreSession::networkDisconnected);
}
}
-
void CoreSession::removeNetwork(NetworkId id)
{
// Make sure the network is disconnected!
- CoreNetwork *net = network(id);
+ CoreNetwork* net = network(id);
if (!net)
return;
}
}
-
void CoreSession::destroyNetwork(NetworkId id)
{
QList<BufferId> removedBuffers = Core::requestBufferIdsForNetwork(user(), id);
- Network *net = _networks.take(id);
+ Network* net = _networks.take(id);
if (net && Core::removeNetwork(user(), id)) {
// make sure that all unprocessed RawMessages from this network are removed
QList<RawMessage>::iterator messageIter = _messageQueue.begin();
}
}
// remove buffers from syncer
- foreach(BufferId bufferId, removedBuffers) {
+ foreach (BufferId bufferId, removedBuffers) {
_bufferSyncer->removeBuffer(bufferId);
}
emit networkRemoved(id);
}
}
-
-void CoreSession::renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName)
+void CoreSession::renameBuffer(const NetworkId& networkId, const QString& newName, const QString& oldName)
{
BufferInfo bufferInfo = Core::bufferInfo(user(), networkId, BufferInfo::QueryBuffer, oldName, false);
if (bufferInfo.isValid()) {
}
}
-
void CoreSession::clientsConnected()
{
- QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
- Identity *identity = nullptr;
- CoreNetwork *net = nullptr;
- IrcUser *me = nullptr;
+ QHash<NetworkId, CoreNetwork*>::iterator netIter = _networks.begin();
+ Identity* identity = nullptr;
+ CoreNetwork* net = nullptr;
+ IrcUser* me = nullptr;
while (netIter != _networks.end()) {
net = *netIter;
++netIter;
}
}
-
void CoreSession::clientsDisconnected()
{
- QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
- Identity *identity = nullptr;
- CoreNetwork *net = nullptr;
- IrcUser *me = nullptr;
+ QHash<NetworkId, CoreNetwork*>::iterator netIter = _networks.begin();
+ Identity* identity = nullptr;
+ CoreNetwork* net = nullptr;
+ IrcUser* me = nullptr;
QString awayReason;
while (netIter != _networks.end()) {
net = *netIter;
}
}
-
-void CoreSession::globalAway(const QString &msg, const bool skipFormatting)
+void CoreSession::globalAway(const QString& msg, const bool skipFormatting)
{
- QHash<NetworkId, CoreNetwork *>::iterator netIter = _networks.begin();
- CoreNetwork *net = nullptr;
+ QHash<NetworkId, CoreNetwork*>::iterator netIter = _networks.begin();
+ CoreNetwork* net = nullptr;
while (netIter != _networks.end()) {
net = *netIter;
++netIter;
}
}
-void CoreSession::changePassword(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword) {
+void CoreSession::changePassword(PeerPtr peer, const QString& userName, const QString& oldPassword, const QString& newPassword)
+{
Q_UNUSED(peer);
bool success = false;
if (uid.isValid() && uid == user())
success = Core::changeUserPassword(uid, newPassword);
- signalProxy()->restrictTargetPeers(signalProxy()->sourcePeer(), [&]{
- emit passwordChanged(nullptr, success);
- });
+ signalProxy()->restrictTargetPeers(signalProxy()->sourcePeer(), [&] { emit passwordChanged(nullptr, success); });
}
-void CoreSession::kickClient(int peerId) {
+void CoreSession::kickClient(int peerId)
+{
auto peer = signalProxy()->peerById(peerId);
if (peer == nullptr) {
qWarning() << "Invalid peer Id: " << peerId;
return;
}
- signalProxy()->restrictTargetPeers(peer, [&]{
- emit disconnectFromCore();
- });
+ signalProxy()->restrictTargetPeers(peer, [&] { emit disconnectFromCore(); });
}
#pragma once
+#include <utility>
+
#include <QHash>
#include <QSet>
#include <QString>
#include <QVariant>
-#include <utility>
-#include "coreinfo.h"
#include "corealiasmanager.h"
#include "corehighlightrulemanager.h"
#include "coreignorelistmanager.h"
+#include "coreinfo.h"
+#include "message.h"
#include "peer.h"
#include "protocol.h"
-#include "message.h"
#include "storage.h"
class CoreBacklogManager;
Q_OBJECT
public:
- CoreSession(UserId, bool restoreState, bool strictIdentEnabled, QObject *parent = nullptr);
+ CoreSession(UserId, bool restoreState, bool strictIdentEnabled, QObject* parent = nullptr);
QList<BufferInfo> buffers() const;
inline UserId user() const { return _user; }
- CoreNetwork *network(NetworkId) const;
- CoreIdentity *identity(IdentityId) const;
+ CoreNetwork* network(NetworkId) const;
+ CoreIdentity* identity(IdentityId) const;
/**
* Returns the optionally strict-compliant ident for the given user identity
*
* @return The user's ident, compliant with strict mode (when enabled)
*/
- const QString strictCompliantIdent(const CoreIdentity *identity);
+ const QString strictCompliantIdent(const CoreIdentity* identity);
- inline CoreNetworkConfig *networkConfig() const { return _networkConfig; }
- NetworkConnection *networkConnection(NetworkId) const;
+ inline CoreNetworkConfig* networkConfig() const { return _networkConfig; }
+ NetworkConnection* networkConnection(NetworkId) const;
Protocol::SessionState sessionState() const;
- inline SignalProxy *signalProxy() const { return _signalProxy; }
+ inline SignalProxy* signalProxy() const { return _signalProxy; }
- const AliasManager &aliasManager() const { return _aliasManager; }
- AliasManager &aliasManager() { return _aliasManager; }
+ const AliasManager& aliasManager() const { return _aliasManager; }
+ AliasManager& aliasManager() { return _aliasManager; }
- inline EventManager *eventManager() const { return _eventManager; }
- inline EventStringifier *eventStringifier() const { return _eventStringifier; }
- inline CoreSessionEventProcessor *sessionEventProcessor() const { return _sessionEventProcessor; }
- inline CtcpParser *ctcpParser() const { return _ctcpParser; }
- inline IrcParser *ircParser() const { return _ircParser; }
+ inline EventManager* eventManager() const { return _eventManager; }
+ inline EventStringifier* eventStringifier() const { return _eventStringifier; }
+ inline CoreSessionEventProcessor* sessionEventProcessor() const { return _sessionEventProcessor; }
+ inline CtcpParser* ctcpParser() const { return _ctcpParser; }
+ inline IrcParser* ircParser() const { return _ircParser; }
- inline CoreIrcListHelper *ircListHelper() const { return _ircListHelper; }
+ inline CoreIrcListHelper* ircListHelper() const { return _ircListHelper; }
- inline CoreIgnoreListManager *ignoreListManager() { return &_ignoreListManager; }
- inline HighlightRuleManager *highlightRuleManager() { return &_highlightRuleManager; }
- inline CoreTransferManager *transferManager() const { return _transferManager; }
- inline CoreDccConfig *dccConfig() const { return _dccConfig; }
+ inline CoreIgnoreListManager* ignoreListManager() { return &_ignoreListManager; }
+ inline HighlightRuleManager* highlightRuleManager() { return &_highlightRuleManager; }
+ inline CoreTransferManager* transferManager() const { return _transferManager; }
+ inline CoreDccConfig* dccConfig() const { return _dccConfig; }
-// void attachNetworkConnection(NetworkConnection *conn);
+ // void attachNetworkConnection(NetworkConnection *conn);
//! Return necessary data for restoring the session after restarting the core
void restoreSessionState();
public slots:
- void addClient(RemotePeer *peer);
- void addClient(InternalPeer *peer);
+ void addClient(RemotePeer* peer);
+ void addClient(InternalPeer* peer);
/**
* Shuts down the session and deletes itself afterwards.
//! Create an identity and propagate the changes to the clients.
/** \param identity The identity to be created.
*/
- void createIdentity(const Identity &identity, const QVariantMap &additional);
- void createIdentity(const CoreIdentity &identity);
+ void createIdentity(const Identity& identity, const QVariantMap& additional);
+ void createIdentity(const CoreIdentity& identity);
//! Remove identity and propagate that fact to the clients.
/** \param identity The identity to be removed.
//! Create a network and propagate the changes to the clients.
/** \param info The network's settings.
*/
- void createNetwork(const NetworkInfo &info, const QStringList &persistentChannels = QStringList());
+ void createNetwork(const NetworkInfo& info, const QStringList& persistentChannels = QStringList());
//! Remove network and propagate that fact to the clients.
/** \param network The id of the network to be removed.
* \param newName The new name of the buffer
* \param oldName The old name of the buffer
*/
- void renameBuffer(const NetworkId &networkId, const QString &newName, const QString &oldName);
+ void renameBuffer(const NetworkId& networkId, const QString& newName, const QString& oldName);
- void changePassword(PeerPtr peer, const QString &userName, const QString &oldPassword, const QString &newPassword);
+ void changePassword(PeerPtr peer, const QString& userName, const QString& oldPassword, const QString& newPassword);
void kickClient(int peerId);
QHash<QString, QString> persistentChannels(NetworkId) const;
QHash<QString, QByteArray> bufferCiphers(NetworkId id) const;
- void setBufferCipher(NetworkId id, const QString &bufferName, const QByteArray &cipher) const;
+ void setBufferCipher(NetworkId id, const QString& bufferName, const QByteArray& cipher) const;
/**
* Marks us away (or unaway) on all networks
* @param[in] msg Away message, or blank to set unaway
* @param[in] skipFormatting If true, skip timestamp formatting codes (e.g. if already done)
*/
- void globalAway(const QString &msg = QString(), const bool skipFormatting = false);
+ void globalAway(const QString& msg = QString(), const bool skipFormatting = false);
signals:
void initialized();
- void sessionStateReceived(const Protocol::SessionState &sessionState);
+ void sessionStateReceived(const Protocol::SessionState& sessionState);
- //void msgFromGui(uint netid, QString buf, QString message);
+ // void msgFromGui(uint netid, QString buf, QString message);
void displayMsg(Message message);
void displayStatusMsg(QString, QString);
/** This signal is propagated to the clients to tell them that the given identity has been created.
* \param identity The new identity.
*/
- void identityCreated(const Identity &identity);
+ void identityCreated(const Identity& identity);
//! Identity has been removed.
/** This signal is propagated to the clients to inform them about the removal of the given identity.
void disconnectFromCore();
protected:
- void customEvent(QEvent *event) override;
+ void customEvent(QEvent* event) override;
private slots:
- void removeClient(Peer *peer);
+ void removeClient(Peer* peer);
void recvStatusMsgFromServer(QString msg);
- void recvMessageFromServer(NetworkId networkId, Message::Type, BufferInfo::Type, const QString &target, const QString &text, const QString &sender = "", Message::Flags flags = Message::None);
+ void recvMessageFromServer(NetworkId networkId,
+ Message::Type,
+ BufferInfo::Type,
+ const QString& target,
+ const QString& text,
+ const QString& sender = "",
+ Message::Flags flags = Message::None);
void destroyNetwork(NetworkId);
void initScriptEngine();
/// Hook for converting events to the old displayMsg() handlers
- Q_INVOKABLE void processMessageEvent(MessageEvent *event);
+ Q_INVOKABLE void processMessageEvent(MessageEvent* event);
UserId _user;
/// Whether or not strict ident mode is enabled, locking users' idents to Quassel username
bool _strictIdentEnabled;
- SignalProxy *_signalProxy;
+ SignalProxy* _signalProxy;
CoreAliasManager _aliasManager;
- QHash<IdentityId, CoreIdentity *> _identities;
- QHash<NetworkId, CoreNetwork *> _networks;
+ QHash<IdentityId, CoreIdentity*> _identities;
+ QHash<NetworkId, CoreNetwork*> _networks;
QSet<NetworkId> _networksPendingDisconnect;
- CoreBufferSyncer *_bufferSyncer;
- CoreBacklogManager *_backlogManager;
- CoreBufferViewManager *_bufferViewManager;
- CoreDccConfig *_dccConfig;
- CoreIrcListHelper *_ircListHelper;
- CoreNetworkConfig *_networkConfig;
- CoreInfo *_coreInfo;
- CoreTransferManager *_transferManager;
+ CoreBufferSyncer* _bufferSyncer;
+ CoreBacklogManager* _backlogManager;
+ CoreBufferViewManager* _bufferViewManager;
+ CoreDccConfig* _dccConfig;
+ CoreIrcListHelper* _ircListHelper;
+ CoreNetworkConfig* _networkConfig;
+ CoreInfo* _coreInfo;
+ CoreTransferManager* _transferManager;
- EventManager *_eventManager;
- EventStringifier *_eventStringifier; // should eventually move into client
- CoreSessionEventProcessor *_sessionEventProcessor;
- CtcpParser *_ctcpParser;
- IrcParser *_ircParser;
+ EventManager* _eventManager;
+ EventStringifier* _eventStringifier; // should eventually move into client
+ CoreSessionEventProcessor* _sessionEventProcessor;
+ CtcpParser* _ctcpParser;
+ IrcParser* _ircParser;
- QScriptEngine *scriptEngine;
+ QScriptEngine* scriptEngine;
/**
* This method obtains the prefixes of the message's sender within a channel, by looking up their channelmodes, and
* @param sender The hostmask of the sender
* @param bufferInfo The BufferInfo object of the buffer
*/
- QString senderPrefixes(const QString &sender, const BufferInfo &bufferInfo) const;
+ QString senderPrefixes(const QString& sender, const BufferInfo& bufferInfo) const;
/**
* This method obtains the realname of the message's sender.
* @param sender The hostmask of the sender
* @param networkId The network the user is on
*/
- QString realName(const QString &sender, NetworkId networkId) const;
+ QString realName(const QString& sender, NetworkId networkId) const;
/**
* This method obtains the avatar of the message's sender.
* @param sender The hostmask of the sender
* @param networkId The network the user is on
*/
- QString avatarUrl(const QString &sender, NetworkId networkId) const;
+ QString avatarUrl(const QString& sender, NetworkId networkId) const;
QList<RawMessage> _messageQueue;
bool _processMessages;
CoreIgnoreListManager _ignoreListManager;
CoreHighlightRuleManager _highlightRuleManager;
};
-
-struct RawMessage {
+struct RawMessage
+{
NetworkId networkId;
Message::Type type;
BufferInfo::Type bufferType;
QString text;
QString sender;
Message::Flags flags;
- RawMessage(NetworkId networkId, Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, Message::Flags flags)
- : networkId(networkId), type(type), bufferType(bufferType), target(std::move(target)), text(std::move(text)), sender(std::move(sender)), flags(flags) {}
+ RawMessage(
+ NetworkId networkId, Message::Type type, BufferInfo::Type bufferType, QString target, QString text, QString sender, Message::Flags flags)
+ : networkId(networkId)
+ , type(type)
+ , bufferType(bufferType)
+ , target(std::move(target))
+ , text(std::move(text))
+ , sender(std::move(sender))
+ , flags(flags)
+ {}
};
#include "quassel.h"
#ifdef HAVE_QCA2
-# include "keyevent.h"
+# include "keyevent.h"
#endif
// IRCv3 capabilities
#include "irccap.h"
-CoreSessionEventProcessor::CoreSessionEventProcessor(CoreSession *session)
- : BasicHandler("handleCtcp", session),
- _coreSession(session)
+CoreSessionEventProcessor::CoreSessionEventProcessor(CoreSession* session)
+ : BasicHandler("handleCtcp", session)
+ , _coreSession(session)
{
connect(coreSession(), &CoreSession::networkDisconnected, this, &CoreSessionEventProcessor::destroyNetsplits);
connect(this, &CoreSessionEventProcessor::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
}
-
-bool CoreSessionEventProcessor::checkParamCount(IrcEvent *e, int minParams)
+bool CoreSessionEventProcessor::checkParamCount(IrcEvent* e, int minParams)
{
if (e->params().count() < minParams) {
if (e->type() == EventManager::IrcEventNumeric) {
- qWarning() << "Command " << static_cast<IrcEventNumeric *>(e)->number() << " requires " << minParams << "params, got: " << e->params();
+ qWarning() << "Command " << static_cast<IrcEventNumeric*>(e)->number() << " requires " << minParams
+ << "params, got: " << e->params();
}
else {
QString name = coreSession()->eventManager()->enumName(e->type());
return true;
}
-
-void CoreSessionEventProcessor::tryNextNick(NetworkEvent *e, const QString &errnick, bool erroneus)
+void CoreSessionEventProcessor::tryNextNick(NetworkEvent* e, const QString& errnick, bool erroneus)
{
QStringList desiredNicks = coreSession()->identity(e->network()->identity())->nicks();
int nextNickIdx = desiredNicks.indexOf(errnick) + 1;
else {
if (erroneus) {
// FIXME Make this an ErrorEvent or something like that, so it's translated in the client
- MessageEvent *msgEvent = new MessageEvent(Message::Error, e->network(),
- tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"),
- QString(), QString(), Message::None, e->timestamp());
+ MessageEvent* msgEvent = new MessageEvent(Message::Error,
+ e->network(),
+ tr("No free and valid nicks in nicklist found. use: /nick <othernick> to continue"),
+ QString(),
+ QString(),
+ Message::None,
+ e->timestamp());
emit newEvent(msgEvent);
return;
}
coreNetwork(e)->putRawLine("NICK " + coreNetwork(e)->encodeServerString(nextNick));
}
-
-void CoreSessionEventProcessor::processIrcEventNumeric(IrcEventNumeric *e)
+void CoreSessionEventProcessor::processIrcEventNumeric(IrcEventNumeric* e)
{
switch (e->number()) {
// SASL authentication replies
// See: http://ircv3.net/specs/extensions/sasl-3.1.html
- //case 900: // RPL_LOGGEDIN
- //case 901: // RPL_LOGGEDOUT
+ // case 900: // RPL_LOGGEDIN
+ // case 901: // RPL_LOGGEDOUT
// Don't use 900 or 901 for updating the local hostmask. Unreal 3.2 gives it as the IP address
// even when cloaked.
// Every other reply should result in moving on
}
}
-
-void CoreSessionEventProcessor::processIrcEventAuthenticate(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventAuthenticate(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
return;
}
- CoreNetwork *net = coreNetwork(e);
+ CoreNetwork* net = coreNetwork(e);
#ifdef HAVE_SSL
if (net->identityPtr()->sslCert().isNull()) {
saslData.prepend("AUTHENTICATE ");
net->putRawLine(saslData);
#ifdef HAVE_SSL
- } else {
+ }
+ else {
net->putRawLine("AUTHENTICATE +");
}
#endif
}
-void CoreSessionEventProcessor::processIrcEventCap(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventCap(IrcEvent* e)
{
// Handle capability negotiation
// See: http://ircv3.net/specs/core/capability-negotiation-3.2.html
if (!checkParamCount(e, 2))
return;
- CoreNetwork *coreNet = coreNetwork(e);
+ CoreNetwork* coreNet = coreNetwork(e);
QString capCommand = e->params().at(1).trimmed().toUpper();
if (capCommand == "LS" || capCommand == "NEW") {
// Either we've gotten a list of capabilities, or new capabilities we may want
// Middle of multi-line reply, ignore the asterisk
capListFinished = false;
availableCaps = e->params().at(3).split(' ');
- } else {
+ }
+ else {
// Single line reply
capListFinished = true;
if (e->params().count() >= 3) {
// Some capabilities are specified, add them
availableCaps = e->params().at(2).split(' ');
- } else {
+ }
+ else {
// No capabilities available, add an empty list
availableCaps = QStringList();
}
// Begin capability requests when capability listing complete
if (capListFinished)
coreNet->beginCapNegotiation();
- } else if (capCommand == "ACK") {
+ }
+ else if (capCommand == "ACK") {
// CAP ACK requires at least 3 parameters (no empty response allowed)
if (!checkParamCount(e, 3)) {
// If an invalid reply is sent, try to continue rather than getting stuck.
acceptedCap = acceptedCaps[i].trimmed().toLower();
// Mark this cap as accepted
coreNet->acknowledgeCap(acceptedCap);
- if (!capsRequireConfiguration &&
- coreNet->capsRequiringConfiguration.contains(acceptedCap)) {
+ if (!capsRequireConfiguration && coreNet->capsRequiringConfiguration.contains(acceptedCap)) {
capsRequireConfiguration = true;
// Some capabilities (e.g. SASL) require further messages to finish. If so, do NOT
// send the next capability; it will be handled elsewhere in CoreNetwork.
// No additional configuration required, move on to the next capability
coreNet->sendNextCap();
}
- } else if (capCommand == "NAK" || capCommand == "DEL") {
+ }
+ else if (capCommand == "NAK" || capCommand == "DEL") {
// CAP NAK/DEL require at least 3 parameters (no empty response allowed)
if (!checkParamCount(e, 3)) {
if (capCommand == "NAK") {
/* IRCv3 account-notify
* Log in: ":nick!user@host ACCOUNT accountname"
* Log out: ":nick!user@host ACCOUNT *" */
-void CoreSessionEventProcessor::processIrcEventAccount(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventAccount(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
- IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
+ IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
if (ircuser) {
// WHOX uses '0' to indicate logged-out, account-notify and extended-join uses '*'.
// As '*' is used internally to represent logged-out, no need to handle that differently.
ircuser->setAccount(e->params().at(0));
- } else {
+ }
+ else {
qDebug() << "Received account-notify data for unknown user" << e->prefix();
}
}
/* IRCv3 away-notify - ":nick!user@host AWAY [:message]" */
-void CoreSessionEventProcessor::processIrcEventAway(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventAway(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
// that it counts as two parameters, but we shouldn't rely on that.
// Nick is sent as part of parameters in order to split user/server decoding
- IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
+ IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
if (ircuser) {
// If two parameters are sent -and- the second parameter isn't empty, then user is away.
// Otherwise, mark them as not away.
if (e->params().count() >= 2 && !e->params().at(1).isEmpty()) {
ircuser->setAway(true);
ircuser->setAwayMessage(e->params().at(1));
- } else {
+ }
+ else {
ircuser->setAway(false);
}
- } else {
+ }
+ else {
qDebug() << "Received away-notify data for unknown user" << e->params().at(0);
}
}
/* IRCv3 chghost - ":nick!user@host CHGHOST newuser new.host.goes.here" */
-void CoreSessionEventProcessor::processIrcEventChghost(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventChghost(IrcEvent* e)
{
if (!checkParamCount(e, 2))
return;
- IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
+ IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
if (ircuser) {
// Update with new user/hostname information. setUser/setHost handles checking what
// actually changed.
ircuser->setUser(e->params().at(0));
ircuser->setHost(e->params().at(1));
- } else {
+ }
+ else {
qDebug() << "Received chghost data for unknown user" << e->prefix();
}
}
-void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventInvite(IrcEvent* e)
{
if (checkParamCount(e, 2)) {
e->network()->updateNickFromMask(e->prefix());
}
/* JOIN: ":<nick!user@host> JOIN <channel>" */
-void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventJoin(IrcEvent* e)
{
- if (e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin
+ if (e->testFlag(EventManager::Fake)) // generated by handleEarlyNetsplitJoin
return;
if (!checkParamCount(e, 1))
return;
- CoreNetwork *net = coreNetwork(e);
+ CoreNetwork* net = coreNetwork(e);
QString channel = e->params()[0];
- IrcUser *ircuser = net->updateNickFromMask(e->prefix());
+ IrcUser* ircuser = net->updateNickFromMask(e->prefix());
if (net->capEnabled(IrcCap::EXTENDED_JOIN)) {
if (e->params().count() < 3) {
// Some IRC servers don't send extended-join events in all situations. Rather than
// ignore the join entirely, treat it as a regular join with a debug-level log entry.
// See: https://github.com/inspircd/inspircd/issues/821
- qDebug() << "extended-join requires 3 params, got:" << e->params() << ", handling as a "
+ qDebug() << "extended-join requires 3 params, got:" << e->params()
+ << ", handling as a "
"regular join";
- } else {
+ }
+ else {
// If logged in, :nick!user@host JOIN #channelname accountname :Real Name
// If logged out, :nick!user@host JOIN #channelname * :Real Name
// See: http://ircv3.net/specs/extensions/extended-join-3.1.html
// Else :nick!user@host JOIN #channelname
bool handledByNetsplit = false;
- foreach(Netsplit* n, _netsplits.value(e->network())) {
+ foreach (Netsplit* n, _netsplits.value(e->network())) {
handledByNetsplit = n->userJoined(e->prefix(), channel);
if (handledByNetsplit)
break;
// Mark the message as Self
e->setFlag(EventManager::Self);
// FIXME use event
- net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely
+ net->putRawLine(net->serverEncode("MODE " + channel)); // we want to know the modes of the channel we just joined, so we ask politely
}
}
-
-void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent *e)
+void CoreSessionEventProcessor::lateProcessIrcEventKick(IrcEvent* e)
{
if (checkParamCount(e, 2)) {
e->network()->updateNickFromMask(e->prefix());
- IrcUser *victim = e->network()->ircUser(e->params().at(1));
+ IrcUser* victim = e->network()->ircUser(e->params().at(1));
if (victim) {
victim->partChannel(e->params().at(0));
- //if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel);
+ // if(e->network()->isMe(victim)) e->network()->setKickedFromChannel(channel);
}
}
}
-
-void CoreSessionEventProcessor::processIrcEventMode(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventMode(IrcEvent* e)
{
if (!checkParamCount(e, 2))
return;
if (e->network()->isChannelName(e->params().first())) {
// Channel Modes
- IrcChannel *channel = e->network()->ircChannel(e->params()[0]);
+ IrcChannel* channel = e->network()->ircChannel(e->params()[0]);
if (!channel) {
- // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like that
- // anyways: we don't have a place to store the data --> discard the info.
+ // we received mode information for a channel we're not in. that means probably we've just been kicked out or something like
+ // that anyways: we don't have a place to store the data --> discard the info.
return;
}
if (e->network()->prefixModes().contains(mode)) {
// user channel modes (op, voice, etc...)
if (paramOffset < e->params().count()) {
- IrcUser *ircUser = e->network()->ircUser(e->params()[paramOffset]);
+ IrcUser* ircUser = e->network()->ircUser(e->params()[paramOffset]);
if (!ircUser) {
qWarning() << Q_FUNC_INFO << "Unknown IrcUser:" << e->params()[paramOffset];
}
else {
if (add) {
bool handledByNetsplit = false;
- QHash<QString, Netsplit *> splits = _netsplits.value(e->network());
- foreach(Netsplit* n, _netsplits.value(e->network())) {
+ QHash<QString, Netsplit*> splits = _netsplits.value(e->network());
+ foreach (Netsplit* n, _netsplits.value(e->network())) {
handledByNetsplit = n->userAlreadyJoined(ircUser->hostmask(), channel->name());
if (handledByNetsplit) {
n->addMode(ircUser->hostmask(), channel->name(), QString(mode));
}
else {
// pure User Modes
- IrcUser *ircUser = e->network()->newIrcUser(e->params().first());
+ IrcUser* ircUser = e->network()->newIrcUser(e->params().first());
QString modeString(e->params()[1]);
QString addModes;
QString removeModes;
}
}
-
-void CoreSessionEventProcessor::processIrcEventNick(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventNick(IrcEvent* e)
{
if (checkParamCount(e, 1)) {
- IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
+ IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
if (!ircuser) {
qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
return;
}
}
-
-void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent *e)
+void CoreSessionEventProcessor::lateProcessIrcEventNick(IrcEvent* e)
{
if (checkParamCount(e, 1)) {
- IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
+ IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
if (!ircuser) {
qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
return;
}
}
-
-void CoreSessionEventProcessor::processIrcEventPart(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventPart(IrcEvent* e)
{
if (checkParamCount(e, 1)) {
- IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
+ IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
if (!ircuser) {
- qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!";
+ qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
return;
}
}
}
-
-void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent *e)
+void CoreSessionEventProcessor::lateProcessIrcEventPart(IrcEvent* e)
{
if (checkParamCount(e, 1)) {
- IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
+ IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
if (!ircuser) {
- qWarning() << Q_FUNC_INFO<< "Unknown IrcUser!";
+ qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
return;
}
QString channel = e->params().at(0);
ircuser->partChannel(channel);
if (e->network()->isMe(ircuser)) {
- qobject_cast<CoreNetwork *>(e->network())->setChannelParted(channel);
+ qobject_cast<CoreNetwork*>(e->network())->setChannelParted(channel);
}
}
}
-
-void CoreSessionEventProcessor::processIrcEventPing(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventPing(IrcEvent* e)
{
QString param = e->params().count() ? e->params().first() : QString();
// FIXME use events
coreNetwork(e)->putRawLine("PONG " + coreNetwork(e)->serverEncode(param), true);
}
-
-void CoreSessionEventProcessor::processIrcEventPong(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventPong(IrcEvent* e)
{
// Ensure we get at least one parameter
if (!checkParamCount(e, 1))
// Only one parameter received
// :localhost PONG 02:43:49.565
timestamp = e->params().at(0);
- } else {
+ }
+ else {
// Two parameters received, pick the second
// :localhost PONG localhost :02:43:49.565
timestamp = e->params().at(1);
// Add a message the first time it happens
qDebug().nospace() << "Received PONG with valid timestamp, marking pong replies on "
"network "
- << "\"" << qPrintable(e->network()->networkName()) << "\" (ID: "
- << qPrintable(QString::number(e->network()->networkId().toInt()))
+ << "\"" << qPrintable(e->network()->networkName())
+ << "\" (ID: " << qPrintable(QString::number(e->network()->networkId().toInt()))
<< ") as usable for latency measurement";
}
// Remove pending flag
// Calculate latency from time difference, divided by 2 to account for round-trip time
e->network()->setLatency(sendTime.msecsTo(QTime::currentTime()) / 2);
- } else if (coreNetwork(e)->isPongReplyPending() && !coreNetwork(e)->isPongTimestampValid()) {
+ }
+ else if (coreNetwork(e)->isPongReplyPending() && !coreNetwork(e)->isPongTimestampValid()) {
// There's an auto-PING reply pending and we've not yet received a PONG reply with a valid
// timestamp. It's possible this server will never respond with a valid timestamp, and thus
// any automated PINGs will result in unwanted spamming of the server buffer.
// Log a message
qDebug().nospace() << "Received PONG with invalid timestamp from network "
- << "\"" << qPrintable(e->network()->networkName()) << "\" (ID: "
- << qPrintable(QString::number(e->network()->networkId().toInt()))
+ << "\"" << qPrintable(e->network()->networkName())
+ << "\" (ID: " << qPrintable(QString::number(e->network()->networkId().toInt()))
<< "), silencing, parameters are " << e->params();
}
// else: We're not expecting a PONG reply and timestamp is not valid, assume it's from the user
}
-
-void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventQuit(IrcEvent* e)
{
- IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
+ IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
if (!ircuser)
return;
// check if netsplit
if (Netsplit::isNetsplit(msg)) {
- Netsplit *n;
+ Netsplit* n;
if (!_netsplits[e->network()].contains(msg)) {
n = new Netsplit(e->network(), this);
connect(n, &Netsplit::finished, this, &CoreSessionEventProcessor::handleNetsplitFinished);
- connect(n, &Netsplit::netsplitJoin,
- this, &CoreSessionEventProcessor::handleNetsplitJoin);
- connect(n, &Netsplit::netsplitQuit,
- this, &CoreSessionEventProcessor::handleNetsplitQuit);
- connect(n, &Netsplit::earlyJoin,
- this, &CoreSessionEventProcessor::handleEarlyNetsplitJoin);
+ connect(n, &Netsplit::netsplitJoin, this, &CoreSessionEventProcessor::handleNetsplitJoin);
+ connect(n, &Netsplit::netsplitQuit, this, &CoreSessionEventProcessor::handleNetsplitQuit);
+ connect(n, &Netsplit::earlyJoin, this, &CoreSessionEventProcessor::handleEarlyNetsplitJoin);
_netsplits[e->network()].insert(msg, n);
}
else {
// normal quit is handled in lateProcessIrcEventQuit()
}
-
-void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent *e)
+void CoreSessionEventProcessor::lateProcessIrcEventQuit(IrcEvent* e)
{
if (e->testFlag(EventManager::Netsplit))
return;
- IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
+ IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
if (!ircuser)
return;
ircuser->quit();
}
-
-void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventTopic(IrcEvent* e)
{
if (checkParamCount(e, 2)) {
- IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
+ IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
if (e->network()->isMe(ircuser)) {
// Mark the message as Self
e->setFlag(EventManager::Self);
}
- IrcChannel *channel = e->network()->ircChannel(e->params().at(0));
+ IrcChannel* channel = e->network()->ircChannel(e->params().at(0));
if (channel)
channel->setTopic(e->params().at(1));
}
/* ERROR - "ERROR :reason"
Example: ERROR :Closing Link: nickname[xxx.xxx.xxx.xxx] (Large base64 image paste.)
See https://tools.ietf.org/html/rfc2812#section-3.7.4 */
-void CoreSessionEventProcessor::processIrcEventError(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEventError(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
}
}
-
#ifdef HAVE_QCA2
-void CoreSessionEventProcessor::processKeyEvent(KeyEvent *e)
+void CoreSessionEventProcessor::processKeyEvent(KeyEvent* e)
{
if (!Cipher::neededFeaturesAvailable()) {
- emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Unable to perform key exchange, missing qca-ossl plugin."), e->prefix(), e->target(), Message::None, e->timestamp()));
+ emit newEvent(new MessageEvent(Message::Error,
+ e->network(),
+ tr("Unable to perform key exchange, missing qca-ossl plugin."),
+ e->prefix(),
+ e->target(),
+ Message::None,
+ e->timestamp()));
return;
}
- auto *net = qobject_cast<CoreNetwork*>(e->network());
- Cipher *c = net->cipher(e->target());
- if (!c) // happens when there is no CoreIrcChannel for the target (i.e. never?)
+ auto* net = qobject_cast<CoreNetwork*>(e->network());
+ Cipher* c = net->cipher(e->target());
+ if (!c) // happens when there is no CoreIrcChannel for the target (i.e. never?)
return;
if (e->exchangeType() == KeyEvent::Init) {
QByteArray pubKey = c->parseInitKeyX(e->key());
if (pubKey.isEmpty()) {
- emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Unable to parse the DH1080_INIT. Key exchange failed."), e->prefix(), e->target(), Message::None, e->timestamp()));
+ emit newEvent(new MessageEvent(Message::Error,
+ e->network(),
+ tr("Unable to parse the DH1080_INIT. Key exchange failed."),
+ e->prefix(),
+ e->target(),
+ Message::None,
+ e->timestamp()));
return;
- } else {
+ }
+ else {
net->setCipherKey(e->target(), c->key());
- emit newEvent(new MessageEvent(Message::Info, e->network(), tr("Your key is set and messages will be encrypted."), e->prefix(), e->target(), Message::None, e->timestamp()));
+ emit newEvent(new MessageEvent(Message::Info,
+ e->network(),
+ tr("Your key is set and messages will be encrypted."),
+ e->prefix(),
+ e->target(),
+ Message::None,
+ e->timestamp()));
QList<QByteArray> p;
- p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ")+pubKey;
+ p << net->serverEncode(e->target()) << net->serverEncode("DH1080_FINISH ") + pubKey;
net->putCmd("NOTICE", p);
}
- } else {
+ }
+ else {
if (c->parseFinishKeyX(e->key())) {
net->setCipherKey(e->target(), c->key());
- emit newEvent(new MessageEvent(Message::Info, e->network(), tr("Your key is set and messages will be encrypted."), e->prefix(), e->target(), Message::None, e->timestamp()));
- } else {
- emit newEvent(new MessageEvent(Message::Info, e->network(), tr("Failed to parse DH1080_FINISH. Key exchange failed."), e->prefix(), e->target(), Message::None, e->timestamp()));
+ emit newEvent(new MessageEvent(Message::Info,
+ e->network(),
+ tr("Your key is set and messages will be encrypted."),
+ e->prefix(),
+ e->target(),
+ Message::None,
+ e->timestamp()));
+ }
+ else {
+ emit newEvent(new MessageEvent(Message::Info,
+ e->network(),
+ tr("Failed to parse DH1080_FINISH. Key exchange failed."),
+ e->prefix(),
+ e->target(),
+ Message::None,
+ e->timestamp()));
}
}
}
#endif
-
/* RPL_WELCOME */
-void CoreSessionEventProcessor::processIrcEvent001(IrcEventNumeric *e)
+void CoreSessionEventProcessor::processIrcEvent001(IrcEventNumeric* e)
{
e->network()->setCurrentServer(e->prefix());
e->network()->setMyNick(e->target());
}
-
/* RPL_ISUPPORT */
// TODO Complete 005 handling, also use sensible defaults for non-sent stuff
-void CoreSessionEventProcessor::processIrcEvent005(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent005(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
e->network()->determinePrefixes();
}
-
/* RPL_UMODEIS - "<user_modes> [<user_mode_params>]" */
-void CoreSessionEventProcessor::processIrcEvent221(IrcEvent *)
+void CoreSessionEventProcessor::processIrcEvent221(IrcEvent*)
{
// TODO: save information in network object
}
-
/* RPL_STATSCONN - "Highest connection cout: 8000 (7999 clients)" */
-void CoreSessionEventProcessor::processIrcEvent250(IrcEvent *)
+void CoreSessionEventProcessor::processIrcEvent250(IrcEvent*)
{
// TODO: save information in network object
}
-
/* RPL_LOCALUSERS - "Current local user: 5024 Max: 7999 */
-void CoreSessionEventProcessor::processIrcEvent265(IrcEvent *)
+void CoreSessionEventProcessor::processIrcEvent265(IrcEvent*)
{
// TODO: save information in network object
}
-
/* RPL_GLOBALUSERS - "Current global users: 46093 Max: 47650" */
-void CoreSessionEventProcessor::processIrcEvent266(IrcEvent *)
+void CoreSessionEventProcessor::processIrcEvent266(IrcEvent*)
{
// TODO: save information in network object
}
-
/*
WHOIS-Message:
Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
*/
/* RPL_AWAY - "<nick> :<away message>" */
-void CoreSessionEventProcessor::processIrcEvent301(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent301(IrcEvent* e)
{
if (!checkParamCount(e, 2))
return;
- IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
+ IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
if (ircuser) {
ircuser->setAway(true);
ircuser->setAwayMessage(e->params().at(1));
// lastAwayMessageTime is set in EventStringifier::processIrcEvent301(), no need to set it
// here too
- //ircuser->setLastAwayMessageTime(now);
+ // ircuser->setLastAwayMessageTime(now);
}
}
-
/* RPL_UNAWAY - ":You are no longer marked as being away" */
-void CoreSessionEventProcessor::processIrcEvent305(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent305(IrcEvent* e)
{
- IrcUser *me = e->network()->me();
+ IrcUser* me = e->network()->me();
if (me)
me->setAway(false);
}
}
-
/* RPL_NOWAWAY - ":You have been marked as being away" */
-void CoreSessionEventProcessor::processIrcEvent306(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent306(IrcEvent* e)
{
- IrcUser *me = e->network()->me();
+ IrcUser* me = e->network()->me();
if (me)
me->setAway(true);
}
-
/* RPL_WHOISSERVICE - "<user> is registered nick" */
-void CoreSessionEventProcessor::processIrcEvent307(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent307(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
- IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
+ IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
if (ircuser)
ircuser->setWhoisServiceReply(e->params().join(" "));
}
-
/* RPL_SUSERHOST - "<user> is available for help." */
-void CoreSessionEventProcessor::processIrcEvent310(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent310(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
- IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
+ IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
if (ircuser)
ircuser->setSuserHost(e->params().join(" "));
}
-
/* RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
-void CoreSessionEventProcessor::processIrcEvent311(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent311(IrcEvent* e)
{
if (!checkParamCount(e, 3))
return;
- IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
+ IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
if (ircuser) {
ircuser->setUser(e->params().at(1));
ircuser->setHost(e->params().at(2));
}
}
-
/* RPL_WHOISSERVER - "<nick> <server> :<server info>" */
-void CoreSessionEventProcessor::processIrcEvent312(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent312(IrcEvent* e)
{
if (!checkParamCount(e, 2))
return;
- IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
+ IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
if (ircuser)
ircuser->setServer(e->params().at(1));
}
-
/* RPL_WHOISOPERATOR - "<nick> :is an IRC operator" */
-void CoreSessionEventProcessor::processIrcEvent313(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent313(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
- IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
+ IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
if (ircuser)
ircuser->setIrcOperator(e->params().last());
}
-
/* RPL_ENDOFWHO: "<name> :End of WHO list" */
-void CoreSessionEventProcessor::processIrcEvent315(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent315(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
e->setFlag(EventManager::Silent);
}
-
/* RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
(real life: "<nick> <integer> <integer> :seconds idle, signon time) */
-void CoreSessionEventProcessor::processIrcEvent317(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent317(IrcEvent* e)
{
if (!checkParamCount(e, 2))
return;
QDateTime loginTime;
int idleSecs = e->params()[1].toInt();
- if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
+ if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
// Allow for 64-bit time
qint64 logintime = e->params()[2].toLongLong();
// Time in IRC protocol is defined as seconds. Convert from seconds instead.
#endif
}
- IrcUser *ircuser = e->network()->ircUser(e->params()[0]);
+ IrcUser* ircuser = e->network()->ircUser(e->params()[0]);
if (ircuser) {
ircuser->setIdleTime(e->timestamp().addSecs(-idleSecs));
if (loginTime.isValid())
}
}
-
/* RPL_LIST - "<channel> <# visible> :<topic>" */
-void CoreSessionEventProcessor::processIrcEvent322(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent322(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
e->stop(); // consumed by IrcListHelper, so don't further process/show this event
}
-
/* RPL_LISTEND ":End of LIST" */
-void CoreSessionEventProcessor::processIrcEvent323(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent323(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
e->stop(); // consumed by IrcListHelper, so don't further process/show this event
}
-
/* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
-void CoreSessionEventProcessor::processIrcEvent324(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent324(IrcEvent* e)
{
processIrcEventMode(e);
}
-
/* RPL_WHOISACCOUNT - "<nick> <account> :is authed as" */
-void CoreSessionEventProcessor::processIrcEvent330(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent330(IrcEvent* e)
{
// Though the ":is authed as" remark should always be there, we should handle cases when it's
// not included, too.
if (!checkParamCount(e, 2))
return;
- IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
+ IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
if (ircuser) {
ircuser->setAccount(e->params().at(1));
}
}
-
/* RPL_NOTOPIC */
-void CoreSessionEventProcessor::processIrcEvent331(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent331(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
- IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
+ IrcChannel* chan = e->network()->ircChannel(e->params()[0]);
if (chan)
chan->setTopic(QString());
}
-
/* RPL_TOPIC */
-void CoreSessionEventProcessor::processIrcEvent332(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent332(IrcEvent* e)
{
if (!checkParamCount(e, 2))
return;
- IrcChannel *chan = e->network()->ircChannel(e->params()[0]);
+ IrcChannel* chan = e->network()->ircChannel(e->params()[0]);
if (chan)
chan->setTopic(e->params()[1]);
}
-
/* RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
-void CoreSessionEventProcessor::processIrcEvent352(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent352(IrcEvent* e)
{
if (!checkParamCount(e, 6))
return;
QString channel = e->params()[0];
- IrcUser *ircuser = e->network()->ircUser(e->params()[4]);
+ IrcUser* ircuser = e->network()->ircUser(e->params()[4]);
if (ircuser) {
// Only process the WHO information if an IRC user exists. Don't create an IRC user here;
// there's no way to track when the user quits, which would leave a phantom IrcUser lying
// around.
// NOTE: Whenever MONITOR support is introduced, the IrcUser will be created by an
// RPL_MONONLINE numeric before any WHO commands are run.
- processWhoInformation(e->network(), channel, ircuser, e->params()[3], e->params()[1],
- e->params()[2], e->params()[5], e->params().last().section(" ", 1));
+ processWhoInformation(e->network(),
+ channel,
+ ircuser,
+ e->params()[3],
+ e->params()[1],
+ e->params()[2],
+ e->params()[5],
+ e->params().last().section(" ", 1));
}
// Check if channel name has a who in progress.
}
}
-
/* RPL_NAMREPLY */
-void CoreSessionEventProcessor::processIrcEvent353(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent353(IrcEvent* e)
{
if (!checkParamCount(e, 3))
return;
// we don't use this information at the time beeing
QString channelname = e->params()[1];
- IrcChannel *channel = e->network()->ircChannel(channelname);
+ IrcChannel* channel = e->network()->ircChannel(channelname);
if (!channel) {
qWarning() << Q_FUNC_INFO << "Received unknown target channel:" << channelname;
return;
// Cache result of multi-prefix to avoid unneeded casts and lookups with each iteration.
bool _useCapMultiPrefix = coreNetwork(e)->capEnabled(IrcCap::MULTI_PREFIX);
- foreach(QString nick, e->params()[2].split(' ', QString::SkipEmptyParts)) {
+ foreach (QString nick, e->params()[2].split(' ', QString::SkipEmptyParts)) {
QString mode;
if (_useCapMultiPrefix) {
// Remove this mode from the nick
nick = nick.remove(0, 1);
}
- } else if (e->network()->prefixes().contains(nick[0])) {
+ }
+ else if (e->network()->prefixes().contains(nick[0])) {
// Multi-prefix is disabled and a mode prefix was found.
mode = e->network()->prefixToMode(nick[0]);
nick = nick.mid(1);
channel->joinIrcUsers(nicks, modes);
}
-
/* RPL_WHOSPCRPL: "<yournick> 152 #<channel> ~<ident> <host> <servname> <nick>
("H"/ "G") <account> :<realname>"
<channel> is * if not specific to any channel
Follows HexChat's usage of 'whox'
See https://github.com/hexchat/hexchat/blob/c874a9525c9b66f1d5ddcf6c4107d046eba7e2c5/src/common/proto-irc.c#L750
And http://faerion.sourceforge.net/doc/irc/whox.var*/
-void CoreSessionEventProcessor::processIrcEvent354(IrcEvent *e)
+void CoreSessionEventProcessor::processIrcEvent354(IrcEvent* e)
{
// First only check if at least one parameter exists. Otherwise, it'll stop the result from
// being shown if the user chooses different parameters.
return;
QString channel = e->params()[1];
- IrcUser *ircuser = e->network()->ircUser(e->params()[5]);
+ IrcUser* ircuser = e->network()->ircUser(e->params()[5]);
if (ircuser) {
// Only process the WHO information if an IRC user exists. Don't create an IRC user here;
// there's no way to track when the user quits, which would leave a phantom IrcUser lying
// around.
// NOTE: Whenever MONITOR support is introduced, the IrcUser will be created by an
// RPL_MONONLINE numeric before any WHO commands are run.
- processWhoInformation(e->network(), channel, ircuser, e->params()[4], e->params()[2],
- e->params()[3], e->params()[6], e->params().last());
+ processWhoInformation(e->network(), channel, ircuser, e->params()[4], e->params()[2], e->params()[3], e->params()[6], e->params().last());
// Don't use .section(" ", 1) with WHOX replies, for there's no hopcount to trim out
// As part of IRCv3 account-notify, check account name
if (newAccount != "0") {
// Account logged in, set account name
ircuser->setAccount(newAccount);
- } else {
+ }
+ else {
// Account logged out, set account name to logged-out
ircuser->setAccount("*");
}
}
}
-
-void CoreSessionEventProcessor::processWhoInformation (Network *net, const QString &targetChannel, IrcUser *ircUser,
- const QString &server, const QString &user, const QString &host,
- const QString &awayStateAndModes, const QString &realname)
+void CoreSessionEventProcessor::processWhoInformation(Network* net,
+ const QString& targetChannel,
+ IrcUser* ircUser,
+ const QString& server,
+ const QString& user,
+ const QString& host,
+ const QString& awayStateAndModes,
+ const QString& realname)
{
ircUser->setUser(user);
ircUser->setHost(host);
if (!validModes.isEmpty()) {
if (targetChannel != "*") {
// Channel-specific modes received, apply to given channel only
- IrcChannel *ircChan = net->ircChannel(targetChannel);
+ IrcChannel* ircChan = net->ircChannel(targetChannel);
if (ircChan) {
// Do one mode at a time
// TODO Better way of syncing this without breaking protocol?
ircChan->addUserMode(ircUser, validModes.at(i));
}
}
- } else {
+ }
+ else {
// Modes apply to the user everywhere
ircUser->addUserModes(validModes);
}
}
}
-
/* ERR_NOSUCHCHANNEL - "<channel name> :No such channel" */
-void CoreSessionEventProcessor::processIrcEvent403(IrcEventNumeric *e)
+void CoreSessionEventProcessor::processIrcEvent403(IrcEventNumeric* e)
{
// If this is the result of an AutoWho, hide it. It's confusing to show to the user.
// Though the ":No such channel" remark should always be there, we should handle cases when it's
}
/* ERR_ERRONEUSNICKNAME */
-void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric *e)
+void CoreSessionEventProcessor::processIrcEvent432(IrcEventNumeric* e)
{
if (!checkParamCount(e, 1))
return;
tryNextNick(e, errnick, true /* erroneus */);
}
-
/* ERR_NICKNAMEINUSE */
-void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric *e)
+void CoreSessionEventProcessor::processIrcEvent433(IrcEventNumeric* e)
{
if (!checkParamCount(e, 1))
return;
tryNextNick(e, errnick);
}
-
/* ERR_UNAVAILRESOURCE */
-void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric *e)
+void CoreSessionEventProcessor::processIrcEvent437(IrcEventNumeric* e)
{
if (!checkParamCount(e, 1))
return;
tryNextNick(e, errnick);
}
-
/* template
void CoreSessionEventProcessor::processIrcEvent(IrcEvent *e) {
if(!checkParamCount(e, 1))
/* Handle signals from Netsplit objects */
-void CoreSessionEventProcessor::handleNetsplitJoin(Network *net,
- const QString &channel,
- const QStringList &users,
- const QStringList &modes,
- const QString &quitMessage)
+void CoreSessionEventProcessor::handleNetsplitJoin(
+ Network* net, const QString& channel, const QStringList& users, const QStringList& modes, const QString& quitMessage)
{
- IrcChannel *ircChannel = net->ircChannel(channel);
+ IrcChannel* ircChannel = net->ircChannel(channel);
if (!ircChannel) {
return;
}
- QList<IrcUser *> ircUsers;
+ QList<IrcUser*> ircUsers;
QStringList newModes = modes;
QStringList newUsers = users;
- foreach(const QString &user, users) {
- IrcUser *iu = net->ircUser(nickFromMask(user));
+ foreach (const QString& user, users) {
+ IrcUser* iu = net->ircUser(nickFromMask(user));
if (iu)
ircUsers.append(iu);
- else { // the user already quit
+ else { // the user already quit
int idx = users.indexOf(user);
newUsers.removeAt(idx);
newModes.removeAt(idx);
}
ircChannel->joinIrcUsers(ircUsers, newModes);
- NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
+ NetworkSplitEvent* event = new NetworkSplitEvent(EventManager::NetworkSplitJoin, net, channel, newUsers, quitMessage);
emit newEvent(event);
}
-
-void CoreSessionEventProcessor::handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage)
+void CoreSessionEventProcessor::handleNetsplitQuit(Network* net, const QString& channel, const QStringList& users, const QString& quitMessage)
{
- NetworkSplitEvent *event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage);
+ NetworkSplitEvent* event = new NetworkSplitEvent(EventManager::NetworkSplitQuit, net, channel, users, quitMessage);
emit newEvent(event);
- foreach(QString user, users) {
- IrcUser *iu = net->ircUser(nickFromMask(user));
+ foreach (QString user, users) {
+ IrcUser* iu = net->ircUser(nickFromMask(user));
if (iu)
iu->quit();
}
}
-
-void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes)
+void CoreSessionEventProcessor::handleEarlyNetsplitJoin(Network* net, const QString& channel, const QStringList& users, const QStringList& modes)
{
- IrcChannel *ircChannel = net->ircChannel(channel);
+ IrcChannel* ircChannel = net->ircChannel(channel);
if (!ircChannel) {
qDebug() << "handleEarlyNetsplitJoin(): channel " << channel << " invalid";
return;
}
- QList<NetworkEvent *> events;
- QList<IrcUser *> ircUsers;
+ QList<NetworkEvent*> events;
+ QList<IrcUser*> ircUsers;
QStringList newModes = modes;
- foreach(QString user, users) {
- IrcUser *iu = net->updateNickFromMask(user);
+ foreach (QString user, users) {
+ IrcUser* iu = net->updateNickFromMask(user);
if (iu) {
ircUsers.append(iu);
// fake event for scripts that consume join events
}
}
ircChannel->joinIrcUsers(ircUsers, newModes);
- foreach(NetworkEvent *event, events) {
- event->setFlag(EventManager::Fake); // ignore this in here!
+ foreach (NetworkEvent* event, events) {
+ event->setFlag(EventManager::Fake); // ignore this in here!
emit newEvent(event);
}
}
-
void CoreSessionEventProcessor::handleNetsplitFinished()
{
- auto *n = qobject_cast<Netsplit *>(sender());
+ auto* n = qobject_cast<Netsplit*>(sender());
Q_ASSERT(n);
- QHash<QString, Netsplit *> splithash = _netsplits.take(n->network());
+ QHash<QString, Netsplit*> splithash = _netsplits.take(n->network());
splithash.remove(splithash.key(n));
if (splithash.count())
_netsplits[n->network()] = splithash;
n->deleteLater();
}
-
void CoreSessionEventProcessor::destroyNetsplits(NetworkId netId)
{
- Network *net = coreSession()->network(netId);
+ Network* net = coreSession()->network(netId);
if (!net)
return;
- QHash<QString, Netsplit *> splits = _netsplits.take(net);
+ QHash<QString, Netsplit*> splits = _netsplits.take(net);
qDeleteAll(splits);
}
-
/*******************************/
/******** CTCP HANDLING ********/
/*******************************/
-void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent *e)
+void CoreSessionEventProcessor::processCtcpEvent(CtcpEvent* e)
{
if (e->testFlag(EventManager::Self))
return; // ignore ctcp events generated by user input
if (e->type() != EventManager::CtcpEvent || e->ctcpType() != CtcpEvent::Query)
return;
- handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e));
+ handle(e->ctcpCmd(), Q_ARG(CtcpEvent*, e));
}
-
-void CoreSessionEventProcessor::defaultHandler(const QString &ctcpCmd, CtcpEvent *e)
+void CoreSessionEventProcessor::defaultHandler(const QString& ctcpCmd, CtcpEvent* e)
{
// This handler is only there to avoid warnings for unknown CTCPs
Q_UNUSED(e);
Q_UNUSED(ctcpCmd);
}
-
-void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent *e)
+void CoreSessionEventProcessor::handleCtcpAction(CtcpEvent* e)
{
// This handler is only there to feed CLIENTINFO
Q_UNUSED(e);
}
-
-void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent *e)
+void CoreSessionEventProcessor::handleCtcpClientinfo(CtcpEvent* e)
{
QStringList supportedHandlers;
- foreach(QString handler, providesHandlers())
- supportedHandlers << handler.toUpper();
+ foreach (QString handler, providesHandlers())
+ supportedHandlers << handler.toUpper();
qSort(supportedHandlers);
e->setReply(supportedHandlers.join(" "));
}
-
// http://www.irchelp.org/irchelp/rfc/ctcpspec.html
// http://en.wikipedia.org/wiki/Direct_Client-to-Client
-void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent *e)
+void CoreSessionEventProcessor::handleCtcpDcc(CtcpEvent* e)
{
// DCC support is unfinished, experimental and potentially dangerous, so make it opt-in
if (!Quassel::isOptionSet("enable-experimental-dcc")) {
QHostAddress address;
quint16 port = params[3].toUShort();
quint64 size = 0;
- QString numIp = params[2]; // this is either IPv4 as a 32 bit value, or IPv6 (which always contains a colon)
- if (numIp.contains(':')) { // IPv6
+ QString numIp = params[2]; // this is either IPv4 as a 32 bit value, or IPv6 (which always contains a colon)
+ if (numIp.contains(':')) { // IPv6
if (!address.setAddress(numIp)) {
qWarning() << "Invalid IPv6:" << numIp;
return;
address.setAddress(numIp.toUInt());
}
- if (port == 0) { // Reverse DCC is indicated by a 0 port
- emit newEvent(new MessageEvent(Message::Error, e->network(), tr("Reverse DCC SEND not supported"), e->prefix(), e->target(), Message::None, e->timestamp()));
+ if (port == 0) { // Reverse DCC is indicated by a 0 port
+ emit newEvent(new MessageEvent(Message::Error,
+ e->network(),
+ tr("Reverse DCC SEND not supported"),
+ e->prefix(),
+ e->target(),
+ Message::None,
+ e->timestamp()));
return;
}
if (port < 1024) {
- qWarning() << "Privileged port requested:" << port; // FIXME ask user if this is ok
+ qWarning() << "Privileged port requested:" << port; // FIXME ask user if this is ok
}
-
- if (params.count() > 4) { // filesize is optional
+ if (params.count() > 4) { // filesize is optional
size = params[4].toULong();
}
// TODO: check if target is the right thing to use for the partner
- CoreTransfer *transfer = new CoreTransfer(Transfer::Direction::Receive, e->target(), filename, address, port, size, this);
+ CoreTransfer* transfer = new CoreTransfer(Transfer::Direction::Receive, e->target(), filename, address, port, size, this);
coreSession()->signalProxy()->synchronize(transfer);
coreSession()->transferManager()->addTransfer(transfer);
}
else {
- emit newEvent(new MessageEvent(Message::Error, e->network(), tr("DCC %1 not supported").arg(cmd), e->prefix(), e->target(), Message::None, e->timestamp()));
+ emit newEvent(new MessageEvent(Message::Error,
+ e->network(),
+ tr("DCC %1 not supported").arg(cmd),
+ e->prefix(),
+ e->target(),
+ Message::None,
+ e->timestamp()));
return;
}
}
}
-
-void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent *e)
+void CoreSessionEventProcessor::handleCtcpPing(CtcpEvent* e)
{
e->setReply(e->param().isNull() ? "" : e->param());
}
-
-void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent *e)
+void CoreSessionEventProcessor::handleCtcpTime(CtcpEvent* e)
{
// Use the ISO standard to avoid locale-specific translated names
// Include timezone offset data to show which timezone a user's in, otherwise we're providing
e->setReply(formatDateTimeToOffsetISO(QDateTime::currentDateTime()));
}
-
-void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent *e)
+void CoreSessionEventProcessor::handleCtcpVersion(CtcpEvent* e)
{
// Deliberately do not translate project name
// Use the ISO standard to avoid locale-specific translated names
// Use UTC time to provide a consistent string regardless of timezone
// (Statistics tracking tools usually only group client versions by exact string matching)
e->setReply(QString("Quassel IRC %1 (version date %2) -- https://www.quassel-irc.org")
- .arg(Quassel::buildInfo().plainVersionString)
- .arg(Quassel::buildInfo().commitDate.isEmpty() ?
- "unknown" : tryFormatUnixEpoch(Quassel::buildInfo().commitDate,
- Qt::DateFormat::ISODate, true)));
+ .arg(Quassel::buildInfo().plainVersionString)
+ .arg(Quassel::buildInfo().commitDate.isEmpty()
+ ? "unknown"
+ : tryFormatUnixEpoch(Quassel::buildInfo().commitDate, Qt::DateFormat::ISODate, true)));
}
Q_OBJECT
public:
- CoreSessionEventProcessor(CoreSession *session);
-
- inline CoreSession *coreSession() const { return _coreSession; }
-
- Q_INVOKABLE void processIrcEventNumeric(IrcEventNumeric *event);
-
- Q_INVOKABLE void processIrcEventAuthenticate(IrcEvent *event); /// SASL authentication
- Q_INVOKABLE void processIrcEventCap(IrcEvent *event); /// CAP framework negotiation
- Q_INVOKABLE void processIrcEventAccount(IrcEvent *event); /// account-notify received
- Q_INVOKABLE void processIrcEventAway(IrcEvent *event); /// away-notify received
- Q_INVOKABLE void processIrcEventChghost(IrcEvent *event); /// chghost received
- Q_INVOKABLE void processIrcEventInvite(IrcEvent *event);
- Q_INVOKABLE void processIrcEventJoin(IrcEvent *event);
- Q_INVOKABLE void lateProcessIrcEventKick(IrcEvent *event);
- Q_INVOKABLE void processIrcEventMode(IrcEvent *event);
- Q_INVOKABLE void processIrcEventNick(IrcEvent *event); /// Nickname changes
- Q_INVOKABLE void lateProcessIrcEventNick(IrcEvent *event);
- Q_INVOKABLE void processIrcEventPart(IrcEvent *event); /// Leaving a channel
- Q_INVOKABLE void lateProcessIrcEventPart(IrcEvent *event);
- Q_INVOKABLE void processIrcEventPing(IrcEvent *event);
- Q_INVOKABLE void processIrcEventPong(IrcEvent *event);
- Q_INVOKABLE void processIrcEventQuit(IrcEvent *event);
- Q_INVOKABLE void lateProcessIrcEventQuit(IrcEvent *event);
- Q_INVOKABLE void processIrcEventTopic(IrcEvent *event);
- Q_INVOKABLE void processIrcEventError(IrcEvent *event); /// ERROR message from server
+ CoreSessionEventProcessor(CoreSession* session);
+
+ inline CoreSession* coreSession() const { return _coreSession; }
+
+ Q_INVOKABLE void processIrcEventNumeric(IrcEventNumeric* event);
+
+ Q_INVOKABLE void processIrcEventAuthenticate(IrcEvent* event); /// SASL authentication
+ Q_INVOKABLE void processIrcEventCap(IrcEvent* event); /// CAP framework negotiation
+ Q_INVOKABLE void processIrcEventAccount(IrcEvent* event); /// account-notify received
+ Q_INVOKABLE void processIrcEventAway(IrcEvent* event); /// away-notify received
+ Q_INVOKABLE void processIrcEventChghost(IrcEvent* event); /// chghost received
+ Q_INVOKABLE void processIrcEventInvite(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventJoin(IrcEvent* event);
+ Q_INVOKABLE void lateProcessIrcEventKick(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventMode(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventNick(IrcEvent* event); /// Nickname changes
+ Q_INVOKABLE void lateProcessIrcEventNick(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventPart(IrcEvent* event); /// Leaving a channel
+ Q_INVOKABLE void lateProcessIrcEventPart(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventPing(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventPong(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventQuit(IrcEvent* event);
+ Q_INVOKABLE void lateProcessIrcEventQuit(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventTopic(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventError(IrcEvent* event); /// ERROR message from server
#ifdef HAVE_QCA2
- Q_INVOKABLE void processKeyEvent(KeyEvent *event);
+ Q_INVOKABLE void processKeyEvent(KeyEvent* event);
#endif
- Q_INVOKABLE void processIrcEvent001(IrcEventNumeric *event); // RPL_WELCOME
- Q_INVOKABLE void processIrcEvent005(IrcEvent *event); // RPL_ISUPPORT
- Q_INVOKABLE void processIrcEvent221(IrcEvent *event); // RPL_UMODEIS
- Q_INVOKABLE void processIrcEvent250(IrcEvent *event); // RPL_STATSCONN
- Q_INVOKABLE void processIrcEvent265(IrcEvent *event); // RPL_LOCALUSERS
- Q_INVOKABLE void processIrcEvent266(IrcEvent *event); // RPL_GLOBALUSERS
- Q_INVOKABLE void processIrcEvent301(IrcEvent *event); // RPL_AWAY
- Q_INVOKABLE void processIrcEvent305(IrcEvent *event); // RPL_UNAWAY
- Q_INVOKABLE void processIrcEvent306(IrcEvent *event); // RPL_NOWAWAY
- Q_INVOKABLE void processIrcEvent307(IrcEvent *event); // RPL_WHOISSERVICE
- Q_INVOKABLE void processIrcEvent310(IrcEvent *event); // RPL_SUSERHOST
- Q_INVOKABLE void processIrcEvent311(IrcEvent *event); // RPL_WHOISUSER
- Q_INVOKABLE void processIrcEvent312(IrcEvent *event); // RPL_WHOISSERVER
- Q_INVOKABLE void processIrcEvent313(IrcEvent *event); // RPL_WHOISOPERATOR
- Q_INVOKABLE void processIrcEvent315(IrcEvent *event); // RPL_ENDOFWHO
- Q_INVOKABLE void processIrcEvent317(IrcEvent *event); // RPL_WHOISIDLE
- Q_INVOKABLE void processIrcEvent322(IrcEvent *event); // RPL_LIST
- Q_INVOKABLE void processIrcEvent323(IrcEvent *event); // RPL_LISTEND
- Q_INVOKABLE void processIrcEvent324(IrcEvent *event); // RPL_CHANNELMODEIS
- Q_INVOKABLE void processIrcEvent330(IrcEvent *event); // RPL_WHOISACCOUNT (quakenet/snircd/undernet)
- Q_INVOKABLE void processIrcEvent331(IrcEvent *event); // RPL_NOTOPIC
- Q_INVOKABLE void processIrcEvent332(IrcEvent *event); // RPL_TOPIC
- Q_INVOKABLE void processIrcEvent352(IrcEvent *event); // RPL_WHOREPLY
- Q_INVOKABLE void processIrcEvent353(IrcEvent *event); // RPL_NAMREPLY
- Q_INVOKABLE void processIrcEvent354(IrcEvent *event); // RPL_WHOSPCRPL
- Q_INVOKABLE void processIrcEvent403(IrcEventNumeric *event); // ERR_NOSUCHCHANNEL
- Q_INVOKABLE void processIrcEvent432(IrcEventNumeric *event); // ERR_ERRONEUSNICKNAME
- Q_INVOKABLE void processIrcEvent433(IrcEventNumeric *event); // ERR_NICKNAMEINUSE
- Q_INVOKABLE void processIrcEvent437(IrcEventNumeric *event); // ERR_UNAVAILRESOURCE
+ Q_INVOKABLE void processIrcEvent001(IrcEventNumeric* event); // RPL_WELCOME
+ Q_INVOKABLE void processIrcEvent005(IrcEvent* event); // RPL_ISUPPORT
+ Q_INVOKABLE void processIrcEvent221(IrcEvent* event); // RPL_UMODEIS
+ Q_INVOKABLE void processIrcEvent250(IrcEvent* event); // RPL_STATSCONN
+ Q_INVOKABLE void processIrcEvent265(IrcEvent* event); // RPL_LOCALUSERS
+ Q_INVOKABLE void processIrcEvent266(IrcEvent* event); // RPL_GLOBALUSERS
+ Q_INVOKABLE void processIrcEvent301(IrcEvent* event); // RPL_AWAY
+ Q_INVOKABLE void processIrcEvent305(IrcEvent* event); // RPL_UNAWAY
+ Q_INVOKABLE void processIrcEvent306(IrcEvent* event); // RPL_NOWAWAY
+ Q_INVOKABLE void processIrcEvent307(IrcEvent* event); // RPL_WHOISSERVICE
+ Q_INVOKABLE void processIrcEvent310(IrcEvent* event); // RPL_SUSERHOST
+ Q_INVOKABLE void processIrcEvent311(IrcEvent* event); // RPL_WHOISUSER
+ Q_INVOKABLE void processIrcEvent312(IrcEvent* event); // RPL_WHOISSERVER
+ Q_INVOKABLE void processIrcEvent313(IrcEvent* event); // RPL_WHOISOPERATOR
+ Q_INVOKABLE void processIrcEvent315(IrcEvent* event); // RPL_ENDOFWHO
+ Q_INVOKABLE void processIrcEvent317(IrcEvent* event); // RPL_WHOISIDLE
+ Q_INVOKABLE void processIrcEvent322(IrcEvent* event); // RPL_LIST
+ Q_INVOKABLE void processIrcEvent323(IrcEvent* event); // RPL_LISTEND
+ Q_INVOKABLE void processIrcEvent324(IrcEvent* event); // RPL_CHANNELMODEIS
+ Q_INVOKABLE void processIrcEvent330(IrcEvent* event); // RPL_WHOISACCOUNT (quakenet/snircd/undernet)
+ Q_INVOKABLE void processIrcEvent331(IrcEvent* event); // RPL_NOTOPIC
+ Q_INVOKABLE void processIrcEvent332(IrcEvent* event); // RPL_TOPIC
+ Q_INVOKABLE void processIrcEvent352(IrcEvent* event); // RPL_WHOREPLY
+ Q_INVOKABLE void processIrcEvent353(IrcEvent* event); // RPL_NAMREPLY
+ Q_INVOKABLE void processIrcEvent354(IrcEvent* event); // RPL_WHOSPCRPL
+ Q_INVOKABLE void processIrcEvent403(IrcEventNumeric* event); // ERR_NOSUCHCHANNEL
+ Q_INVOKABLE void processIrcEvent432(IrcEventNumeric* event); // ERR_ERRONEUSNICKNAME
+ Q_INVOKABLE void processIrcEvent433(IrcEventNumeric* event); // ERR_NICKNAMEINUSE
+ Q_INVOKABLE void processIrcEvent437(IrcEventNumeric* event); // ERR_UNAVAILRESOURCE
// Q_INVOKABLE void processIrcEvent(IrcEvent *event);
/* CTCP handlers */
- Q_INVOKABLE void processCtcpEvent(CtcpEvent *event);
+ Q_INVOKABLE void processCtcpEvent(CtcpEvent* event);
- Q_INVOKABLE void handleCtcpAction(CtcpEvent *event);
- Q_INVOKABLE void handleCtcpClientinfo(CtcpEvent *event);
- Q_INVOKABLE void handleCtcpDcc(CtcpEvent *event);
- Q_INVOKABLE void handleCtcpPing(CtcpEvent *event);
- Q_INVOKABLE void handleCtcpTime(CtcpEvent *event);
- Q_INVOKABLE void handleCtcpVersion(CtcpEvent *event);
- Q_INVOKABLE void defaultHandler(const QString &ctcpCmd, CtcpEvent *event);
+ Q_INVOKABLE void handleCtcpAction(CtcpEvent* event);
+ Q_INVOKABLE void handleCtcpClientinfo(CtcpEvent* event);
+ Q_INVOKABLE void handleCtcpDcc(CtcpEvent* event);
+ Q_INVOKABLE void handleCtcpPing(CtcpEvent* event);
+ Q_INVOKABLE void handleCtcpTime(CtcpEvent* event);
+ Q_INVOKABLE void handleCtcpVersion(CtcpEvent* event);
+ Q_INVOKABLE void defaultHandler(const QString& ctcpCmd, CtcpEvent* event);
signals:
- void newEvent(Event *event);
+ void newEvent(Event* event);
protected:
- bool checkParamCount(IrcEvent *event, int minParams);
- inline CoreNetwork *coreNetwork(NetworkEvent *e) const { return qobject_cast<CoreNetwork *>(e->network()); }
- void tryNextNick(NetworkEvent *e, const QString &errnick, bool erroneous = false);
+ bool checkParamCount(IrcEvent* event, int minParams);
+ inline CoreNetwork* coreNetwork(NetworkEvent* e) const { return qobject_cast<CoreNetwork*>(e->network()); }
+ void tryNextNick(NetworkEvent* e, const QString& errnick, bool erroneous = false);
private slots:
//! Joins after a netsplit
/** This slot handles a bulk-join after a netsplit is over
- * \param net The network
- * \param channel The channel the users joined
- * \param users The list of users that joind the channel
- * \param modes The list of modes the users get set
- * \param quitMessage The message we received when the netsplit occured
- */
- void handleNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes, const QString &quitMessage);
+ * \param net The network
+ * \param channel The channel the users joined
+ * \param users The list of users that joind the channel
+ * \param modes The list of modes the users get set
+ * \param quitMessage The message we received when the netsplit occured
+ */
+ void handleNetsplitJoin(Network* net, const QString& channel, const QStringList& users, const QStringList& modes, const QString& quitMessage);
//! Quits after a netsplit
/** This slot handles a bulk-quit after a netsplit occured
- * \param net The network
- * \param channel The channel the users quitted
- * \param users The list of users that got split
- * \param quitMessage The message we received when the netsplit occured
- */
- void handleNetsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage);
+ * \param net The network
+ * \param channel The channel the users quitted
+ * \param users The list of users that got split
+ * \param quitMessage The message we received when the netsplit occured
+ */
+ void handleNetsplitQuit(Network* net, const QString& channel, const QStringList& users, const QString& quitMessage);
//! Netsplit finished
/** This slot deletes the netsplit object that sent the finished() signal
- */
+ */
void handleNetsplitFinished();
- void handleEarlyNetsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes);
+ void handleEarlyNetsplitJoin(Network* net, const QString& channel, const QStringList& users, const QStringList& modes);
//! Destroy any existing netsplits
/** This slot deletes all netsplit objects
- * Used to get rid of existing netsplits on network reconnect
- * \param network The network we want to clear
- */
+ * Used to get rid of existing netsplits on network reconnect
+ * \param network The network we want to clear
+ */
void destroyNetsplits(NetworkId network);
private:
- CoreSession *_coreSession;
+ CoreSession* _coreSession;
// structure to organize netsplits
// key: quit message
// value: the corresponding netsplit object
- QHash<Network *, QHash<QString, Netsplit *> > _netsplits;
+ QHash<Network*, QHash<QString, Netsplit*>> _netsplits;
/**
* Process given WHO reply information, updating user data, channel modes, etc as needed
* @param[in] awayStateAndModes Nick away-state and modes (e.g. G@)
* @param[in] realname Nick realname
*/
- void processWhoInformation (Network *net, const QString &targetChannel, IrcUser *ircUser,
- const QString &server, const QString &user, const QString &host,
- const QString &awayStateAndModes, const QString &realname);
+ void processWhoInformation(Network* net,
+ const QString& targetChannel,
+ IrcUser* ircUser,
+ const QString& server,
+ const QString& user,
+ const QString& host,
+ const QString& awayStateAndModes,
+ const QString& realname);
};
-
#endif
CoreSettings::CoreSettings(QString group)
: Settings(std::move(group), Quassel::buildInfo().coreApplicationName)
-{
-}
+{}
-
-void CoreSettings::setStorageSettings(const QVariant &data)
+void CoreSettings::setStorageSettings(const QVariant& data)
{
setLocalValue("StorageSettings", data);
}
-
-QVariant CoreSettings::storageSettings(const QVariant &def) const
+QVariant CoreSettings::storageSettings(const QVariant& def) const
{
return localValue("StorageSettings", def);
}
-
-void CoreSettings::setAuthSettings(const QVariant &data)
+void CoreSettings::setAuthSettings(const QVariant& data)
{
setLocalValue("AuthSettings", data);
}
-
-QVariant CoreSettings::authSettings(const QVariant &def) const
+QVariant CoreSettings::authSettings(const QVariant& def) const
{
return localValue("AuthSettings", def);
}
return localValue("DatabaseSettings");
}
-
-void CoreSettings::setCoreState(const QVariant &data)
+void CoreSettings::setCoreState(const QVariant& data)
{
setLocalValue("CoreState", data);
}
-
-QVariant CoreSettings::coreState(const QVariant &def) const
+QVariant CoreSettings::coreState(const QVariant& def) const
{
return localValue("CoreState", def);
}
public:
CoreSettings(QString group = "Core");
- void setStorageSettings(const QVariant &data);
- QVariant storageSettings(const QVariant &def = {}) const;
+ void setStorageSettings(const QVariant& data);
+ QVariant storageSettings(const QVariant& def = {}) const;
- void setAuthSettings(const QVariant &data);
- QVariant authSettings(const QVariant &def = {}) const;
+ void setAuthSettings(const QVariant& data);
+ QVariant authSettings(const QVariant& def = {}) const;
QVariant oldDbSettings() const; // FIXME remove
- void setCoreState(const QVariant &data);
- QVariant coreState(const QVariant &def = {}) const;
+ void setCoreState(const QVariant& data);
+ QVariant coreState(const QVariant& def = {}) const;
};
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include <QtEndian>
+#include "coretransfer.h"
#include <QCoreApplication>
#include <QTcpSocket>
+#include <QtEndian>
-#include "coretransfer.h"
#include "util.h"
const qint64 chunkSize = 16 * 1024;
-CoreTransfer::CoreTransfer(Direction direction, const QString &nick, const QString &fileName, const QHostAddress &address, quint16 port, quint64 fileSize, QObject *parent)
- : Transfer(direction, nick, fileName, address, port, fileSize, parent),
- _socket(nullptr),
- _pos(0),
- _reading(false)
-{
-
-}
-
+CoreTransfer::CoreTransfer(Direction direction,
+ const QString& nick,
+ const QString& fileName,
+ const QHostAddress& address,
+ quint16 port,
+ quint64 fileSize,
+ QObject* parent)
+ : Transfer(direction, nick, fileName, address, port, fileSize, parent)
+ , _socket(nullptr)
+ , _pos(0)
+ , _reading(false)
+{}
quint64 CoreTransfer::transferred() const
{
return _pos;
}
-
void CoreTransfer::cleanUp()
{
if (_socket) {
_reading = false;
}
-
void CoreTransfer::onSocketDisconnected()
{
if (status() == Status::Connecting || status() == Status::Transferring) {
cleanUp();
}
-
void CoreTransfer::onSocketError(QAbstractSocket::SocketError error)
{
Q_UNUSED(error)
}
}
-
void CoreTransfer::requestAccepted(PeerPtr peer)
{
if (_peer || !peer || status() != Status::New)
- return; // transfer was already accepted
+ return; // transfer was already accepted
_peer = peer;
setStatus(Status::Pending);
start();
}
-
void CoreTransfer::requestRejected(PeerPtr peer)
{
if (_peer || status() != Status::New)
emit rejected(peer);
}
-
void CoreTransfer::start()
{
if (!_peer || status() != Status::Pending || direction() != Direction::Receive)
setupConnectionForReceive();
}
-
void CoreTransfer::setupConnectionForReceive()
{
if (port() == 0) {
_socket->connectToHost(address(), port());
}
-
void CoreTransfer::startReceiving()
{
setStatus(Status::Transferring);
}
-
void CoreTransfer::onDataReceived()
{
- if (_reading) // since we're spinning the event loop, we may get another readyRead() and thus reentrancy
+ if (_reading) // since we're spinning the event loop, we may get another readyRead() and thus reentrancy
return;
_reading = true;
return;
QCoreApplication::processEvents(); // don't block the rest of the core/client communication
- if (!_socket) // just in case something happened during spinning the event loop that killed our socket
+ if (!_socket) // just in case something happened during spinning the event loop that killed our socket
return;
}
// Send ack to sender. The DCC protocol only specifies 32 bit values, but modern clients (i.e. those who can send files
// larger than 4 GB) will ignore this anyway...
- quint32 ack = qToBigEndian((quint32)_pos);// qDebug() << Q_FUNC_INFO << _pos;
- _socket->write((char *)&ack, 4);
+ quint32 ack = qToBigEndian((quint32)_pos); // qDebug() << Q_FUNC_INFO << _pos;
+ _socket->write((char*)&ack, 4);
if (_pos > fileSize()) {
qWarning() << "DCC Receive: Got more data than expected!";
}
else if (_pos == fileSize()) {
qDebug() << "DCC Receive: Transfer finished";
- if (relayData(QByteArray(), false)) // empty buffer
+ if (relayData(QByteArray(), false)) // empty buffer
setStatus(Status::Completed);
}
_reading = false;
}
-
-bool CoreTransfer::relayData(const QByteArray &data, bool requireChunkSize)
+bool CoreTransfer::relayData(const QByteArray& data, bool requireChunkSize)
{
// safeguard against a disconnecting quasselclient
if (!_peer) {
// we only want to send data to the client once we have reached the chunksize
if (_buffer.size() > 0 && (_buffer.size() >= chunkSize || !requireChunkSize)) {
- Peer *p = _peer.data();
+ Peer* p = _peer.data();
SYNC_OTHER(dataReceived, ARG(p), ARG(_buffer));
_buffer.clear();
}
#include <QPointer>
-#include "transfer.h"
#include "peer.h"
+#include "transfer.h"
class QTcpSocket;
Q_OBJECT
public:
- CoreTransfer(Direction direction, const QString &nick, const QString &fileName, const QHostAddress &address, quint16 port, quint64 size = 0, QObject *parent = nullptr);
+ CoreTransfer(Direction direction,
+ const QString& nick,
+ const QString& fileName,
+ const QHostAddress& address,
+ quint16 port,
+ quint64 size = 0,
+ QObject* parent = nullptr);
quint64 transferred() const override;
private:
void setupConnectionForReceive();
- bool relayData(const QByteArray &data, bool requireChunkSize);
+ bool relayData(const QByteArray& data, bool requireChunkSize);
void cleanUp() override;
QPointer<Peer> _peer;
- QTcpSocket *_socket;
+ QTcpSocket* _socket;
quint64 _pos;
QByteArray _buffer;
bool _reading;
#include "coreuserinputhandler.h"
-#include "util.h"
+#include <QRegExp>
#include "ctcpparser.h"
-
-#include <QRegExp>
+#include "util.h"
#ifdef HAVE_QCA2
-# include "cipher.h"
+# include "cipher.h"
#endif
-CoreUserInputHandler::CoreUserInputHandler(CoreNetwork *parent)
+CoreUserInputHandler::CoreUserInputHandler(CoreNetwork* parent)
: CoreBasicHandler(parent)
-{
-}
-
+{}
-void CoreUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleUserInput(const BufferInfo& bufferInfo, const QString& msg)
{
if (msg.isEmpty())
return;
}
}
-
// ====================
// Public Slots
// ====================
-void CoreUserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg,
- const bool skipFormatting)
+void CoreUserInputHandler::handleAway(const BufferInfo& bufferInfo, const QString& msg, const bool skipFormatting)
{
Q_UNUSED(bufferInfo)
if (msg.startsWith("-all")) {
issueAway(msg, true /* force away */, skipFormatting);
}
-
-void CoreUserInputHandler::issueAway(const QString &msg, bool autoCheck, const bool skipFormatting)
+void CoreUserInputHandler::issueAway(const QString& msg, bool autoCheck, const bool skipFormatting)
{
QString awayMsg = msg;
- IrcUser *me = network()->me();
+ IrcUser* me = network()->me();
// Only apply timestamp formatting when requested
// This avoids re-processing any existing away message when the core restarts, so chained escape
// if there is no message supplied we have to check if we are already away or not
if (autoCheck && msg.isEmpty()) {
if (me && !me->isAway()) {
- Identity *identity = network()->identityPtr();
+ Identity* identity = network()->identityPtr();
if (identity) {
awayMsg = formatCurrentDateTimeInString(identity->awayReason());
}
putCmd("AWAY", serverEncode(awayMsg));
}
-
-void CoreUserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleBan(const BufferInfo& bufferInfo, const QString& msg)
{
banOrUnban(bufferInfo, msg, true);
}
-
-void CoreUserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleUnban(const BufferInfo& bufferInfo, const QString& msg)
{
banOrUnban(bufferInfo, msg, false);
}
-
-void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban)
+void CoreUserInputHandler::banOrUnban(const BufferInfo& bufferInfo, const QString& msg, bool ban)
{
QString banChannel;
QString banUser;
}
if (!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) {
- IrcUser *ircuser = network()->ircUser(params[0]);
+ IrcUser* ircuser = network()->ircUser(params[0]);
// generalizedHost changes <nick> to *!ident@*.sld.tld.
QString generalizedHost = ircuser->host();
if (generalizedHost.isEmpty()) {
}
static QRegExp ipAddress(R"(\d+\.\d+\.\d+\.\d+)");
- if (ipAddress.exactMatch(generalizedHost)) {
+ if (ipAddress.exactMatch(generalizedHost)) {
int lastDotPos = generalizedHost.lastIndexOf('.') + 1;
generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*');
}
- else if (generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) {
- int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1);
+ else if (generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".") - 1) != -1) {
+ int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".") - 1);
generalizedHost.replace(0, secondLastPeriodPosition, "*");
}
banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost);
emit putRawLine(serverEncode(banMsg));
}
-
-void CoreUserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleCtcp(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo)
// FIXME make this a proper event
coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), nick, ctcpTag, message);
- emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage,
- network()->myNick(), Message::Flag::Self);
+ emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick(), Message::Flag::Self);
}
-
-void CoreUserInputHandler::handleDelkey(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleDelkey(const BufferInfo& bufferInfo, const QString& msg)
{
QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
#ifdef HAVE_QCA2
return;
if (!Cipher::neededFeaturesAvailable()) {
- emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
+ emit displayMsg(Message::Error,
+ typeByTarget(bufname),
+ bufname,
+ tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
return;
}
parms.prepend(bufferInfo.bufferName());
if (parms.isEmpty()) {
- emit displayMsg(Message::Info, typeByTarget(bufname), bufname,
- tr("[usage] /delkey <nick|channel> deletes the encryption key for nick or channel or just /delkey when in a channel or query."));
+ emit displayMsg(Message::Info,
+ typeByTarget(bufname),
+ bufname,
+ tr("[usage] /delkey <nick|channel> deletes the encryption key for nick or channel or just /delkey when in a "
+ "channel or query."));
return;
}
#else
Q_UNUSED(msg)
- emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
- "with support for the Qt Cryptographic Architecture (QCA2) library. "
- "Contact your distributor about a Quassel package with QCA2 "
- "support, or rebuild Quassel with QCA2 present."));
+ emit displayMsg(Message::Error,
+ typeByTarget(bufname),
+ bufname,
+ tr("Error: Setting an encryption key requires Quassel to have been built "
+ "with support for the Qt Cryptographic Architecture (QCA2) library. "
+ "Contact your distributor about a Quassel package with QCA2 "
+ "support, or rebuild Quassel with QCA2 present."));
#endif
}
-void CoreUserInputHandler::doMode(const BufferInfo &bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString &nicks)
+void CoreUserInputHandler::doMode(const BufferInfo& bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString& nicks)
{
QString m;
bool isNumber;
int maxModes = network()->support("MODES").toInt(&isNumber);
- if (!isNumber || maxModes == 0) maxModes = 1;
+ if (!isNumber || maxModes == 0)
+ maxModes = 1;
QStringList nickList;
- if (nicks == "*" && bufferInfo.type() == BufferInfo::ChannelBuffer) { // All users in channel
+ if (nicks == "*" && bufferInfo.type() == BufferInfo::ChannelBuffer) { // All users in channel
const QList<IrcUser*> users = network()->ircChannel(bufferInfo.bufferName())->ircUsers();
- foreach(IrcUser *user, users) {
+ foreach (IrcUser* user, users) {
if ((addOrRemove == '+' && !network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode))
|| (addOrRemove == '-' && network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode)))
nickList.append(user->nick());
}
- } else {
+ }
+ else {
nickList = nicks.split(' ', QString::SkipEmptyParts);
}
- if (nickList.count() == 0) return;
+ if (nickList.count() == 0)
+ return;
while (!nickList.isEmpty()) {
int amount = qMin(nickList.count(), maxModes);
- QString m = addOrRemove; for(int i = 0; i < amount; i++) m += mode;
+ QString m = addOrRemove;
+ for (int i = 0; i < amount; i++)
+ m += mode;
QStringList params;
params << bufferInfo.bufferName() << m;
- for(int i = 0; i < amount; i++) params << nickList.takeFirst();
+ for (int i = 0; i < amount; i++)
+ params << nickList.takeFirst();
emit putCmd("MODE", serverEncode(params));
}
}
-
-void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &nicks)
+void CoreUserInputHandler::handleDeop(const BufferInfo& bufferInfo, const QString& nicks)
{
doMode(bufferInfo, '-', 'o', nicks);
}
-
-void CoreUserInputHandler::handleDehalfop(const BufferInfo &bufferInfo, const QString &nicks)
+void CoreUserInputHandler::handleDehalfop(const BufferInfo& bufferInfo, const QString& nicks)
{
doMode(bufferInfo, '-', 'h', nicks);
}
-
-void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &nicks)
+void CoreUserInputHandler::handleDevoice(const BufferInfo& bufferInfo, const QString& nicks)
{
doMode(bufferInfo, '-', 'v', nicks);
}
-void CoreUserInputHandler::handleHalfop(const BufferInfo &bufferInfo, const QString &nicks)
+void CoreUserInputHandler::handleHalfop(const BufferInfo& bufferInfo, const QString& nicks)
{
doMode(bufferInfo, '+', 'h', nicks);
}
-void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &nicks) {
- doMode(bufferInfo, '+', 'o', nicks);
+void CoreUserInputHandler::handleOp(const BufferInfo& bufferInfo, const QString& nicks)
+{
+ doMode(bufferInfo, '+', 'o', nicks);
}
-
-void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleInvite(const BufferInfo& bufferInfo, const QString& msg)
{
QStringList params;
params << msg << bufferInfo.bufferName();
emit putCmd("INVITE", serverEncode(params));
}
-
-void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleJoin(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo);
}
}
- static const char *cmd = "JOIN";
+ static const char* cmd = "JOIN";
i = 0;
QStringList joinChans, joinKeys;
int slicesize = chans.count();
}
}
-
-void CoreUserInputHandler::handleKeyx(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleKeyx(const BufferInfo& bufferInfo, const QString& msg)
{
QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
#ifdef HAVE_QCA2
return;
if (!Cipher::neededFeaturesAvailable()) {
- emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
+ emit displayMsg(Message::Error,
+ typeByTarget(bufname),
+ bufname,
+ tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
return;
}
if (parms.count() == 0 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
parms.prepend(bufferInfo.bufferName());
else if (parms.count() != 1) {
- emit displayMsg(Message::Info, typeByTarget(bufname), bufname,
- tr("[usage] /keyx [<nick>] Initiates a DH1080 key exchange with the target."));
+ emit displayMsg(Message::Info,
+ typeByTarget(bufname),
+ bufname,
+ tr("[usage] /keyx [<nick>] Initiates a DH1080 key exchange with the target."));
return;
}
return;
}
- Cipher *cipher = network()->cipher(target);
- if (!cipher) // happens when there is no CoreIrcChannel for the target
+ Cipher* cipher = network()->cipher(target);
+ if (!cipher) // happens when there is no CoreIrcChannel for the target
return;
QByteArray pubKey = cipher->initKeyExchange();
}
#else
Q_UNUSED(msg)
- emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
- "with support for the Qt Cryptographic Architecture (QCA) library. "
- "Contact your distributor about a Quassel package with QCA "
- "support, or rebuild Quassel with QCA present."));
+ emit displayMsg(Message::Error,
+ typeByTarget(bufname),
+ bufname,
+ tr("Error: Setting an encryption key requires Quassel to have been built "
+ "with support for the Qt Cryptographic Architecture (QCA) library. "
+ "Contact your distributor about a Quassel package with QCA "
+ "support, or rebuild Quassel with QCA present."));
#endif
}
-
-void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleKick(const BufferInfo& bufferInfo, const QString& msg)
{
QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed();
emit putCmd("KICK", params);
}
-
-void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleKill(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo)
QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty);
emit putCmd("KILL", params);
}
-
-void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleList(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo)
emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts)));
}
-
-void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleMe(const BufferInfo& bufferInfo, const QString& msg)
{
if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
return; // server buffer
foreach (auto message, messages) {
// Handle each separated message independently
- coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(),
- "ACTION", message);
- emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), message,
- network()->myNick(), Message::Self);
+ coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(), "ACTION", message);
+ emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), message, network()->myNick(), Message::Self);
}
}
-
-void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleMode(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo)
if (!params.isEmpty()) {
if (params[0] == "-reset" && params.count() == 1) {
network()->resetPersistentModes();
- emit displayMsg(Message::Info, BufferInfo::StatusBuffer, "",
- tr("Your persistent modes have been reset."));
+ emit displayMsg(Message::Info, BufferInfo::StatusBuffer, "", tr("Your persistent modes have been reset."));
return;
}
if (!network()->isChannelName(params[0]) && !network()->isMyNick(params[0]))
// If the first argument is neither a channel nor us (user modes are only to oneself)
// the current buffer is assumed to be the target.
// If the current buffer returns no name (e.g. status buffer), assume target is us.
- params.prepend(!bufferInfo.bufferName().isEmpty() ?
- bufferInfo.bufferName() : network()->myNick());
+ params.prepend(!bufferInfo.bufferName().isEmpty() ? bufferInfo.bufferName() : network()->myNick());
if (network()->isMyNick(params[0]) && params.count() == 2)
network()->updateIssuedModes(params[1]);
}
emit putCmd("MODE", serverEncode(params));
}
-
// TODO: show privmsgs
-void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleMsg(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo);
if (!msg.contains(' '))
QString target = msg.section(' ', 0, 0);
QString msgSection = msg.section(' ', 1);
- std::function<QByteArray(const QString &, const QString &)> encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray {
- return userEncode(target, message);
- };
+ std::function<QByteArray(const QString&, const QString&)> encodeFunc =
+ [this](const QString& target, const QString& message) -> QByteArray { return userEncode(target, message); };
#ifdef HAVE_QCA2
putPrivmsg(target, msgSection, encodeFunc, network()->cipher(target));
#endif
}
-
-void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleNick(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo)
QString nick = msg.section(' ', 0, 0);
emit putCmd("NICK", serverEncode(nick));
}
-
-void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleNotice(const BufferInfo& bufferInfo, const QString& msg)
{
QString bufferName = msg.section(' ', 0, 0);
QList<QByteArray> params;
params.clear();
params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), message);
emit putCmd("NOTICE", params);
- emit displayMsg(Message::Notice, typeByTarget(bufferName), bufferName, message,
- network()->myNick(), Message::Self);
+ emit displayMsg(Message::Notice, typeByTarget(bufferName), bufferName, message, network()->myNick(), Message::Self);
}
}
-
-
-void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleOper(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo)
emit putRawLine(serverEncode(QString("OPER %1").arg(msg)));
}
-
-void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handlePart(const BufferInfo& bufferInfo, const QString& msg)
{
QList<QByteArray> params;
QString partReason;
emit putCmd("PART", params);
}
-
-void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handlePing(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo)
putCmd("PING", serverEncode(param), QByteArray(), true);
}
-
-void CoreUserInputHandler::handlePrint(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handlePrint(const BufferInfo& bufferInfo, const QString& msg)
{
if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
return; // server buffer
emit displayMsg(Message::Info, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self);
}
-
// TODO: implement queries
-void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleQuery(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo)
QString target = msg.section(' ', 0, 0);
foreach (auto message, messages) {
// Handle each separated message independently
if (message.isEmpty()) {
- emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target,
- tr("Starting query with %1").arg(target), network()->myNick(),
+ emit displayMsg(Message::Server,
+ BufferInfo::QueryBuffer,
+ target,
+ tr("Starting query with %1").arg(target),
+ network()->myNick(),
Message::Self);
// handleMsg is a no-op if message is empty
- } else {
- emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message,
- network()->myNick(), Message::Self);
+ }
+ else {
+ emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self);
// handleMsg needs the target specified at the beginning of the message
handleMsg(bufferInfo, target + " " + message);
}
}
}
-
-void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleQuit(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo)
network()->disconnectFromIrc(true, msg);
}
-
-void CoreUserInputHandler::issueQuit(const QString &reason, bool forceImmediate)
+void CoreUserInputHandler::issueQuit(const QString& reason, bool forceImmediate)
{
// If needing an immediate QUIT (e.g. core shutdown), prepend this to the queue
emit putCmd("QUIT", serverEncode(reason), QByteArray(), forceImmediate);
}
-
-void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleQuote(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo)
emit putRawLine(serverEncode(msg));
}
-
-void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleSay(const BufferInfo& bufferInfo, const QString& msg)
{
if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
return; // server buffer
- std::function<QByteArray(const QString &, const QString &)> encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray {
- return channelEncode(target, message);
- };
+ std::function<QByteArray(const QString&, const QString&)> encodeFunc =
+ [this](const QString& target, const QString& message) -> QByteArray { return channelEncode(target, message); };
// Split apart messages at line feeds. The IRC protocol uses those to separate commands, so
// they need to be split into multiple messages.
foreach (auto message, messages) {
// Handle each separated message independently
#ifdef HAVE_QCA2
- putPrivmsg(bufferInfo.bufferName(), message, encodeFunc,
- network()->cipher(bufferInfo.bufferName()));
+ putPrivmsg(bufferInfo.bufferName(), message, encodeFunc, network()->cipher(bufferInfo.bufferName()));
#else
putPrivmsg(bufferInfo.bufferName(), message, encodeFunc);
#endif
- emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), message,
- network()->myNick(), Message::Self);
+ emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), message, network()->myNick(), Message::Self);
}
}
-
-void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleSetkey(const BufferInfo& bufferInfo, const QString& msg)
{
QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
#ifdef HAVE_QCA2
return;
if (!Cipher::neededFeaturesAvailable()) {
- emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
+ emit displayMsg(Message::Error,
+ typeByTarget(bufname),
+ bufname,
+ tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
return;
}
if (parms.count() == 1 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages())
parms.prepend(bufferInfo.bufferName());
else if (parms.count() != 2) {
- emit displayMsg(Message::Info, typeByTarget(bufname), bufname,
- tr("[usage] /setkey <nick|channel> <key> sets the encryption key for nick or channel. "
- "/setkey <key> when in a channel or query buffer sets the key for it."));
+ emit displayMsg(Message::Info,
+ typeByTarget(bufname),
+ bufname,
+ tr("[usage] /setkey <nick|channel> <key> sets the encryption key for nick or channel. "
+ "/setkey <key> when in a channel or query buffer sets the key for it."));
return;
}
emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 has been set.").arg(target));
#else
Q_UNUSED(msg)
- emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
- "with support for the Qt Cryptographic Architecture (QCA) library. "
- "Contact your distributor about a Quassel package with QCA "
- "support, or rebuild Quassel with QCA present."));
+ emit displayMsg(Message::Error,
+ typeByTarget(bufname),
+ bufname,
+ tr("Error: Setting an encryption key requires Quassel to have been built "
+ "with support for the Qt Cryptographic Architecture (QCA) library. "
+ "Contact your distributor about a Quassel package with QCA "
+ "support, or rebuild Quassel with QCA present."));
#endif
}
-
-void CoreUserInputHandler::handleShowkey(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleShowkey(const BufferInfo& bufferInfo, const QString& msg)
{
QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName();
#ifdef HAVE_QCA2
return;
if (!Cipher::neededFeaturesAvailable()) {
- emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
+ emit displayMsg(Message::Error,
+ typeByTarget(bufname),
+ bufname,
+ tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin."));
return;
}
parms.prepend(bufferInfo.bufferName());
if (parms.isEmpty()) {
- emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("[usage] /showkey <nick|channel> shows the encryption key for nick or channel or just /showkey when in a channel or query."));
+ emit displayMsg(Message::Info,
+ typeByTarget(bufname),
+ bufname,
+ tr("[usage] /showkey <nick|channel> shows the encryption key for nick or channel or just /showkey when in a "
+ "channel or query."));
return;
}
return;
}
- emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key)));
+ emit displayMsg(Message::Info,
+ typeByTarget(bufname),
+ bufname,
+ tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key)));
#else
Q_UNUSED(msg)
- emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built "
- "with support for the Qt Cryptographic Architecture (QCA2) library. "
- "Contact your distributor about a Quassel package with QCA2 "
- "support, or rebuild Quassel with QCA2 present."));
+ emit displayMsg(Message::Error,
+ typeByTarget(bufname),
+ bufname,
+ tr("Error: Setting an encryption key requires Quassel to have been built "
+ "with support for the Qt Cryptographic Architecture (QCA2) library. "
+ "Contact your distributor about a Quassel package with QCA2 "
+ "support, or rebuild Quassel with QCA2 present."));
#endif
}
-
-void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleTopic(const BufferInfo& bufferInfo, const QString& msg)
{
if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages())
return;
params << serverEncode(bufferInfo.bufferName());
if (!msg.isEmpty()) {
-# ifdef HAVE_QCA2
+#ifdef HAVE_QCA2
params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg));
-# else
+#else
params << channelEncode(bufferInfo.bufferName(), msg);
-# endif
+#endif
}
emit putCmd("TOPIC", params);
}
-
-void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleVoice(const BufferInfo& bufferInfo, const QString& msg)
{
QStringList nicks = msg.split(' ', QString::SkipEmptyParts);
- QString m = "+"; for (int i = 0; i < nicks.count(); i++) m += 'v';
+ QString m = "+";
+ for (int i = 0; i < nicks.count(); i++)
+ m += 'v';
QStringList params;
params << bufferInfo.bufferName() << m << nicks;
emit putCmd("MODE", serverEncode(params));
}
-
-void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleWait(const BufferInfo& bufferInfo, const QString& msg)
{
int splitPos = msg.indexOf(';');
if (splitPos <= 0)
_delayedCommands[startTimer(delay)] = Command(bufferInfo, command);
}
-
-void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleWho(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo)
emit putCmd("WHO", serverEncode(msg.split(' ')));
}
-
-void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleWhois(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo)
emit putCmd("WHOIS", serverEncode(msg.split(' ')));
}
-
-void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::handleWhowas(const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo)
emit putCmd("WHOWAS", serverEncode(msg.split(' ')));
}
-
-void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg)
+void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo& bufferInfo, const QString& msg)
{
Q_UNUSED(bufferInfo);
emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" ")));
}
-
-void CoreUserInputHandler::putPrivmsg(const QString &target, const QString &message, std::function<QByteArray(const QString &, const QString &)> encodeFunc, Cipher *cipher)
+void CoreUserInputHandler::putPrivmsg(const QString& target,
+ const QString& message,
+ std::function<QByteArray(const QString&, const QString&)> encodeFunc,
+ Cipher* cipher)
{
Q_UNUSED(cipher);
QString cmd("PRIVMSG");
QByteArray targetEnc = serverEncode(target);
- std::function<QList<QByteArray>(QString &)> cmdGenerator = [&] (QString &splitMsg) -> QList<QByteArray> {
+ std::function<QList<QByteArray>(QString&)> cmdGenerator = [&](QString& splitMsg) -> QList<QByteArray> {
QByteArray splitMsgEnc = encodeFunc(target, splitMsg);
#ifdef HAVE_QCA2
putCmd(cmd, network()->splitMessage(cmd, message, cmdGenerator));
}
-
// returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long
-int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> ¶ms)
+int CoreUserInputHandler::lastParamOverrun(const QString& cmd, const QList<QByteArray>& params)
{
// the server will pass our message truncated to 512 bytes including CRLF with the following format:
// ":prefix COMMAND param0 param1 :lastparam"
// where prefix = "nickname!user@host"
// that means that the last message can be as long as:
- // 512 - nicklen - userlen - hostlen - commandlen - sum(param[0]..param[n-1])) - 2 (for CRLF) - 4 (":!@" + 1space between prefix and command) - max(paramcount - 1, 0) (space for simple params) - 2 (space and colon for last param)
- IrcUser *me = network()->me();
- int maxLen = 480 - cmd.toLatin1().count(); // educated guess in case we don't know us (yet?)
+ // 512 - nicklen - userlen - hostlen - commandlen - sum(param[0]..param[n-1])) - 2 (for CRLF) - 4 (":!@" + 1space between prefix and
+ // command) - max(paramcount - 1, 0) (space for simple params) - 2 (space and colon for last param)
+ IrcUser* me = network()->me();
+ int maxLen = 480 - cmd.toLatin1().count(); // educated guess in case we don't know us (yet?)
if (me)
- maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toLatin1().count() - 6;
+ maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count()
+ - cmd.toLatin1().count() - 6;
if (!params.isEmpty()) {
for (int i = 0; i < params.count() - 1; i++) {
maxLen -= (params[i].count() + 1);
}
- maxLen -= 2; // " :" last param separator;
+ maxLen -= 2; // " :" last param separator;
if (params.last().count() > maxLen) {
return params.last().count() - maxLen;
}
}
-
#ifdef HAVE_QCA2
-QByteArray CoreUserInputHandler::encrypt(const QString &target, const QByteArray &message_, bool *didEncrypt) const
+QByteArray CoreUserInputHandler::encrypt(const QString& target, const QByteArray& message_, bool* didEncrypt) const
{
if (didEncrypt)
*didEncrypt = false;
if (!Cipher::neededFeaturesAvailable())
return message_;
- Cipher *cipher = network()->cipher(target);
+ Cipher* cipher = network()->cipher(target);
if (!cipher || cipher->key().isEmpty())
return message_;
return message;
}
-
#endif
-void CoreUserInputHandler::timerEvent(QTimerEvent *event)
+void CoreUserInputHandler::timerEvent(QTimerEvent* event)
{
if (!_delayedCommands.contains(event->timerId())) {
QObject::timerEvent(event);
// the stored command might be the result of an alias expansion, so we need to split it up again
QStringList commands = rawCommand.split(QRegExp("; ?"));
- foreach(QString command, commands) {
+ foreach (QString command, commands) {
handleUserInput(bufferInfo, command);
}
}
Q_OBJECT
public:
- CoreUserInputHandler(CoreNetwork *parent = nullptr);
- inline CoreNetwork *coreNetwork() const { return qobject_cast<CoreNetwork *>(parent()); }
+ CoreUserInputHandler(CoreNetwork* parent = nullptr);
+ inline CoreNetwork* coreNetwork() const { return qobject_cast<CoreNetwork*>(parent()); }
- void handleUserInput(const BufferInfo &bufferInfo, const QString &text);
- int lastParamOverrun(const QString &cmd, const QList<QByteArray> ¶ms);
+ void handleUserInput(const BufferInfo& bufferInfo, const QString& text);
+ int lastParamOverrun(const QString& cmd, const QList<QByteArray>& params);
public slots:
/**
* @param[in] text Away message, or blank to set unaway
* @param[in] skipFormatting If true, skip timestamp formatting codes (e.g. if already done)
*/
- void handleAway(const BufferInfo &bufferInfo, const QString &text,
- const bool skipFormatting = false);
- void handleBan(const BufferInfo &bufferInfo, const QString &text);
- void handleUnban(const BufferInfo &bufferInfo, const QString &text);
- void handleCtcp(const BufferInfo &bufferInfo, const QString &text);
- void handleDelkey(const BufferInfo &bufferInfo, const QString &text);
- void handleDeop(const BufferInfo& bufferInfo, const QString &nicks);
- void handleDehalfop(const BufferInfo& bufferInfo, const QString &nicks);
- void handleDevoice(const BufferInfo& bufferInfo, const QString &nicks);
- void handleInvite(const BufferInfo &bufferInfo, const QString &text);
- void handleJoin(const BufferInfo &bufferInfo, const QString &text);
- void handleKeyx(const BufferInfo &bufferInfo, const QString &text);
- void handleKick(const BufferInfo &bufferInfo, const QString &text);
- void handleKill(const BufferInfo &bufferInfo, const QString &text);
- void handleList(const BufferInfo &bufferInfo, const QString &text);
- void handleMe(const BufferInfo &bufferInfo, const QString &text);
- void handleMode(const BufferInfo &bufferInfo, const QString &text);
- void handleMsg(const BufferInfo &bufferInfo, const QString &text);
- void handleNick(const BufferInfo &bufferInfo, const QString &text);
- void handleNotice(const BufferInfo &bufferInfo, const QString &text);
- void handleOper(const BufferInfo &bufferInfo, const QString &text);
- void handleOp(const BufferInfo& bufferInfo, const QString &nicks);
- void handleHalfop(const BufferInfo& bufferInfo, const QString &nicks);
- void handlePart(const BufferInfo &bufferInfo, const QString &text);
- void handlePing(const BufferInfo &bufferInfo, const QString &text);
- void handlePrint(const BufferInfo &bufferInfo, const QString &text);
- void handleQuery(const BufferInfo &bufferInfo, const QString &text);
- void handleQuit(const BufferInfo &bufferInfo, const QString &text);
- void handleQuote(const BufferInfo &bufferInfo, const QString &text);
- void handleSay(const BufferInfo &bufferInfo, const QString &text);
- void handleSetkey(const BufferInfo &bufferInfo, const QString &text);
- void handleShowkey(const BufferInfo &bufferInfo, const QString &text);
- void handleTopic(const BufferInfo &bufferInfo, const QString &text);
- void handleVoice(const BufferInfo &bufferInfo, const QString &text);
- void handleWait(const BufferInfo &bufferInfo, const QString &text);
- void handleWho(const BufferInfo &bufferInfo, const QString &text);
- void handleWhois(const BufferInfo &bufferInfo, const QString &text);
- void handleWhowas(const BufferInfo &bufferInfo, const QString &text);
-
- void defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &text);
+ void handleAway(const BufferInfo& bufferInfo, const QString& text, const bool skipFormatting = false);
+ void handleBan(const BufferInfo& bufferInfo, const QString& text);
+ void handleUnban(const BufferInfo& bufferInfo, const QString& text);
+ void handleCtcp(const BufferInfo& bufferInfo, const QString& text);
+ void handleDelkey(const BufferInfo& bufferInfo, const QString& text);
+ void handleDeop(const BufferInfo& bufferInfo, const QString& nicks);
+ void handleDehalfop(const BufferInfo& bufferInfo, const QString& nicks);
+ void handleDevoice(const BufferInfo& bufferInfo, const QString& nicks);
+ void handleInvite(const BufferInfo& bufferInfo, const QString& text);
+ void handleJoin(const BufferInfo& bufferInfo, const QString& text);
+ void handleKeyx(const BufferInfo& bufferInfo, const QString& text);
+ void handleKick(const BufferInfo& bufferInfo, const QString& text);
+ void handleKill(const BufferInfo& bufferInfo, const QString& text);
+ void handleList(const BufferInfo& bufferInfo, const QString& text);
+ void handleMe(const BufferInfo& bufferInfo, const QString& text);
+ void handleMode(const BufferInfo& bufferInfo, const QString& text);
+ void handleMsg(const BufferInfo& bufferInfo, const QString& text);
+ void handleNick(const BufferInfo& bufferInfo, const QString& text);
+ void handleNotice(const BufferInfo& bufferInfo, const QString& text);
+ void handleOper(const BufferInfo& bufferInfo, const QString& text);
+ void handleOp(const BufferInfo& bufferInfo, const QString& nicks);
+ void handleHalfop(const BufferInfo& bufferInfo, const QString& nicks);
+ void handlePart(const BufferInfo& bufferInfo, const QString& text);
+ void handlePing(const BufferInfo& bufferInfo, const QString& text);
+ void handlePrint(const BufferInfo& bufferInfo, const QString& text);
+ void handleQuery(const BufferInfo& bufferInfo, const QString& text);
+ void handleQuit(const BufferInfo& bufferInfo, const QString& text);
+ void handleQuote(const BufferInfo& bufferInfo, const QString& text);
+ void handleSay(const BufferInfo& bufferInfo, const QString& text);
+ void handleSetkey(const BufferInfo& bufferInfo, const QString& text);
+ void handleShowkey(const BufferInfo& bufferInfo, const QString& text);
+ void handleTopic(const BufferInfo& bufferInfo, const QString& text);
+ void handleVoice(const BufferInfo& bufferInfo, const QString& text);
+ void handleWait(const BufferInfo& bufferInfo, const QString& text);
+ void handleWho(const BufferInfo& bufferInfo, const QString& text);
+ void handleWhois(const BufferInfo& bufferInfo, const QString& text);
+ void handleWhowas(const BufferInfo& bufferInfo, const QString& text);
+
+ void defaultHandler(QString cmd, const BufferInfo& bufferInfo, const QString& text);
/**
* Send a QUIT to the IRC server, optionally skipping the command queue.
* @param reason Reason for quitting, often displayed to other IRC clients
* @param forceImmediate Immediately quit, skipping queue of other commands
*/
- void issueQuit(const QString &reason, bool forceImmediate = false);
+ void issueQuit(const QString& reason, bool forceImmediate = false);
/**
* Issues the away command, marking as away or unaway on the current network
* @param[in] autoCheck If true, always set away, defaulting to the identity away message
* @param[in] skipFormatting If true, skip timestamp formatting codes (e.g. if already done)
*/
- void issueAway(const QString &msg, bool autoCheck = true, const bool skipFormatting = false);
+ void issueAway(const QString& msg, bool autoCheck = true, const bool skipFormatting = false);
protected:
- void timerEvent(QTimerEvent *event) override;
+ void timerEvent(QTimerEvent* event) override;
private:
- void doMode(const BufferInfo& bufferInfo, const QChar &addOrRemove, const QChar &mode, const QString &nickList);
- void banOrUnban(const BufferInfo &bufferInfo, const QString &text, bool ban);
- void putPrivmsg(const QString &target, const QString &message, std::function<QByteArray(const QString &, const QString &)> encodeFunc, Cipher *cipher = nullptr);
+ void doMode(const BufferInfo& bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString& nickList);
+ void banOrUnban(const BufferInfo& bufferInfo, const QString& text, bool ban);
+ void putPrivmsg(const QString& target,
+ const QString& message,
+ std::function<QByteArray(const QString&, const QString&)> encodeFunc,
+ Cipher* cipher = nullptr);
#ifdef HAVE_QCA2
- QByteArray encrypt(const QString &target, const QByteArray &message, bool *didEncrypt = nullptr) const;
+ QByteArray encrypt(const QString& target, const QByteArray& message, bool* didEncrypt = nullptr) const;
#endif
- struct Command {
+ struct Command
+ {
BufferInfo bufferInfo;
QString command;
- Command(BufferInfo info, QString command) : bufferInfo(std::move(info)), command(std::move(command)) {}
+ Command(BufferInfo info, QString command)
+ : bufferInfo(std::move(info))
+ , command(std::move(command))
+ {}
Command() = default;
};
QHash<int, Command> _delayedCommands;
};
-
#endif
#include "coreusersettings.h"
CoreUserSettings::CoreUserSettings(UserId uid)
- : CoreSettings(QString("CoreUser/%1").arg(uid.toInt())), user(uid)
-{
-}
-
+ : CoreSettings(QString("CoreUser/%1").arg(uid.toInt()))
+ , user(uid)
+{}
Identity CoreUserSettings::identity(IdentityId id) const
{
return Identity();
}
-
QList<IdentityId> CoreUserSettings::identityIds() const
{
QList<IdentityId> res;
- foreach(QString id, localChildKeys("Identities")) {
+ foreach (QString id, localChildKeys("Identities")) {
res << id.toInt();
}
return res;
}
-
-void CoreUserSettings::storeIdentity(const Identity &identity)
+void CoreUserSettings::storeIdentity(const Identity& identity)
{
setLocalValue(QString("Identities/%1").arg(identity.id().toInt()), qVariantFromValue(identity));
}
-
void CoreUserSettings::removeIdentity(IdentityId id)
{
removeLocalKey(QString("Identities/%1").arg(id.toInt()));
}
-
-void CoreUserSettings::setSessionState(const QVariant &data)
+void CoreUserSettings::setSessionState(const QVariant& data)
{
setLocalValue("SessionState", data);
}
-
-QVariant CoreUserSettings::sessionState(const QVariant &def) const
+QVariant CoreUserSettings::sessionState(const QVariant& def) const
{
return localValue("SessionState", def);
}
-
QVariantMap CoreUserSettings::sessionData() const
{
QVariantMap res;
- foreach(QString key, localChildKeys(QString("SessionData"))) {
+ foreach (QString key, localChildKeys(QString("SessionData"))) {
res[key] = localValue(QString("SessionData/%1").arg(key));
}
return res;
}
-
-void CoreUserSettings::setSessionValue(const QString &key, const QVariant &data)
+void CoreUserSettings::setSessionValue(const QString& key, const QVariant& data)
{
setLocalValue(QString("SessionData/%1").arg(key), data);
}
-
-QVariant CoreUserSettings::sessionValue(const QString &key, const QVariant &def) const
+QVariant CoreUserSettings::sessionValue(const QString& key, const QVariant& def) const
{
return localValue(QString("SessionData/%1").arg(key), def);
}
#pragma once
+#include <QVariantMap>
+
#include "coresettings.h"
#include "identity.h"
#include "network.h"
#include "types.h"
-#include <QVariantMap>
-
class CoreUserSettings : public CoreSettings
{
public:
Identity identity(IdentityId id) const;
QList<IdentityId> identityIds() const;
- void storeIdentity(const Identity &identity);
+ void storeIdentity(const Identity& identity);
void removeIdentity(IdentityId id);
- void setSessionState(const QVariant &data);
- QVariant sessionState(const QVariant &def = {}) const;
+ void setSessionState(const QVariant& data);
+ QVariant sessionState(const QVariant& def = {}) const;
private:
// this stuff should only be accessed by CoreSession!
QVariantMap sessionData() const;
- QVariant sessionValue(const QString &key, const QVariant &def = {}) const;
- void setSessionValue(const QString &key, const QVariant &value);
+ QVariant sessionValue(const QString& key, const QVariant& def = {}) const;
+ void setSessionValue(const QString& key, const QVariant& value);
UserId user;
#include "corenetworkconfig.h"
#include "coresession.h"
+#include "coreuserinputhandler.h"
#include "ctcpevent.h"
#include "messageevent.h"
-#include "coreuserinputhandler.h"
const QByteArray XDELIM = "\001";
-CtcpParser::CtcpParser(CoreSession *coreSession, QObject *parent)
- : QObject(parent),
- _coreSession(coreSession)
+CtcpParser::CtcpParser(CoreSession* coreSession, QObject* parent)
+ : QObject(parent)
+ , _coreSession(coreSession)
{
QByteArray MQUOTE = QByteArray("\020");
_ctcpMDequoteHash[MQUOTE + '0'] = QByteArray(1, '\000');
connect(this, &CtcpParser::newEvent, _coreSession->eventManager(), &EventManager::postEvent);
}
-
void CtcpParser::setStandardCtcp(bool enabled)
{
QByteArray XQUOTE = QByteArray(R"(\)");
_ctcpXDelimDequoteHash[XQUOTE + QByteArray("a")] = XDELIM;
}
-
-void CtcpParser::displayMsg(NetworkEvent *event, Message::Type msgType, const QString &msg, const QString &sender,
- const QString &target, Message::Flags msgFlags)
+void CtcpParser::displayMsg(
+ NetworkEvent* event, Message::Type msgType, const QString& msg, const QString& sender, const QString& target, Message::Flags msgFlags)
{
if (event->testFlag(EventManager::Silent))
return;
- MessageEvent *msgEvent = new MessageEvent(msgType, event->network(), msg, sender, target, msgFlags);
+ MessageEvent* msgEvent = new MessageEvent(msgType, event->network(), msg, sender, target, msgFlags);
msgEvent->setTimestamp(event->timestamp());
emit newEvent(msgEvent);
}
-
-QByteArray CtcpParser::lowLevelQuote(const QByteArray &message)
+QByteArray CtcpParser::lowLevelQuote(const QByteArray& message)
{
QByteArray quotedMessage = message;
return quotedMessage;
}
-
-QByteArray CtcpParser::lowLevelDequote(const QByteArray &message)
+QByteArray CtcpParser::lowLevelDequote(const QByteArray& message)
{
QByteArray dequotedMessage;
QByteArray messagepart;
// copy dequote Message
for (int i = 0; i < message.size(); i++) {
messagepart = message.mid(i, 1);
- if (i+1 < message.size()) {
+ if (i + 1 < message.size()) {
for (ctcpquote = _ctcpMDequoteHash.begin(); ctcpquote != _ctcpMDequoteHash.end(); ++ctcpquote) {
if (message.mid(i, 2) == ctcpquote.key()) {
messagepart = ctcpquote.value();
return dequotedMessage;
}
-
-QByteArray CtcpParser::xdelimQuote(const QByteArray &message)
+QByteArray CtcpParser::xdelimQuote(const QByteArray& message)
{
QByteArray quotedMessage = message;
QHash<QByteArray, QByteArray>::const_iterator quoteIter = _ctcpXDelimDequoteHash.constBegin();
return quotedMessage;
}
-
-QByteArray CtcpParser::xdelimDequote(const QByteArray &message)
+QByteArray CtcpParser::xdelimDequote(const QByteArray& message)
{
QByteArray dequotedMessage;
QByteArray messagepart;
for (int i = 0; i < message.size(); i++) {
messagepart = message.mid(i, 1);
- if (i+1 < message.size()) {
+ if (i + 1 < message.size()) {
for (xdelimquote = _ctcpXDelimDequoteHash.begin(); xdelimquote != _ctcpXDelimDequoteHash.end(); ++xdelimquote) {
if (message.mid(i, 2) == xdelimquote.key()) {
messagepart = xdelimquote.value();
return dequotedMessage;
}
-
-void CtcpParser::processIrcEventRawNotice(IrcEventRawMessage *event)
+void CtcpParser::processIrcEventRawNotice(IrcEventRawMessage* event)
{
parse(event, Message::Notice);
}
-
-void CtcpParser::processIrcEventRawPrivmsg(IrcEventRawMessage *event)
+void CtcpParser::processIrcEventRawPrivmsg(IrcEventRawMessage* event)
{
parse(event, Message::Plain);
}
-
-void CtcpParser::parse(IrcEventRawMessage *e, Message::Type messagetype)
+void CtcpParser::parse(IrcEventRawMessage* e, Message::Type messagetype)
{
- //lowlevel message dequote
+ // lowlevel message dequote
QByteArray dequotedMessage = lowLevelDequote(e->rawMessage());
- CtcpEvent::CtcpType ctcptype = e->type() == EventManager::IrcEventRawNotice
- ? CtcpEvent::Reply
- : CtcpEvent::Query;
+ CtcpEvent::CtcpType ctcptype = e->type() == EventManager::IrcEventRawNotice ? CtcpEvent::Reply : CtcpEvent::Query;
- Message::Flags flags = (ctcptype == CtcpEvent::Reply && !e->network()->isChannelName(e->target()))
- ? Message::Redirected
- : Message::None;
+ Message::Flags flags = (ctcptype == CtcpEvent::Reply && !e->network()->isChannelName(e->target())) ? Message::Redirected : Message::None;
bool isStatusMsg = false;
parseSimple(e, messagetype, dequotedMessage, ctcptype, flags);
}
-
// only accept CTCPs in their simplest form, i.e. one ctcp, from start to
// end, no text around it; not as per the 'specs', but makes people happier
-void CtcpParser::parseSimple(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags)
+void CtcpParser::parseSimple(
+ IrcEventRawMessage* e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags)
{
- if (dequotedMessage.count(XDELIM) != 2 || dequotedMessage[0] != '\001' || dequotedMessage[dequotedMessage.count() -1] != '\001') {
+ if (dequotedMessage.count(XDELIM) != 2 || dequotedMessage[0] != '\001' || dequotedMessage[dequotedMessage.count() - 1] != '\001') {
displayMsg(e, messagetype, targetDecode(e, dequotedMessage), e->prefix(), e->target(), flags);
- } else {
+ }
+ else {
int spacePos;
QString ctcpcmd, ctcpparam;
if (spacePos != -1) {
ctcpcmd = targetDecode(e, ctcp.left(spacePos));
ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1));
- } else {
+ }
+ else {
ctcpcmd = targetDecode(e, ctcp);
ctcpparam = QString();
}
ctcpcmd = ctcpcmd.toUpper();
// we don't want to block /me messages by the CTCP ignore list
- if (ctcpcmd == QLatin1String("ACTION") || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) {
+ if (ctcpcmd == QLatin1String("ACTION")
+ || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) {
QUuid uuid = QUuid::createUuid();
_replies.insert(uuid, CtcpReply(coreNetwork(e), nickFromMask(e->prefix())));
- CtcpEvent *event = new CtcpEvent(EventManager::CtcpEvent, e->network(), e->prefix(), e->target(),
- ctcptype, ctcpcmd, ctcpparam, e->timestamp(), uuid);
+ CtcpEvent* event = new CtcpEvent(EventManager::CtcpEvent,
+ e->network(),
+ e->prefix(),
+ e->target(),
+ ctcptype,
+ ctcpcmd,
+ ctcpparam,
+ e->timestamp(),
+ uuid);
emit newEvent(event);
- CtcpEvent *flushEvent = new CtcpEvent(EventManager::CtcpEventFlush, e->network(), e->prefix(), e->target(),
- ctcptype, "INVALID", QString(), e->timestamp(), uuid);
+ CtcpEvent* flushEvent = new CtcpEvent(EventManager::CtcpEventFlush,
+ e->network(),
+ e->prefix(),
+ e->target(),
+ ctcptype,
+ "INVALID",
+ QString(),
+ e->timestamp(),
+ uuid);
emit newEvent(flushEvent);
}
}
}
-
-void CtcpParser::parseStandard(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags)
+void CtcpParser::parseStandard(
+ IrcEventRawMessage* e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags)
{
QByteArray ctcp;
- QList<CtcpEvent *> ctcpEvents;
- QUuid uuid; // needed to group all replies together
+ QList<CtcpEvent*> ctcpEvents;
+ QUuid uuid; // needed to group all replies together
// extract tagged / extended data
int xdelimPos = -1;
ctcp = xdelimDequote(dequotedMessage.mid(xdelimPos + 1, xdelimEndPos - xdelimPos - 1));
dequotedMessage = dequotedMessage.mid(xdelimEndPos + 1);
- //dispatch the ctcp command
+ // dispatch the ctcp command
QString ctcpcmd = targetDecode(e, ctcp.left(spacePos));
QString ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1));
ctcpcmd = ctcpcmd.toUpper();
// we don't want to block /me messages by the CTCP ignore list
- if (ctcpcmd == QLatin1String("ACTION") || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) {
+ if (ctcpcmd == QLatin1String("ACTION")
+ || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) {
if (uuid.isNull())
uuid = QUuid::createUuid();
- CtcpEvent *event = new CtcpEvent(EventManager::CtcpEvent, e->network(), e->prefix(), e->target(),
- ctcptype, ctcpcmd, ctcpparam, e->timestamp(), uuid);
+ CtcpEvent* event = new CtcpEvent(EventManager::CtcpEvent,
+ e->network(),
+ e->prefix(),
+ e->target(),
+ ctcptype,
+ ctcpcmd,
+ ctcpparam,
+ e->timestamp(),
+ uuid);
ctcpEvents << event;
}
}
if (!ctcpEvents.isEmpty()) {
_replies.insert(uuid, CtcpReply(coreNetwork(e), nickFromMask(e->prefix())));
- CtcpEvent *flushEvent = new CtcpEvent(EventManager::CtcpEventFlush, e->network(), e->prefix(), e->target(),
- ctcptype, "INVALID", QString(), e->timestamp(), uuid);
+ CtcpEvent* flushEvent = new CtcpEvent(EventManager::CtcpEventFlush,
+ e->network(),
+ e->prefix(),
+ e->target(),
+ ctcptype,
+ "INVALID",
+ QString(),
+ e->timestamp(),
+ uuid);
ctcpEvents << flushEvent;
- foreach(CtcpEvent *event, ctcpEvents) {
+ foreach (CtcpEvent* event, ctcpEvents) {
emit newEvent(event);
}
}
displayMsg(e, messagetype, targetDecode(e, dequotedMessage), e->prefix(), e->target(), flags);
}
-
-void CtcpParser::sendCtcpEvent(CtcpEvent *e)
+void CtcpParser::sendCtcpEvent(CtcpEvent* e)
{
- CoreNetwork *net = coreNetwork(e);
+ CoreNetwork* net = coreNetwork(e);
if (e->type() == EventManager::CtcpEvent) {
QByteArray quotedReply;
QString bufname = nickFromMask(e->prefix());
if (e->ctcpType() == CtcpEvent::Query && !e->reply().isNull()) {
if (_replies.contains(e->uuid()))
- _replies[e->uuid()].replies << lowLevelQuote(pack(net->serverEncode(e->ctcpCmd()),
- net->userEncode(bufname, e->reply())));
+ _replies[e->uuid()].replies << lowLevelQuote(pack(net->serverEncode(e->ctcpCmd()), net->userEncode(bufname, e->reply())));
else
// reply not caused by a request processed in here, so send it off immediately
reply(net, bufname, e->ctcpCmd(), e->reply());
}
}
-
-QByteArray CtcpParser::pack(const QByteArray &ctcpTag, const QByteArray &message)
+QByteArray CtcpParser::pack(const QByteArray& ctcpTag, const QByteArray& message)
{
if (message.isEmpty())
return XDELIM + ctcpTag + XDELIM;
return XDELIM + ctcpTag + ' ' + xdelimQuote(message) + XDELIM;
}
-
-void CtcpParser::query(CoreNetwork *net, const QString &bufname, const QString &ctcpTag, const QString &message)
+void CtcpParser::query(CoreNetwork* net, const QString& bufname, const QString& ctcpTag, const QString& message)
{
QString cmd("PRIVMSG");
- std::function<QList<QByteArray>(QString &)> cmdGenerator = [&] (QString &splitMsg) -> QList<QByteArray> {
- return QList<QByteArray>() << net->serverEncode(bufname) << lowLevelQuote(pack(net->serverEncode(ctcpTag), net->userEncode(bufname, splitMsg)));
+ std::function<QList<QByteArray>(QString&)> cmdGenerator = [&](QString& splitMsg) -> QList<QByteArray> {
+ return QList<QByteArray>() << net->serverEncode(bufname)
+ << lowLevelQuote(pack(net->serverEncode(ctcpTag), net->userEncode(bufname, splitMsg)));
};
net->putCmd(cmd, net->splitMessage(cmd, message, cmdGenerator));
}
-
-void CtcpParser::reply(CoreNetwork *net, const QString &bufname, const QString &ctcpTag, const QString &message)
+void CtcpParser::reply(CoreNetwork* net, const QString& bufname, const QString& ctcpTag, const QString& message)
{
QList<QByteArray> params;
params << net->serverEncode(bufname) << lowLevelQuote(pack(net->serverEncode(ctcpTag), net->userEncode(bufname, message)));
net->putCmd("NOTICE", params);
}
-
-void CtcpParser::packedReply(CoreNetwork *net, const QString &bufname, const QList<QByteArray> &replies)
+void CtcpParser::packedReply(CoreNetwork* net, const QString& bufname, const QList<QByteArray>& replies)
{
QList<QByteArray> params;
#ifndef CTCPPARSER_H
#define CTCPPARSER_H
-#include <QUuid>
#include <utility>
+#include <QUuid>
+
#include "corenetwork.h"
+#include "ctcpevent.h"
#include "eventmanager.h"
#include "ircevent.h"
-#include "ctcpevent.h"
class CoreSession;
class CtcpEvent;
Q_OBJECT
public:
- CtcpParser(CoreSession *coreSession, QObject *parent = nullptr);
+ CtcpParser(CoreSession* coreSession, QObject* parent = nullptr);
- inline CoreSession *coreSession() const { return _coreSession; }
+ inline CoreSession* coreSession() const { return _coreSession; }
- void query(CoreNetwork *network, const QString &bufname, const QString &ctcpTag, const QString &message);
- void reply(CoreNetwork *network, const QString &bufname, const QString &ctcpTag, const QString &message);
+ void query(CoreNetwork* network, const QString& bufname, const QString& ctcpTag, const QString& message);
+ void reply(CoreNetwork* network, const QString& bufname, const QString& ctcpTag, const QString& message);
- Q_INVOKABLE void processIrcEventRawNotice(IrcEventRawMessage *event);
- Q_INVOKABLE void processIrcEventRawPrivmsg(IrcEventRawMessage *event);
+ Q_INVOKABLE void processIrcEventRawNotice(IrcEventRawMessage* event);
+ Q_INVOKABLE void processIrcEventRawPrivmsg(IrcEventRawMessage* event);
- Q_INVOKABLE void sendCtcpEvent(CtcpEvent *event);
+ Q_INVOKABLE void sendCtcpEvent(CtcpEvent* event);
signals:
- void newEvent(Event *event);
+ void newEvent(Event* event);
protected:
- inline CoreNetwork *coreNetwork(NetworkEvent *e) const { return qobject_cast<CoreNetwork *>(e->network()); }
+ inline CoreNetwork* coreNetwork(NetworkEvent* e) const { return qobject_cast<CoreNetwork*>(e->network()); }
// FIXME duplicates functionality in EventStringifier, maybe want to put that in something common
//! Creates and sends a MessageEvent
- void displayMsg(NetworkEvent *event,
- Message::Type msgType,
- const QString &msg,
- const QString &sender = QString(),
- const QString &target = QString(),
- Message::Flags msgFlags = Message::None);
-
- void parse(IrcEventRawMessage *event, Message::Type msgType);
- void parseSimple(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags);
- void parseStandard(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags);
-
- QByteArray lowLevelQuote(const QByteArray &);
- QByteArray lowLevelDequote(const QByteArray &);
- QByteArray xdelimQuote(const QByteArray &);
- QByteArray xdelimDequote(const QByteArray &);
-
- QByteArray pack(const QByteArray &ctcpTag, const QByteArray &message);
- void packedReply(CoreNetwork *network, const QString &bufname, const QList<QByteArray> &replies);
+ void displayMsg(NetworkEvent* event,
+ Message::Type msgType,
+ const QString& msg,
+ const QString& sender = QString(),
+ const QString& target = QString(),
+ Message::Flags msgFlags = Message::None);
+
+ void parse(IrcEventRawMessage* event, Message::Type msgType);
+ void parseSimple(
+ IrcEventRawMessage* e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags);
+ void parseStandard(
+ IrcEventRawMessage* e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags);
+
+ QByteArray lowLevelQuote(const QByteArray&);
+ QByteArray lowLevelDequote(const QByteArray&);
+ QByteArray xdelimQuote(const QByteArray&);
+ QByteArray xdelimDequote(const QByteArray&);
+
+ QByteArray pack(const QByteArray& ctcpTag, const QByteArray& message);
+ void packedReply(CoreNetwork* network, const QString& bufname, const QList<QByteArray>& replies);
private slots:
void setStandardCtcp(bool enabled);
private:
- inline QString targetDecode(IrcEventRawMessage *e, const QByteArray &msg) { return coreNetwork(e)->userDecode(e->target(), msg); }
+ inline QString targetDecode(IrcEventRawMessage* e, const QByteArray& msg) { return coreNetwork(e)->userDecode(e->target(), msg); }
- CoreSession *_coreSession;
+ CoreSession* _coreSession;
- struct CtcpReply {
- CoreNetwork *network{nullptr};
+ struct CtcpReply
+ {
+ CoreNetwork* network{nullptr};
QString bufferName;
QList<QByteArray> replies;
CtcpReply() = default;
- CtcpReply(CoreNetwork *net, QString buf) : network(net), bufferName(std::move(buf)) {}
+ CtcpReply(CoreNetwork* net, QString buf)
+ : network(net)
+ , bufferName(std::move(buf))
+ {}
};
QHash<QUuid, CtcpReply> _replies;
QHash<QByteArray, QByteArray> _ctcpXDelimDequoteHash;
};
-
#endif
#include "ctcpevent.h"
#include "messageevent.h"
-EventStringifier::EventStringifier(CoreSession *parent) : BasicHandler("handleCtcp", parent),
- _coreSession(parent),
- _whois(false)
+EventStringifier::EventStringifier(CoreSession* parent)
+ : BasicHandler("handleCtcp", parent)
+ , _coreSession(parent)
+ , _whois(false)
{
connect(this, &EventStringifier::newMessageEvent, coreSession()->eventManager(), &EventManager::postEvent);
}
-
-void EventStringifier::displayMsg(NetworkEvent *event, Message::Type msgType, const QString &msg, const QString &sender,
- const QString &target, Message::Flags msgFlags)
+void EventStringifier::displayMsg(
+ NetworkEvent* event, Message::Type msgType, const QString& msg, const QString& sender, const QString& target, Message::Flags msgFlags)
{
if (event->flags().testFlag(EventManager::Silent))
return;
- MessageEvent *msgEvent = createMessageEvent(event, msgType, msg, sender, target, msgFlags);
- //sendMessageEvent(msgEvent);
+ MessageEvent* msgEvent = createMessageEvent(event, msgType, msg, sender, target, msgFlags);
+ // sendMessageEvent(msgEvent);
emit newMessageEvent(msgEvent);
}
-
-MessageEvent *EventStringifier::createMessageEvent(NetworkEvent *event, Message::Type msgType, const QString &msg, const QString &sender,
- const QString &target, Message::Flags msgFlags)
+MessageEvent* EventStringifier::createMessageEvent(
+ NetworkEvent* event, Message::Type msgType, const QString& msg, const QString& sender, const QString& target, Message::Flags msgFlags)
{
- MessageEvent *msgEvent = new MessageEvent(msgType, event->network(), msg, sender, target, msgFlags);
+ MessageEvent* msgEvent = new MessageEvent(msgType, event->network(), msg, sender, target, msgFlags);
msgEvent->setTimestamp(event->timestamp());
return msgEvent;
}
-
-bool EventStringifier::checkParamCount(IrcEvent *e, int minParams)
+bool EventStringifier::checkParamCount(IrcEvent* e, int minParams)
{
if (e->params().count() < minParams) {
if (e->type() == EventManager::IrcEventNumeric) {
- qWarning() << "Command " << static_cast<IrcEventNumeric *>(e)->number() << " requires " << minParams << "params, got: " << e->params();
+ qWarning() << "Command " << static_cast<IrcEventNumeric*>(e)->number() << " requires " << minParams
+ << "params, got: " << e->params();
}
else {
QString name = coreSession()->eventManager()->enumName(e->type());
return true;
}
-
/* These are only for legacy reasons; remove as soon as we handle NetworkSplitEvents properly */
-void EventStringifier::processNetworkSplitJoin(NetworkSplitEvent *e)
+void EventStringifier::processNetworkSplitJoin(NetworkSplitEvent* e)
{
QString msg = e->users().join("#:#") + "#:#" + e->quitMessage();
displayMsg(e, Message::NetsplitJoin, msg, QString(), e->channel());
}
-
-void EventStringifier::processNetworkSplitQuit(NetworkSplitEvent *e)
+void EventStringifier::processNetworkSplitQuit(NetworkSplitEvent* e)
{
QString msg = e->users().join("#:#") + "#:#" + e->quitMessage();
displayMsg(e, Message::NetsplitQuit, msg, QString(), e->channel());
}
-
/* End legacy */
-void EventStringifier::processIrcEventNumeric(IrcEventNumeric *e)
+void EventStringifier::processIrcEventNumeric(IrcEventNumeric* e)
{
- //qDebug() << e->number();
+ // qDebug() << e->number();
switch (e->number()) {
// Welcome, status, info messages. Just display these.
case 1:
case 491:
case 501:
case 502:
- case 431: // ERR_NONICKNAMEGIVEN
+ case 431: // ERR_NONICKNAMEGIVEN
displayMsg(e, Message::Error, e->params().join(" "), e->prefix());
break;
// Server error messages, display them in red. Colon between first param and rest.
- case 401:
- {
+ case 401: {
if (!checkParamCount(e, 1))
return;
case 408:
case 415:
case 421:
- case 442:
- {
+ case 442: {
if (!checkParamCount(e, 1))
return;
case 423:
case 441:
case 444:
- case 461: // FIXME see below for the 47x codes
+ case 461: // FIXME see below for the 47x codes
case 467:
case 471:
case 473:
case 477:
case 478:
case 482:
- case 436: // ERR_NICKCOLLISION
+ case 436: // ERR_NICKCOLLISION
{
if (!checkParamCount(e, 1))
return;
}
else {
// FIXME figure out how/where to do this in the future
- //if(coreSession()->ircListHelper()->requestInProgress(network()->networkId()))
+ // if(coreSession()->ircListHelper()->requestInProgress(network()->networkId()))
// coreSession()->ircListHelper()->reportError(params.join(" "));
- //else
+ // else
displayMsg(e, Message::Error, QString("%1 %2").arg(e->number(), 3, 10, QLatin1Char('0')).arg(e->params().join(" ")), e->prefix());
}
}
}
-
-void EventStringifier::processIrcEventInvite(IrcEvent *e)
+void EventStringifier::processIrcEventInvite(IrcEvent* e)
{
displayMsg(e, Message::Invite, tr("%1 invited you to channel %2").arg(e->nick(), e->params().at(1)));
}
-
-void EventStringifier::processIrcEventJoin(IrcEvent *e)
+void EventStringifier::processIrcEventJoin(IrcEvent* e)
{
if (e->testFlag(EventManager::Netsplit))
return;
displayMsg(e, Message::Join, e->params()[0], e->prefix(), e->params()[0], msgFlags);
}
-
-void EventStringifier::processIrcEventKick(IrcEvent *e)
+void EventStringifier::processIrcEventKick(IrcEvent* e)
{
if (!checkParamCount(e, 2))
return;
- IrcUser *victim = e->network()->ircUser(e->params().at(1));
+ IrcUser* victim = e->network()->ircUser(e->params().at(1));
if (victim) {
QString channel = e->params().at(0);
QString msg = victim->nick();
}
}
-
-void EventStringifier::processIrcEventMode(IrcEvent *e)
+void EventStringifier::processIrcEventMode(IrcEvent* e)
{
if (e->network()->isChannelName(e->params().first())) {
// Channel Modes
}
}
-
// this needs to be called before the ircuser is renamed!
-void EventStringifier::processIrcEventNick(IrcEvent *e)
+void EventStringifier::processIrcEventNick(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
- IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
+ IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
if (!ircuser) {
qWarning() << Q_FUNC_INFO << "Unknown IrcUser!";
return;
// Treat the sender as the new nickname, mark the message as Self
sender = newnick;
msgFlags = Message::Self;
- } else {
+ }
+ else {
// Take the sender from the event prefix, don't mark the message
sender = e->prefix();
}
// Announce to all channels the IrcUser is in
- foreach(const QString &channel, ircuser->channels()) {
+ foreach (const QString& channel, ircuser->channels()) {
displayMsg(e, Message::Nick, newnick, sender, channel, msgFlags);
}
}
-
-void EventStringifier::processIrcEventPart(IrcEvent *e)
+void EventStringifier::processIrcEventPart(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
QString channel = e->params().at(0);
QString msg = e->params().count() > 1 ? e->params().at(1) : QString();
-
Message::Flag msgFlags = Message::Flag::None;
if (e->testFlag(EventManager::Self)) {
// Mark the message as Self
displayMsg(e, Message::Part, msg, e->prefix(), channel, msgFlags);
}
-
-void EventStringifier::processIrcEventPong(IrcEvent *e)
+void EventStringifier::processIrcEventPong(IrcEvent* e)
{
// CoreSessionEventProcessor will flag automated PONG replies as EventManager::Silent. There's
// no need to handle that specially here.
displayMsg(e, Message::Server, "PONG " + e->params().join(" "), e->prefix());
}
-
-void EventStringifier::processIrcEventQuit(IrcEvent *e)
+void EventStringifier::processIrcEventQuit(IrcEvent* e)
{
if (e->testFlag(EventManager::Netsplit))
return;
- IrcUser *ircuser = e->network()->updateNickFromMask(e->prefix());
+ IrcUser* ircuser = e->network()->updateNickFromMask(e->prefix());
if (!ircuser)
return;
-
Message::Flag msgFlags = Message::Flag::None;
if (e->testFlag(EventManager::Self)) {
// Mark the message as Self
}
// Announce to all channels the IrcUser is in
- foreach(const QString &channel, ircuser->channels()) {
- displayMsg(e, Message::Quit, e->params().count() ? e->params().first() : QString(),
- e->prefix(), channel, msgFlags);
+ foreach (const QString& channel, ircuser->channels()) {
+ displayMsg(e, Message::Quit, e->params().count() ? e->params().first() : QString(), e->prefix(), channel, msgFlags);
}
}
-
-void EventStringifier::processIrcEventTopic(IrcEvent *e)
+void EventStringifier::processIrcEventTopic(IrcEvent* e)
{
Message::Flag msgFlags = Message::Flag::None;
if (e->testFlag(EventManager::Self)) {
msgFlags = Message::Self;
}
- displayMsg(e, Message::Topic, tr("%1 has changed topic for %2 to: \"%3\"")
- .arg(e->nick(), e->params().at(0), e->params().at(1)), QString(), e->params().at(0),
+ displayMsg(e,
+ Message::Topic,
+ tr("%1 has changed topic for %2 to: \"%3\"").arg(e->nick(), e->params().at(0), e->params().at(1)),
+ QString(),
+ e->params().at(0),
msgFlags);
}
-void EventStringifier::processIrcEventError(IrcEvent *e)
+void EventStringifier::processIrcEventError(IrcEvent* e)
{
// Need an error reason
if (!checkParamCount(e, 1))
displayMsg(e, Message::Server, tr("Error from server: ") + e->params().join(""));
}
-void EventStringifier::processIrcEventWallops(IrcEvent *e)
+void EventStringifier::processIrcEventWallops(IrcEvent* e)
{
displayMsg(e, Message::Server, tr("[Operwall] %1: %2").arg(e->nick(), e->params().join(" ")));
}
-
/* RPL_ISUPPORT */
-void EventStringifier::processIrcEvent005(IrcEvent *e)
+void EventStringifier::processIrcEvent005(IrcEvent* e)
{
if (!e->params().last().contains(QRegExp("are supported (by|on) this server")))
displayMsg(e, Message::Error, tr("Received non-RFC-compliant RPL_ISUPPORT: this can lead to unexpected behavior!"), e->prefix());
displayMsg(e, Message::Server, e->params().join(" "), e->prefix());
}
-
/* RPL_AWAY - "<nick> :<away message>" */
-void EventStringifier::processIrcEvent301(IrcEvent *e)
+void EventStringifier::processIrcEvent301(IrcEvent* e)
{
QString nick = e->params().at(0);
QString awayMsg = e->params().at(1);
}
else {
target = nick;
- IrcUser *ircuser = e->network()->ircUser(nick);
+ IrcUser* ircuser = e->network()->ircUser(nick);
if (ircuser) {
QDateTime now = QDateTime::currentDateTime();
now.setTimeSpec(Qt::UTC);
// 1 hour = 60 min * 60 sec
const int silenceTime = 60 * 60;
// Check if away state has NOT changed and silence time hasn't yet elapsed
- if (!ircuser->hasAwayChanged()
- && ircuser->lastAwayMessageTime().addSecs(silenceTime) >= now) {
+ if (!ircuser->hasAwayChanged() && ircuser->lastAwayMessageTime().addSecs(silenceTime) >= now) {
// Away message hasn't changed and we're still within the period of silence; don't
// repeat the message
send = false;
displayMsg(e, Message::Server, msg + tr("%1 is away: \"%2\"").arg(nick, awayMsg), QString(), target);
}
-
/* RPL_UNAWAY - ":You are no longer marked as being away" */
-void EventStringifier::processIrcEvent305(IrcEvent *e)
+void EventStringifier::processIrcEvent305(IrcEvent* e)
{
displayMsg(e, Message::Server, tr("You are no longer marked as being away"));
}
-
/* RPL_NOWAWAY - ":You have been marked as being away" */
-void EventStringifier::processIrcEvent306(IrcEvent *e)
+void EventStringifier::processIrcEvent306(IrcEvent* e)
{
if (!e->network()->autoAwayActive())
displayMsg(e, Message::Server, tr("You have been marked as being away"));
}
-
/*
WHOIS-Message:
Replies 311 - 313, 317 - 319 are all replies generated in response to a WHOIS message.
*/
/* RPL_WHOISUSER - "<nick> <user> <host> * :<real name>" */
-void EventStringifier::processIrcEvent311(IrcEvent *e)
+void EventStringifier::processIrcEvent311(IrcEvent* e)
{
_whois = true;
const QString whoisUserString = tr("[Whois] %1 is %2 (%3)");
- IrcUser *ircuser = e->network()->ircUser(e->params().at(0));
+ IrcUser* ircuser = e->network()->ircUser(e->params().at(0));
if (ircuser)
displayMsg(e, Message::Server, whoisUserString.arg(ircuser->nick(), ircuser->hostmask(), ircuser->realName()));
else {
}
}
-
/* RPL_WHOISSERVER - "<nick> <server> :<server info>" */
-void EventStringifier::processIrcEvent312(IrcEvent *e)
+void EventStringifier::processIrcEvent312(IrcEvent* e)
{
if (_whois)
displayMsg(e, Message::Server, tr("[Whois] %1 is online via %2 (%3)").arg(e->params().at(0), e->params().at(1), e->params().last()));
displayMsg(e, Message::Server, tr("[Whowas] %1 was online via %2 (%3)").arg(e->params().at(0), e->params().at(1), e->params().last()));
}
-
/* RPL_WHOWASUSER - "<nick> <user> <host> * :<real name>" */
-void EventStringifier::processIrcEvent314(IrcEvent *e)
+void EventStringifier::processIrcEvent314(IrcEvent* e)
{
if (!checkParamCount(e, 3))
return;
displayMsg(e, Message::Server, tr("[Whowas] %1 was %2@%3 (%4)").arg(e->params()[0], e->params()[1], e->params()[2], e->params().last()));
}
-
/* RPL_ENDOFWHO: "<name> :End of WHO list" */
-void EventStringifier::processIrcEvent315(IrcEvent *e)
+void EventStringifier::processIrcEvent315(IrcEvent* e)
{
QStringList p = e->params();
- p.takeLast(); // should be "End of WHO list"
+ p.takeLast(); // should be "End of WHO list"
displayMsg(e, Message::Server, tr("[Who] End of /WHO list for %1").arg(p.join(" ")));
}
-
/* RPL_WHOISIDLE - "<nick> <integer> :seconds idle"
(real life: "<nick> <integer> <integer> :seconds idle, signon time) */
-void EventStringifier::processIrcEvent317(IrcEvent *e)
+void EventStringifier::processIrcEvent317(IrcEvent* e)
{
int idleSecs = e->params()[1].toInt();
- if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
- // Time in IRC protocol is defined as seconds. Convert from seconds instead.
- // See https://doc.qt.io/qt-5/qdatetime.html#fromSecsSinceEpoch
+ if (e->params().count() > 3) { // if we have more then 3 params we have the above mentioned "real life" situation
+ // Time in IRC protocol is defined as seconds. Convert from seconds instead.
+ // See https://doc.qt.io/qt-5/qdatetime.html#fromSecsSinceEpoch
#if QT_VERSION >= 0x050800
QDateTime loginTime = QDateTime::fromSecsSinceEpoch(e->params()[2].toLongLong()).toUTC();
#else
// fromSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for now.
// See https://doc.qt.io/qt-5/qdatetime.html#fromMSecsSinceEpoch
- QDateTime loginTime = QDateTime::fromMSecsSinceEpoch(
- (qint64)(e->params()[2].toLongLong() * 1000)).toUTC();
+ QDateTime loginTime = QDateTime::fromMSecsSinceEpoch((qint64)(e->params()[2].toLongLong() * 1000)).toUTC();
#endif
- displayMsg(e, Message::Server, tr("[Whois] %1 is logged in since %2")
- .arg(e->params()[0], loginTime.toString("yyyy-MM-dd hh:mm:ss UTC")));
+ displayMsg(e,
+ Message::Server,
+ tr("[Whois] %1 is logged in since %2").arg(e->params()[0], loginTime.toString("yyyy-MM-dd hh:mm:ss UTC")));
}
QDateTime idlingSince = e->timestamp().toLocalTime().addSecs(-idleSecs).toUTC();
- displayMsg(e, Message::Server, tr("[Whois] %1 is idling for %2 (since %3)")
- .arg(e->params()[0], secondsToString(idleSecs),
- idlingSince.toString("yyyy-MM-dd hh:mm:ss UTC")));
+ displayMsg(e,
+ Message::Server,
+ tr("[Whois] %1 is idling for %2 (since %3)")
+ .arg(e->params()[0], secondsToString(idleSecs), idlingSince.toString("yyyy-MM-dd hh:mm:ss UTC")));
}
-
/* RPL_ENDOFWHOIS - "<nick> :End of WHOIS list" */
-void EventStringifier::processIrcEvent318(IrcEvent *e)
+void EventStringifier::processIrcEvent318(IrcEvent* e)
{
_whois = false;
displayMsg(e, Message::Server, tr("[Whois] End of /WHOIS list"));
}
-
/* RPL_WHOISCHANNELS - "<nick> :*( ( "@" / "+" ) <channel> " " )" */
-void EventStringifier::processIrcEvent319(IrcEvent *e)
+void EventStringifier::processIrcEvent319(IrcEvent* e)
{
if (!checkParamCount(e, 2))
return;
QStringList op;
QStringList voice;
QStringList user;
- foreach(QString channel, e->params().last().split(" ")) {
+ foreach (QString channel, e->params().last().split(" ")) {
if (channel.startsWith("@"))
op.append(channel.remove(0, 1));
else if (channel.startsWith("+"))
displayMsg(e, Message::Server, tr("[Whois] %1 is an operator on channels: %2").arg(nick, op.join(" ")));
}
-
/* RPL_LIST - "<channel> <# visible> :<topic>" */
-void EventStringifier::processIrcEvent322(IrcEvent *e)
+void EventStringifier::processIrcEvent322(IrcEvent* e)
{
QString channelName;
quint32 userCount = 0;
default:
break;
}
- displayMsg(e, Message::Server, tr("Channel %1 has %2 users. Topic is: \"%3\"")
- .arg(channelName).arg(userCount).arg(topic));
+ displayMsg(e, Message::Server, tr("Channel %1 has %2 users. Topic is: \"%3\"").arg(channelName).arg(userCount).arg(topic));
}
-
/* RPL_LISTEND ":End of LIST" */
-void EventStringifier::processIrcEvent323(IrcEvent *e)
+void EventStringifier::processIrcEvent323(IrcEvent* e)
{
displayMsg(e, Message::Server, tr("End of channel list"));
}
-
/* RPL_CHANNELMODEIS - "<channel> <mode> <mode params>" */
-void EventStringifier::processIrcEvent324(IrcEvent *e)
+void EventStringifier::processIrcEvent324(IrcEvent* e)
{
processIrcEventMode(e);
}
-
/* RPL_??? - "<channel> <homepage> */
-void EventStringifier::processIrcEvent328(IrcEvent *e)
+void EventStringifier::processIrcEvent328(IrcEvent* e)
{
if (!checkParamCount(e, 2))
return;
displayMsg(e, Message::Topic, tr("Homepage for %1 is %2").arg(channel, e->params()[1]), QString(), channel);
}
-
/* RPL_??? - "<channel> <creation time (unix)>" */
-void EventStringifier::processIrcEvent329(IrcEvent *e)
+void EventStringifier::processIrcEvent329(IrcEvent* e)
{
if (!checkParamCount(e, 2))
return;
// See https://doc.qt.io/qt-5/qdatetime.html#fromMSecsSinceEpoch
QDateTime time = QDateTime::fromMSecsSinceEpoch((qint64)(unixtime * 1000)).toUTC();
#endif
- displayMsg(e, Message::Topic, tr("Channel %1 created on %2")
- .arg(channel, time.toString("yyyy-MM-dd hh:mm:ss UTC")),
- QString(), channel);
+ displayMsg(e, Message::Topic, tr("Channel %1 created on %2").arg(channel, time.toString("yyyy-MM-dd hh:mm:ss UTC")), QString(), channel);
}
-
/* RPL_WHOISACCOUNT: "<nick> <account> :is authed as */
-void EventStringifier::processIrcEvent330(IrcEvent *e)
+void EventStringifier::processIrcEvent330(IrcEvent* e)
{
if (e->params().count() < 3)
return;
}
}
-
/* RPL_NOTOPIC */
-void EventStringifier::processIrcEvent331(IrcEvent *e)
+void EventStringifier::processIrcEvent331(IrcEvent* e)
{
QString channel = e->params().first();
displayMsg(e, Message::Topic, tr("No topic is set for %1.").arg(channel), QString(), channel);
}
-
/* RPL_TOPIC */
-void EventStringifier::processIrcEvent332(IrcEvent *e)
+void EventStringifier::processIrcEvent332(IrcEvent* e)
{
QString channel = e->params().first();
displayMsg(e, Message::Topic, tr("Topic for %1 is \"%2\"").arg(channel, e->params()[1]), QString(), channel);
}
-
/* Topic set by... */
-void EventStringifier::processIrcEvent333(IrcEvent *e)
+void EventStringifier::processIrcEvent333(IrcEvent* e)
{
if (!checkParamCount(e, 3))
return;
#else
// fromSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for now.
// See https://doc.qt.io/qt-5/qdatetime.html#fromMSecsSinceEpoch
- QDateTime topicSetTime = QDateTime::fromMSecsSinceEpoch(
- (qint64)(e->params()[2].toLongLong() * 1000)).toUTC();
+ QDateTime topicSetTime = QDateTime::fromMSecsSinceEpoch((qint64)(e->params()[2].toLongLong() * 1000)).toUTC();
#endif
- displayMsg(e, Message::Topic, tr("Topic set by %1 on %2")
- .arg(e->params()[1],
- topicSetTime.toString("yyyy-MM-dd hh:mm:ss UTC")), QString(), channel);
+ displayMsg(e,
+ Message::Topic,
+ tr("Topic set by %1 on %2").arg(e->params()[1], topicSetTime.toString("yyyy-MM-dd hh:mm:ss UTC")),
+ QString(),
+ channel);
}
-
/* RPL_INVITING - "<nick> <channel>*/
-void EventStringifier::processIrcEvent341(IrcEvent *e)
+void EventStringifier::processIrcEvent341(IrcEvent* e)
{
if (!checkParamCount(e, 2))
return;
displayMsg(e, Message::Server, tr("%1 has been invited to %2").arg(e->params().first(), channel), QString(), channel);
}
-
/* RPL_WHOREPLY: "<channel> <user> <host> <server> <nick>
( "H" / "G" > ["*"] [ ( "@" / "+" ) ] :<hopcount> <real name>" */
-void EventStringifier::processIrcEvent352(IrcEvent *e)
+void EventStringifier::processIrcEvent352(IrcEvent* e)
{
displayMsg(e, Message::Server, tr("[Who] %1").arg(e->params().join(" ")));
}
-
/* RPL_WHOSPCRPL: "<yournick> <num> #<channel> ~<ident> <host> <servname> <nick>
("H"/ "G") <account> :<realname>"
Could be anything else, though. User-specified fields.
See http://faerion.sourceforge.net/doc/irc/whox.var */
-void EventStringifier::processIrcEvent354(IrcEvent *e)
+void EventStringifier::processIrcEvent354(IrcEvent* e)
{
displayMsg(e, Message::Server, tr("[WhoX] %1").arg(e->params().join(" ")));
}
-
/* RPL_ENDOFWHOWAS - "<nick> :End of WHOWAS" */
-void EventStringifier::processIrcEvent369(IrcEvent *e)
+void EventStringifier::processIrcEvent369(IrcEvent* e)
{
displayMsg(e, Message::Server, tr("End of /WHOWAS"));
}
-
/* ERR_ERRONEUSNICKNAME */
-void EventStringifier::processIrcEvent432(IrcEvent *e)
+void EventStringifier::processIrcEvent432(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
displayMsg(e, Message::Error, tr("Nick %1 contains illegal characters").arg(e->params()[0]));
}
-
/* ERR_NICKNAMEINUSE */
-void EventStringifier::processIrcEvent433(IrcEvent *e)
+void EventStringifier::processIrcEvent433(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
displayMsg(e, Message::Error, tr("Nick already in use: %1").arg(e->params()[0]));
}
-
/* ERR_UNAVAILRESOURCE */
-void EventStringifier::processIrcEvent437(IrcEvent *e)
+void EventStringifier::processIrcEvent437(IrcEvent* e)
{
if (!checkParamCount(e, 1))
return;
displayMsg(e, Message::Error, tr("Nick/channel is temporarily unavailable: %1").arg(e->params()[0]));
}
-
// template
/*
/******** CTCP HANDLING ********/
/*******************************/
-void EventStringifier::processCtcpEvent(CtcpEvent *e)
+void EventStringifier::processCtcpEvent(CtcpEvent* e)
{
if (e->type() != EventManager::CtcpEvent)
return;
if (e->testFlag(EventManager::Self)) {
- displayMsg(e, Message::Action,
+ displayMsg(e,
+ Message::Action,
tr("sending CTCP-%1 request to %2").arg(e->ctcpCmd(), e->target()),
- e->network()->myNick(), QString(), Message::Flag::Self);
+ e->network()->myNick(),
+ QString(),
+ Message::Flag::Self);
return;
}
- handle(e->ctcpCmd(), Q_ARG(CtcpEvent *, e));
+ handle(e->ctcpCmd(), Q_ARG(CtcpEvent*, e));
}
-
-void EventStringifier::defaultHandler(const QString &ctcpCmd, CtcpEvent *e)
+void EventStringifier::defaultHandler(const QString& ctcpCmd, CtcpEvent* e)
{
Q_UNUSED(ctcpCmd);
if (e->ctcpType() == CtcpEvent::Query) {
QString unknown;
- if (e->reply().isNull()) // all known core-side handlers (except for ACTION) set a reply!
+ if (e->reply().isNull()) // all known core-side handlers (except for ACTION) set a reply!
//: Optional "unknown" in "Received unknown CTCP-FOO request by bar"
unknown = tr("unknown") + ' ';
displayMsg(e, Message::Server, tr("Received %1CTCP-%2 request by %3").arg(unknown, e->ctcpCmd(), e->prefix()));
displayMsg(e, Message::Server, tr("Received CTCP-%1 answer from %2: %3").arg(e->ctcpCmd(), nickFromMask(e->prefix()), e->param()));
}
-
-void EventStringifier::handleCtcpAction(CtcpEvent *e)
+void EventStringifier::handleCtcpAction(CtcpEvent* e)
{
displayMsg(e, Message::Action, e->param(), e->prefix(), e->target());
}
-
-void EventStringifier::handleCtcpPing(CtcpEvent *e)
+void EventStringifier::handleCtcpPing(CtcpEvent* e)
{
if (e->ctcpType() == CtcpEvent::Query)
defaultHandler(e->ctcpCmd(), e);
else {
- displayMsg(e, Message::Server, tr("Received CTCP-PING answer from %1 with %2 milliseconds round trip time")
- .arg(nickFromMask(e->prefix())).arg(QDateTime::fromMSecsSinceEpoch(e->param().toULongLong()).msecsTo(e->timestamp())));
+ displayMsg(e,
+ Message::Server,
+ tr("Received CTCP-PING answer from %1 with %2 milliseconds round trip time")
+ .arg(nickFromMask(e->prefix()))
+ .arg(QDateTime::fromMSecsSinceEpoch(e->param().toULongLong()).msecsTo(e->timestamp())));
}
}
Q_OBJECT
public:
- explicit EventStringifier(CoreSession *parent);
+ explicit EventStringifier(CoreSession* parent);
- inline CoreSession *coreSession() const { return _coreSession; }
+ inline CoreSession* coreSession() const { return _coreSession; }
- MessageEvent *createMessageEvent(NetworkEvent *event,
- Message::Type msgType,
- const QString &msg,
- const QString &sender = QString(),
- const QString &target = QString(),
- Message::Flags msgFlags = Message::None);
+ MessageEvent* createMessageEvent(NetworkEvent* event,
+ Message::Type msgType,
+ const QString& msg,
+ const QString& sender = QString(),
+ const QString& target = QString(),
+ Message::Flags msgFlags = Message::None);
// legacy handlers
- Q_INVOKABLE void processNetworkSplitJoin(NetworkSplitEvent *event);
- Q_INVOKABLE void processNetworkSplitQuit(NetworkSplitEvent *event);
+ Q_INVOKABLE void processNetworkSplitJoin(NetworkSplitEvent* event);
+ Q_INVOKABLE void processNetworkSplitQuit(NetworkSplitEvent* event);
//! Handle generic numeric events
- Q_INVOKABLE void processIrcEventNumeric(IrcEventNumeric *event);
-
- Q_INVOKABLE void processIrcEventInvite(IrcEvent *event);
- Q_INVOKABLE void processIrcEventJoin(IrcEvent *event);
- Q_INVOKABLE void processIrcEventKick(IrcEvent *event);
- Q_INVOKABLE void processIrcEventMode(IrcEvent *event);
- Q_INVOKABLE void processIrcEventNick(IrcEvent *event);
- Q_INVOKABLE void processIrcEventPart(IrcEvent *event);
- Q_INVOKABLE void processIrcEventPong(IrcEvent *event);
- Q_INVOKABLE void processIrcEventQuit(IrcEvent *event);
- Q_INVOKABLE void processIrcEventTopic(IrcEvent *event);
- Q_INVOKABLE void processIrcEventError(IrcEvent *event); /// ERROR message from server
- Q_INVOKABLE void processIrcEventWallops(IrcEvent *event);
-
- Q_INVOKABLE void processIrcEvent005(IrcEvent *event); // RPL_ISUPPORT
- Q_INVOKABLE void processIrcEvent301(IrcEvent *event); // RPL_AWAY
- Q_INVOKABLE void processIrcEvent305(IrcEvent *event); // RPL_UNAWAY
- Q_INVOKABLE void processIrcEvent306(IrcEvent *event); // RPL_NOWAWAY
- Q_INVOKABLE void processIrcEvent311(IrcEvent *event); // RPL_WHOISUSER
- Q_INVOKABLE void processIrcEvent312(IrcEvent *event); // RPL_WHOISSERVER
- Q_INVOKABLE void processIrcEvent314(IrcEvent *event); // RPL_WHOWASUSER
- Q_INVOKABLE void processIrcEvent315(IrcEvent *event); // RPL_ENDOFWHO
- Q_INVOKABLE void processIrcEvent317(IrcEvent *event); // RPL_WHOISIDLE
- Q_INVOKABLE void processIrcEvent318(IrcEvent *event); // RPL_ENDOFWHOIS
- Q_INVOKABLE void processIrcEvent319(IrcEvent *event); // RPL_WHOISCHANNELS
- Q_INVOKABLE void processIrcEvent322(IrcEvent *event); // RPL_LIST
- Q_INVOKABLE void processIrcEvent323(IrcEvent *event); // RPL_LISTEND
- Q_INVOKABLE void processIrcEvent324(IrcEvent *event); // RPL_CHANNELMODEIS
- Q_INVOKABLE void processIrcEvent328(IrcEvent *event); // RPL_??? (channel creation time)
- Q_INVOKABLE void processIrcEvent329(IrcEvent *event); // RPL_??? (channel homepage)
- Q_INVOKABLE void processIrcEvent330(IrcEvent *event); // RPL_WHOISACCOUNT (quakenet/snircd/undernet)
- Q_INVOKABLE void processIrcEvent331(IrcEvent *event); // RPL_NOTOPIC
- Q_INVOKABLE void processIrcEvent332(IrcEvent *event); // RPL_TOPIC
- Q_INVOKABLE void processIrcEvent333(IrcEvent *event); // RPL_??? (topic set by)
- Q_INVOKABLE void processIrcEvent341(IrcEvent *event); // RPL_INVITING
- Q_INVOKABLE void processIrcEvent352(IrcEvent *event); // RPL_WHOREPLY
- Q_INVOKABLE void processIrcEvent354(IrcEvent *event); // RPL_WHOSPCRPL
- Q_INVOKABLE void processIrcEvent369(IrcEvent *event); // RPL_ENDOFWHOWAS
- Q_INVOKABLE void processIrcEvent432(IrcEvent *event); // ERR_ERRONEUSNICKNAME
- Q_INVOKABLE void processIrcEvent433(IrcEvent *event); // ERR_NICKNAMEINUSE
- Q_INVOKABLE void processIrcEvent437(IrcEvent *event); // ERR_UNAVAILRESOURCE
+ Q_INVOKABLE void processIrcEventNumeric(IrcEventNumeric* event);
+
+ Q_INVOKABLE void processIrcEventInvite(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventJoin(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventKick(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventMode(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventNick(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventPart(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventPong(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventQuit(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventTopic(IrcEvent* event);
+ Q_INVOKABLE void processIrcEventError(IrcEvent* event); /// ERROR message from server
+ Q_INVOKABLE void processIrcEventWallops(IrcEvent* event);
+
+ Q_INVOKABLE void processIrcEvent005(IrcEvent* event); // RPL_ISUPPORT
+ Q_INVOKABLE void processIrcEvent301(IrcEvent* event); // RPL_AWAY
+ Q_INVOKABLE void processIrcEvent305(IrcEvent* event); // RPL_UNAWAY
+ Q_INVOKABLE void processIrcEvent306(IrcEvent* event); // RPL_NOWAWAY
+ Q_INVOKABLE void processIrcEvent311(IrcEvent* event); // RPL_WHOISUSER
+ Q_INVOKABLE void processIrcEvent312(IrcEvent* event); // RPL_WHOISSERVER
+ Q_INVOKABLE void processIrcEvent314(IrcEvent* event); // RPL_WHOWASUSER
+ Q_INVOKABLE void processIrcEvent315(IrcEvent* event); // RPL_ENDOFWHO
+ Q_INVOKABLE void processIrcEvent317(IrcEvent* event); // RPL_WHOISIDLE
+ Q_INVOKABLE void processIrcEvent318(IrcEvent* event); // RPL_ENDOFWHOIS
+ Q_INVOKABLE void processIrcEvent319(IrcEvent* event); // RPL_WHOISCHANNELS
+ Q_INVOKABLE void processIrcEvent322(IrcEvent* event); // RPL_LIST
+ Q_INVOKABLE void processIrcEvent323(IrcEvent* event); // RPL_LISTEND
+ Q_INVOKABLE void processIrcEvent324(IrcEvent* event); // RPL_CHANNELMODEIS
+ Q_INVOKABLE void processIrcEvent328(IrcEvent* event); // RPL_??? (channel creation time)
+ Q_INVOKABLE void processIrcEvent329(IrcEvent* event); // RPL_??? (channel homepage)
+ Q_INVOKABLE void processIrcEvent330(IrcEvent* event); // RPL_WHOISACCOUNT (quakenet/snircd/undernet)
+ Q_INVOKABLE void processIrcEvent331(IrcEvent* event); // RPL_NOTOPIC
+ Q_INVOKABLE void processIrcEvent332(IrcEvent* event); // RPL_TOPIC
+ Q_INVOKABLE void processIrcEvent333(IrcEvent* event); // RPL_??? (topic set by)
+ Q_INVOKABLE void processIrcEvent341(IrcEvent* event); // RPL_INVITING
+ Q_INVOKABLE void processIrcEvent352(IrcEvent* event); // RPL_WHOREPLY
+ Q_INVOKABLE void processIrcEvent354(IrcEvent* event); // RPL_WHOSPCRPL
+ Q_INVOKABLE void processIrcEvent369(IrcEvent* event); // RPL_ENDOFWHOWAS
+ Q_INVOKABLE void processIrcEvent432(IrcEvent* event); // ERR_ERRONEUSNICKNAME
+ Q_INVOKABLE void processIrcEvent433(IrcEvent* event); // ERR_NICKNAMEINUSE
+ Q_INVOKABLE void processIrcEvent437(IrcEvent* event); // ERR_UNAVAILRESOURCE
// Q_INVOKABLE void processIrcEvent(IrcEvent *event);
/* CTCP handlers */
- Q_INVOKABLE void processCtcpEvent(CtcpEvent *event);
+ Q_INVOKABLE void processCtcpEvent(CtcpEvent* event);
- Q_INVOKABLE void handleCtcpAction(CtcpEvent *event);
- Q_INVOKABLE void handleCtcpPing(CtcpEvent *event);
- Q_INVOKABLE void defaultHandler(const QString &cmd, CtcpEvent *event);
+ Q_INVOKABLE void handleCtcpAction(CtcpEvent* event);
+ Q_INVOKABLE void handleCtcpPing(CtcpEvent* event);
+ Q_INVOKABLE void defaultHandler(const QString& cmd, CtcpEvent* event);
public slots:
//! Creates and sends a MessageEvent
- void displayMsg(NetworkEvent *event,
- Message::Type msgType,
- const QString &msg,
- const QString &sender = QString(),
- const QString &target = QString(),
- Message::Flags msgFlags = Message::None);
+ void displayMsg(NetworkEvent* event,
+ Message::Type msgType,
+ const QString& msg,
+ const QString& sender = QString(),
+ const QString& target = QString(),
+ Message::Flags msgFlags = Message::None);
signals:
- void newMessageEvent(Event *event);
+ void newMessageEvent(Event* event);
private:
- bool checkParamCount(IrcEvent *event, int minParams);
+ bool checkParamCount(IrcEvent* event, int minParams);
- CoreSession *_coreSession;
+ CoreSession* _coreSession;
bool _whois;
};
-
#endif
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "identserver.h"
+
#include <limits>
#include "corenetwork.h"
-#include "identserver.h"
#include "logmessage.h"
-IdentServer::IdentServer(QObject *parent)
+IdentServer::IdentServer(QObject* parent)
: QObject(parent)
{
connect(&_server, &QTcpServer::newConnection, this, &IdentServer::incomingConnection);
connect(&_v6server, &QTcpServer::newConnection, this, &IdentServer::incomingConnection);
}
-
bool IdentServer::startListening()
{
uint16_t port = Quassel::optionValue("ident-port").toUShort();
bool success = false;
if (_v6server.listen(QHostAddress("::1"), port)) {
- quInfo() << qPrintable(
- tr("Listening for identd clients on IPv6 %1 port %2")
- .arg("::1")
- .arg(_v6server.serverPort())
- );
+ quInfo() << qPrintable(tr("Listening for identd clients on IPv6 %1 port %2").arg("::1").arg(_v6server.serverPort()));
success = true;
}
if (_server.listen(QHostAddress("127.0.0.1"), port)) {
- quInfo() << qPrintable(
- tr("Listening for identd clients on IPv4 %1 port %2")
- .arg("127.0.0.1")
- .arg(_server.serverPort())
- );
+ quInfo() << qPrintable(tr("Listening for identd clients on IPv4 %1 port %2").arg("127.0.0.1").arg(_server.serverPort()));
success = true;
}
return success;
}
-
-void IdentServer::stopListening(const QString &msg)
+void IdentServer::stopListening(const QString& msg)
{
bool wasListening = false;
}
}
-
void IdentServer::incomingConnection()
{
- auto server = qobject_cast<QTcpServer *>(sender());
+ auto server = qobject_cast<QTcpServer*>(sender());
Q_ASSERT(server);
while (server->hasPendingConnections()) {
- QTcpSocket *socket = server->nextPendingConnection();
+ QTcpSocket* socket = server->nextPendingConnection();
connect(socket, &QIODevice::readyRead, this, &IdentServer::respond);
connect(socket, &QAbstractSocket::disconnected, socket, &QObject::deleteLater);
}
}
-
void IdentServer::respond()
{
- auto *socket = qobject_cast<QTcpSocket *>(sender());
+ auto* socket = qobject_cast<QTcpSocket*>(sender());
Q_ASSERT(socket);
qint64 transactionId = _socketId;
}
}
-
-void Request::respondSuccess(const QString &user)
+void Request::respondSuccess(const QString& user)
{
if (socket) {
QString data = query + " : USERID : Quassel : " + user + "\r\n";
}
}
-
-void Request::respondError(const QString &error)
+void Request::respondError(const QString& error)
{
if (socket) {
QString data = query + " : ERROR : " + error + "\r\n";
}
}
-
bool IdentServer::responseAvailable(Request request) const
{
if (!_connections.contains(request.localPort)) {
return true;
}
-
-void IdentServer::addSocket(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort,
- const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId)
+void IdentServer::addSocket(const CoreIdentity* identity,
+ const QHostAddress& localAddress,
+ quint16 localPort,
+ const QHostAddress& peerAddress,
+ quint16 peerPort,
+ qint64 socketId)
{
Q_UNUSED(localAddress)
Q_UNUSED(peerAddress)
Q_UNUSED(peerPort)
- const CoreNetwork *network = qobject_cast<CoreNetwork *>(sender());
- _connections[localPort] = network->coreSession()->strictCompliantIdent(identity);;
+ const CoreNetwork* network = qobject_cast<CoreNetwork*>(sender());
+ _connections[localPort] = network->coreSession()->strictCompliantIdent(identity);
+ ;
processWaiting(socketId);
}
-
-void IdentServer::removeSocket(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort,
- const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId)
+void IdentServer::removeSocket(const CoreIdentity* identity,
+ const QHostAddress& localAddress,
+ quint16 localPort,
+ const QHostAddress& peerAddress,
+ quint16 peerPort,
+ qint64 socketId)
{
Q_UNUSED(identity)
Q_UNUSED(localAddress)
processWaiting(socketId);
}
-
qint64 IdentServer::addWaitingSocket()
{
qint64 newSocketId = _socketId++;
return newSocketId;
}
-
qint64 IdentServer::lowestSocketId() const
{
if (_waiting.empty()) {
return _waiting.front();
}
-
void IdentServer::removeWaitingSocket(qint64 socketId)
{
_waiting.remove(socketId);
}
-
void IdentServer::processWaiting(qint64 socketId)
{
removeWaitingSocket(socketId);
});
}
-
-bool operator==(const Request &a, const Request &b)
+bool operator==(const Request& a, const Request& b)
{
return a.requestId == b.requestId;
}
qint64 transactionId;
qint64 requestId;
- friend bool operator==(const Request &a, const Request &b);
+ friend bool operator==(const Request& a, const Request& b);
- void respondSuccess(const QString &user);
- void respondError(const QString &error);
+ void respondSuccess(const QString& user);
+ void respondError(const QString& error);
};
-
class IdentServer : public QObject
{
Q_OBJECT
public:
- IdentServer(QObject *parent = nullptr);
+ IdentServer(QObject* parent = nullptr);
bool startListening();
- void stopListening(const QString &msg);
+ void stopListening(const QString& msg);
qint64 addWaitingSocket();
public slots:
- void addSocket(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId);
- void removeSocket(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId);
+ void addSocket(const CoreIdentity* identity,
+ const QHostAddress& localAddress,
+ quint16 localPort,
+ const QHostAddress& peerAddress,
+ quint16 peerPort,
+ qint64 socketId);
+ void removeSocket(const CoreIdentity* identity,
+ const QHostAddress& localAddress,
+ quint16 localPort,
+ const QHostAddress& peerAddress,
+ quint16 peerPort,
+ qint64 socketId);
private slots:
void incomingConnection();
#include "networkevent.h"
#ifdef HAVE_QCA2
-# include "cipher.h"
-# include "keyevent.h"
+# include "cipher.h"
+# include "keyevent.h"
#endif
-IrcParser::IrcParser(CoreSession *session) :
- QObject(session),
- _coreSession(session)
+IrcParser::IrcParser(CoreSession* session)
+ : QObject(session)
+ , _coreSession(session)
{
// Check if raw IRC logging is enabled
_debugLogRawIrc = (Quassel::isOptionSet("debug-irc") || Quassel::isOptionSet("debug-irc-id"));
connect(this, &IrcParser::newEvent, coreSession()->eventManager(), &EventManager::postEvent);
}
-
-bool IrcParser::checkParamCount(const QString &cmd, const QList<QByteArray> ¶ms, int minParams)
+bool IrcParser::checkParamCount(const QString& cmd, const QList<QByteArray>& params, int minParams)
{
if (params.count() < minParams) {
qWarning() << "Expected" << minParams << "params for IRC command" << cmd << ", got:" << params;
return true;
}
-
-QByteArray IrcParser::decrypt(Network *network, const QString &bufferName, const QByteArray &message, bool isTopic)
+QByteArray IrcParser::decrypt(Network* network, const QString& bufferName, const QByteArray& message, bool isTopic)
{
#ifdef HAVE_QCA2
if (message.isEmpty())
if (!Cipher::neededFeaturesAvailable())
return message;
- Cipher *cipher = qobject_cast<CoreNetwork *>(network)->cipher(bufferName);
+ Cipher* cipher = qobject_cast<CoreNetwork*>(network)->cipher(bufferName);
if (!cipher || cipher->key().isEmpty())
return message;
#endif
}
-
/* parse the raw server string and generate an appropriate event */
/* used to be handleServerMsg() */
-void IrcParser::processNetworkIncoming(NetworkDataEvent *e)
+void IrcParser::processNetworkIncoming(NetworkDataEvent* e)
{
- auto *net = qobject_cast<CoreNetwork *>(e->network());
+ auto* net = qobject_cast<CoreNetwork*>(e->network());
if (!net) {
qWarning() << "Received network event without valid network pointer!";
return;
}
// Log the message if enabled and network ID matches or allows all
- if (_debugLogRawIrc
- && (_debugLogRawNetId == -1 || net->networkId().toInt() == _debugLogRawNetId)) {
+ if (_debugLogRawIrc && (_debugLogRawNetId == -1 || net->networkId().toInt() == _debugLogRawNetId)) {
// Include network ID
qDebug() << "IRC net" << net->networkId() << "<<" << msg;
}
// next string without a whitespace is the command
cmd = foo.trimmed();
- QList<Event *> events;
+ QList<Event*> events;
EventManager::EventType type = EventManager::Invalid;
uint num = cmd.toUInt();
// nice pre-parsed events that the CTCP handler can consume.
QStringList decParams;
- bool defaultHandling = true; // whether to automatically copy the remaining params and send the event
+ bool defaultHandling = true; // whether to automatically copy the remaining params and send the event
switch (type) {
case EventManager::IrcEventPrivmsg:
- defaultHandling = false; // this might create a list of events
+ defaultHandling = false; // this might create a list of events
if (checkParamCount(cmd, params, 1)) {
QString senderNick = nickFromMask(prefix);
// consider including this within an if (!isSelfMessage) block
msg = decrypt(net, target, msg);
- IrcEventRawMessage *rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg, net, msg, prefix, target, e->timestamp());
+ IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawPrivmsg,
+ net,
+ msg,
+ prefix,
+ target,
+ e->timestamp());
if (isSelfMessage) {
// Self-messages need processed differently, tag as such via flag.
rawMessage->setFlag(EventManager::Self);
QString target = *targetIter;
// special treatment for welcome messages like:
- // :ChanServ!ChanServ@services. NOTICE egst :[#apache] Welcome, this is #apache. Please read the in-channel topic message. This channel is being logged by IRSeekBot. If you have any question please see http://blog.freenode.net/?p=68
+ // :ChanServ!ChanServ@services. NOTICE egst :[#apache] Welcome, this is #apache. Please read the in-channel topic message.
+ // This channel is being logged by IRSeekBot. If you have any question please see http://blog.freenode.net/?p=68
if (!net->isChannelName(target)) {
QString decMsg = net->serverDecode(params.at(1));
QRegExp welcomeRegExp(R"(^\[([^\]]+)\] )");
if (welcomeRegExp.indexIn(decMsg) != -1) {
QString channelname = welcomeRegExp.cap(1);
decMsg = decMsg.mid(welcomeRegExp.matchedLength());
- CoreIrcChannel *chan = static_cast<CoreIrcChannel *>(net->ircChannel(channelname)); // we only have CoreIrcChannels in the core, so this cast is safe
+ CoreIrcChannel* chan = static_cast<CoreIrcChannel*>(
+ net->ircChannel(channelname)); // we only have CoreIrcChannels in the core, so this cast is safe
if (chan && !chan->receivedWelcomeMsg()) {
chan->setReceivedWelcomeMsg();
events << new MessageEvent(Message::Notice, net, decMsg, prefix, channelname, Message::None, e->timestamp());
bool keyExchangeAllowed = (!net->isChannelName(target) && !isSelfMessage);
if (params[1].startsWith("DH1080_INIT") && keyExchangeAllowed) {
events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Init, params[1].mid(12));
- } else if (params[1].startsWith("DH1080_FINISH") && keyExchangeAllowed) {
+ }
+ else if (params[1].startsWith("DH1080_FINISH") && keyExchangeAllowed) {
events << new KeyEvent(EventManager::KeyEvent, net, prefix, target, KeyEvent::Finish, params[1].mid(14));
- } else
+ }
+ else
#endif
{
- IrcEventRawMessage *rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawNotice, net, params[1], prefix, target, e->timestamp());
+ IrcEventRawMessage* rawMessage = new IrcEventRawMessage(EventManager::IrcEventRawNotice,
+ net,
+ params[1],
+ prefix,
+ target,
+ e->timestamp());
if (isSelfMessage) {
// Self-messages need processed differently, tag as such via flag.
rawMessage->setFlag(EventManager::Self);
// the following events need only special casing for param decoding
case EventManager::IrcEventKick:
- if (params.count() >= 3) { // we have a reason
+ if (params.count() >= 3) { // we have a reason
decParams << net->serverDecode(params.at(0)) << net->serverDecode(params.at(1));
- decParams << net->channelDecode(decParams.first(), params.at(2)); // kick reason
+ decParams << net->channelDecode(decParams.first(), params.at(2)); // kick reason
}
break;
}
break;
- case EventManager::IrcEventAway:
- {
- // Update hostmask info first. This will create the nick if it doesn't exist, e.g.
- // away-notify data being sent before JOIN messages.
- net->updateNickFromMask(prefix);
- // Separate nick in order to separate server and user decoding
- QString nick = nickFromMask(prefix);
- decParams << nick;
- decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString());
- }
- break;
+ case EventManager::IrcEventAway: {
+ // Update hostmask info first. This will create the nick if it doesn't exist, e.g.
+ // away-notify data being sent before JOIN messages.
+ net->updateNickFromMask(prefix);
+ // Separate nick in order to separate server and user decoding
+ QString nick = nickFromMask(prefix);
+ decParams << nick;
+ decParams << (params.count() >= 1 ? net->userDecode(nick, params.at(0)) : QString());
+ } break;
case EventManager::IrcEventNumeric:
switch (num) {
// If server doesn't support capabilities, it will report this message. Turn it
// into a nicer message since it's not a real error.
defaultHandling = false;
- events << new MessageEvent(Message::Server, e->network(),
+ events << new MessageEvent(Message::Server,
+ e->network(),
tr("Capability negotiation not supported"),
- QString(), QString(), Message::None, e->timestamp());
+ QString(),
+ QString(),
+ Message::None,
+ e->timestamp());
}
break;
}
if (!decParams.isEmpty() && decParams.last().endsWith(' '))
decParams.append(decParams.takeLast().trimmed());
- IrcEvent *event;
+ IrcEvent* event;
if (type == EventManager::IrcEventNumeric)
event = new IrcEventNumeric(num, net, prefix, target);
else
events << event;
}
- foreach(Event *event, events) {
+ foreach (Event* event, events) {
emit newEvent(event);
}
}
Q_OBJECT
public:
- IrcParser(CoreSession *session);
+ IrcParser(CoreSession* session);
- inline CoreSession *coreSession() const { return _coreSession; }
- inline EventManager *eventManager() const { return coreSession()->eventManager(); }
+ inline CoreSession* coreSession() const { return _coreSession; }
+ inline EventManager* eventManager() const { return coreSession()->eventManager(); }
signals:
- void newEvent(Event *);
+ void newEvent(Event*);
protected:
- Q_INVOKABLE void processNetworkIncoming(NetworkDataEvent *e);
+ Q_INVOKABLE void processNetworkIncoming(NetworkDataEvent* e);
- bool checkParamCount(const QString &cmd, const QList<QByteArray> ¶ms, int minParams);
+ bool checkParamCount(const QString& cmd, const QList<QByteArray>& params, int minParams);
// no-op if we don't have crypto support!
- QByteArray decrypt(Network *network, const QString &target, const QByteArray &message, bool isTopic = false);
+ QByteArray decrypt(Network* network, const QString& target, const QByteArray& message, bool isTopic = false);
private:
- CoreSession *_coreSession;
+ CoreSession* _coreSession;
- bool _debugLogRawIrc; ///< If true, include raw IRC socket messages in the debug log
- qint32 _debugLogRawNetId; ///< Network ID for logging raw IRC socket messages, or -1 for all
+ bool _debugLogRawIrc; ///< If true, include raw IRC socket messages in the debug log
+ qint32 _debugLogRawNetId; ///< Network ID for logging raw IRC socket messages, or -1 for all
};
-
#endif
#include "keyevent.h"
-Event *KeyEvent::create(EventManager::EventType type, QVariantMap &map, Network *network)
+Event* KeyEvent::create(EventManager::EventType type, QVariantMap& map, Network* network)
{
if (type == EventManager::KeyEvent)
return new KeyEvent(type, map, network);
return nullptr;
}
-
-KeyEvent::KeyEvent(EventManager::EventType type, QVariantMap &map, Network *network)
+KeyEvent::KeyEvent(EventManager::EventType type, QVariantMap& map, Network* network)
: IrcEvent(type, map, network)
{
_exchangeType = static_cast<ExchangeType>(map.take("exchangeType").toInt());
_key = map.take("key").toByteArray();
}
-
-void KeyEvent::toVariantMap(QVariantMap &map) const
+void KeyEvent::toVariantMap(QVariantMap& map) const
{
IrcEvent::toVariantMap(map);
map["exchangeType"] = exchangeType();
class KeyEvent : public IrcEvent
{
public:
- enum ExchangeType {
+ enum ExchangeType
+ {
Init,
Finish
};
- explicit KeyEvent(EventManager::EventType type, Network *network, const QString &prefix, QString target,
- ExchangeType exchangeType, QByteArray key,
- const QDateTime ×tamp = QDateTime())
- : IrcEvent(type, network, prefix),
- _exchangeType(exchangeType),
- _target(std::move(target)),
- _key(std::move(key))
+ explicit KeyEvent(EventManager::EventType type,
+ Network* network,
+ const QString& prefix,
+ QString target,
+ ExchangeType exchangeType,
+ QByteArray key,
+ const QDateTime& timestamp = QDateTime())
+ : IrcEvent(type, network, prefix)
+ , _exchangeType(exchangeType)
+ , _target(std::move(target))
+ , _key(std::move(key))
{
setTimestamp(timestamp);
}
-
inline ExchangeType exchangeType() const { return _exchangeType; }
inline void setExchangeType(ExchangeType type) { _exchangeType = type; }
inline QString target() const { return _target; }
- inline void setTarget(const QString &target) { _target = target; }
+ inline void setTarget(const QString& target) { _target = target; }
inline QByteArray key() const { return _key; }
- inline void setKey(const QByteArray &key) { _key = key; }
+ inline void setKey(const QByteArray& key) { _key = key; }
- static Event *create(EventManager::EventType type, QVariantMap &map, Network *network);
+ static Event* create(EventManager::EventType type, QVariantMap& map, Network* network);
protected:
- explicit KeyEvent(EventManager::EventType type, QVariantMap &map, Network *network);
- void toVariantMap(QVariantMap &map) const override;
+ explicit KeyEvent(EventManager::EventType type, QVariantMap& map, Network* network);
+ void toVariantMap(QVariantMap& map) const override;
inline QString className() const override { return "KeyEvent"; }
- inline void debugInfo(QDebug &dbg) const override
+ inline void debugInfo(QDebug& dbg) const override
{
NetworkEvent::debugInfo(dbg);
- dbg << ", prefix = " << qPrintable(prefix())
- << ", target = " << qPrintable(target())
- << ", exchangetype = " << (exchangeType() == Init ? "init" : "finish")
- << ", key = " << key();
+ dbg << ", prefix = " << qPrintable(prefix()) << ", target = " << qPrintable(target())
+ << ", exchangetype = " << (exchangeType() == Init ? "init" : "finish") << ", key = " << key();
}
-
private:
ExchangeType _exchangeType;
QString _target;
QByteArray _key;
};
-
#endif
#include <ldap.h>
//#endif
-LdapAuthenticator::LdapAuthenticator(QObject *parent)
- : Authenticator(parent),
- _connection(nullptr)
-{
-}
-
+LdapAuthenticator::LdapAuthenticator(QObject* parent)
+ : Authenticator(parent)
+ , _connection(nullptr)
+{}
LdapAuthenticator::~LdapAuthenticator()
{
}
}
-
bool LdapAuthenticator::isAvailable() const
{
// FIXME: probably this should test if we can speak to the LDAP server.
return true;
}
-
QString LdapAuthenticator::backendId() const
{
// We identify the backend to use for the monolithic core by this identifier.
return QString("LDAP");
}
-
QString LdapAuthenticator::displayName() const
{
return tr("LDAP");
}
-
QString LdapAuthenticator::description() const
{
return tr("Authenticate users using an LDAP server.");
}
-
QVariantList LdapAuthenticator::setupData() const
{
// The parameters needed for LDAP.
QVariantList data;
- data << "Hostname" << tr("Hostname") << QString{"ldap://localhost"}
- << "Port" << tr("Port") << DEFAULT_LDAP_PORT
- << "BindDN" << tr("Bind DN") << QString{}
- << "BindPassword" << tr("Bind Password") << QString{}
- << "BaseDN" << tr("Base DN") << QString{}
- << "Filter" << tr("Filter") << QString{}
- << "UidAttribute" << tr("UID Attribute") << QString{"uid"}
- ;
+ data << "Hostname" << tr("Hostname") << QString{"ldap://localhost"} << "Port" << tr("Port") << DEFAULT_LDAP_PORT << "BindDN"
+ << tr("Bind DN") << QString{} << "BindPassword" << tr("Bind Password") << QString{} << "BaseDN" << tr("Base DN") << QString{}
+ << "Filter" << tr("Filter") << QString{} << "UidAttribute" << tr("UID Attribute") << QString{"uid"};
return data;
}
-
-void LdapAuthenticator::setAuthProperties(const QVariantMap &properties,
- const QProcessEnvironment &environment,
- bool loadFromEnvironment)
+void LdapAuthenticator::setAuthProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment)
{
if (loadFromEnvironment) {
_hostName = environment.value("AUTH_LDAP_HOSTNAME");
_baseDN = environment.value("AUTH_LDAP_BASE_DN");
_filter = environment.value("AUTH_LDAP_FILTER");
_uidAttribute = environment.value("AUTH_LDAP_UID_ATTRIBUTE");
- } else {
+ }
+ else {
_hostName = properties["Hostname"].toString();
_port = properties["Port"].toInt();
_bindDN = properties["BindDN"].toString();
// class should be created implementing it.
// i.e. a provider that does its own thing and then pokes at the current storage
// through the default core method.
-UserId LdapAuthenticator::validateUser(const QString &username, const QString &password)
+UserId LdapAuthenticator::validateUser(const QString& username, const QString& password)
{
bool result = ldapAuth(username, password);
if (!result) {
return quasselId;
}
-
-bool LdapAuthenticator::setup(const QVariantMap &settings,
- const QProcessEnvironment &environment,
- bool loadFromEnvironment)
+bool LdapAuthenticator::setup(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment)
{
setAuthProperties(settings, environment, loadFromEnvironment);
bool status = ldapConnect();
return status;
}
-
-Authenticator::State LdapAuthenticator::init(const QVariantMap &settings,
- const QProcessEnvironment &environment,
- bool loadFromEnvironment)
+Authenticator::State LdapAuthenticator::init(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment)
{
setAuthProperties(settings, environment, loadFromEnvironment);
return true;
}
-
void LdapAuthenticator::ldapDisconnect()
{
if (_connection == nullptr) {
_connection = nullptr;
}
-
-bool LdapAuthenticator::ldapAuth(const QString &username, const QString &password)
+bool LdapAuthenticator::ldapAuth(const QString& username, const QString& password)
{
if (password.isEmpty()) {
return false;
const QByteArray ldapQuery = "(&(" + uidAttribute + '=' + username.toLocal8Bit() + ")" + _filter.toLocal8Bit() + ")";
- res = ldap_search_ext_s(_connection, baseDN.constData(), LDAP_SCOPE_SUBTREE, ldapQuery.constData(), nullptr, 0, nullptr, nullptr, nullptr, 0, &msg);
+ res = ldap_search_ext_s(_connection,
+ baseDN.constData(),
+ LDAP_SCOPE_SUBTREE,
+ ldapQuery.constData(),
+ nullptr,
+ 0,
+ nullptr,
+ nullptr,
+ nullptr,
+ 0,
+ &msg);
if (res != LDAP_SUCCESS) {
qWarning() << "Refusing connection from" << username << "(LDAP search failed:" << ldap_err2string(res) << ")";
cred.bv_val = passwordArray.data();
cred.bv_len = password.size();
- char *userDN = ldap_get_dn(_connection, entry);
+ char* userDN = ldap_get_dn(_connection, entry);
res = ldap_sasl_bind_s(_connection, userDN, LDAP_SASL_SIMPLE, &cred, nullptr, nullptr, nullptr);
#pragma once
#include "authenticator.h"
-
#include "core.h"
// Link against LDAP.
Q_OBJECT
public:
- LdapAuthenticator(QObject *parent = nullptr);
+ LdapAuthenticator(QObject* parent = nullptr);
~LdapAuthenticator() override;
public slots:
bool canChangePassword() const override { return false; }
- bool setup(const QVariantMap &settings, const QProcessEnvironment &environment,
- bool loadFromEnvironment) override;
- State init(const QVariantMap &settings, const QProcessEnvironment &environment,
- bool loadFromEnvironment) override;
- UserId validateUser(const QString &user, const QString &password) override;
+ bool setup(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) override;
+ State init(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) override;
+ UserId validateUser(const QString& user, const QString& password) override;
protected:
- void setAuthProperties(const QVariantMap &properties, const QProcessEnvironment &environment,
- bool loadFromEnvironment);
+ void setAuthProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment);
bool ldapConnect();
void ldapDisconnect();
- bool ldapAuth(const QString &username, const QString &password);
+ bool ldapAuth(const QString& username, const QString& password);
// Protected methods for retrieving info about the LDAP connection.
QString hostName() const { return _hostName; }
QString _uidAttribute;
// The actual connection object.
- LDAP *_connection {nullptr};
+ LDAP* _connection{nullptr};
};
***************************************************************************/
#include "netsplit.h"
-#include "network.h"
-#include "util.h"
#include <QRegExp>
-Netsplit::Netsplit(Network *network, QObject *parent)
- : QObject(parent),
- _network(network), _quitMsg(""), _sentQuit(false), _joinCounter(0), _quitCounter(0)
+#include "network.h"
+#include "util.h"
+
+Netsplit::Netsplit(Network* network, QObject* parent)
+ : QObject(parent)
+ , _network(network)
+ , _quitMsg("")
+ , _sentQuit(false)
+ , _joinCounter(0)
+ , _quitCounter(0)
{
_discardTimer.setSingleShot(true);
_joinTimer.setSingleShot(true);
_discardTimer.start(3600000);
}
-
-void Netsplit::userQuit(const QString &sender, const QStringList &channels, const QString &msg)
+void Netsplit::userQuit(const QString& sender, const QStringList& channels, const QString& msg)
{
if (_quitMsg.isEmpty())
_quitMsg = msg;
- foreach(QString channel, channels) {
+ foreach (QString channel, channels) {
_quits[channel].append(sender);
}
_quitCounter++;
_quitTimer.start(10000);
}
-
-bool Netsplit::userJoined(const QString &sender, const QString &channel)
+bool Netsplit::userJoined(const QString& sender, const QString& channel)
{
if (!_quits.contains(channel))
return false;
- QStringList &users = _quits[channel];
+ QStringList& users = _quits[channel];
QStringList::iterator userIter;
const QString senderNick = nickFromMask(sender);
_joinCounter++;
- if (_quits.empty()) // all users joined already - no need to wait
+ if (_quits.empty()) // all users joined already - no need to wait
_joinTimer.start(0);
- else // wait 30s to finish the netsplit-join
+ else // wait 30s to finish the netsplit-join
_joinTimer.start(30000);
return true;
}
-
-bool Netsplit::userAlreadyJoined(const QString &sender, const QString &channel)
+bool Netsplit::userAlreadyJoined(const QString& sender, const QString& channel)
{
if (_joins.value(channel).first.contains(sender))
return true;
return false;
}
-
-void Netsplit::addMode(const QString &sender, const QString &channel, const QString &mode)
+void Netsplit::addMode(const QString& sender, const QString& channel, const QString& mode)
{
if (!_joins.contains(channel))
return;
_joins[channel].second[idx].append(mode);
}
-
-bool Netsplit::isNetsplit(const QString &quitMessage)
+bool Netsplit::isNetsplit(const QString& quitMessage)
{
// check if we find some common chars that disqualify the netsplit as such
if (quitMessage.contains(':') || quitMessage.contains('/'))
return false;
}
-
void Netsplit::joinTimeout()
{
if (!_sentQuit) {
quitTimeout();
}
- QHash<QString, QPair<QStringList, QStringList> >::iterator it;
+ QHash<QString, QPair<QStringList, QStringList>>::iterator it;
/*
Try to catch server jumpers.
A netsplit is assumed over only if at least 1/3 of all quits had their corresponding
join again.
*/
- if (_joinCounter < _quitCounter/3) {
+ if (_joinCounter < _quitCounter / 3) {
for (it = _joins.begin(); it != _joins.end(); ++it)
emit earlyJoin(network(), it.key(), it.value().first, it.value().second);
emit finished();
}
-
void Netsplit::quitTimeout()
{
// send netsplitQuit for every recorded channel
for (channelIter = _quits.begin(); channelIter != _quits.end(); ++channelIter) {
QStringList usersToSend;
- foreach(QString user, channelIter.value()) {
+ foreach (QString user, channelIter.value()) {
if (!_quitsWithMessageSent.value(channelIter.key()).contains(user)) {
usersToSend << user;
_quitsWithMessageSent[channelIter.key()].append(user);
#ifndef NETSPLIT_H
#define NETSPLIT_H
-#include <QTimer>
#include <QHash>
#include <QPair>
#include <QStringList>
+#include <QTimer>
class Network;
{
Q_OBJECT
public:
- Netsplit(Network *network, QObject *parent = nullptr);
+ Netsplit(Network* network, QObject* parent = nullptr);
- inline Network *network() const { return _network; }
+ inline Network* network() const { return _network; }
//! Add a user to the netsplit
/** Call this method if you noticed a netsplit.
- * \note This method doesn't check if it really is a netsplit.
- * \note Check with isNetsplit(const QString &quitMessage) before calling it!
- *
- * \param sender The sender string of the quitting user
- * \param channels The channels that user shared with us
- * \param msg The quit message
- */
- void userQuit(const QString &sender, const QStringList &channels, const QString &msg);
+ * \note This method doesn't check if it really is a netsplit.
+ * \note Check with isNetsplit(const QString &quitMessage) before calling it!
+ *
+ * \param sender The sender string of the quitting user
+ * \param channels The channels that user shared with us
+ * \param msg The quit message
+ */
+ void userQuit(const QString& sender, const QStringList& channels, const QString& msg);
//! Remove a user from the netsplit
/** Call this method if a user joined after a netsplit occured.
- *
- * \param sender The sender string of the joined user
- * \param channel The channel that user shares with us
- * \return true if user was found in the netsplit
- */
- bool userJoined(const QString &sender, const QString &channel);
+ *
+ * \param sender The sender string of the joined user
+ * \param channel The channel that user shares with us
+ * \return true if user was found in the netsplit
+ */
+ bool userJoined(const QString& sender, const QString& channel);
//! Check if user has joined since netsplit
/** This method shows if a user has already joined after being hit by netsplit
- * \note The method doesn't check if the user was recorded in the netsplit!
- *
- * \param sender The sender string of the user
- * \param channel The channel the user shares with us
- * \return true if user joined after a netsplit
- */
- bool userAlreadyJoined(const QString &sender, const QString &channel);
+ * \note The method doesn't check if the user was recorded in the netsplit!
+ *
+ * \param sender The sender string of the user
+ * \param channel The channel the user shares with us
+ * \return true if user joined after a netsplit
+ */
+ bool userAlreadyJoined(const QString& sender, const QString& channel);
//! Add mode to user
/** Use this method to buffer userspecific channel modes until netsplitJoin is emitted.
- *
- * \param sender The sender string of the user
- * \param channel The channel the user shares with us
- * \return true if user joined after a netsplit
- */
- void addMode(const QString &sender, const QString &channel, const QString &mode);
+ *
+ * \param sender The sender string of the user
+ * \param channel The channel the user shares with us
+ * \return true if user joined after a netsplit
+ */
+ void addMode(const QString& sender, const QString& channel, const QString& mode);
//! Check if a string matches the criteria for a netsplit
/** \param quitMessage The message to be checked
- * \return true if the message is a netsplit
- */
- static bool isNetsplit(const QString &quitMessage);
+ * \return true if the message is a netsplit
+ */
+ static bool isNetsplit(const QString& quitMessage);
signals:
//! A bulk-join of netsplitted users timed out
/** Whenever the internal join-timer times out, we consider the bulk-join to be finished and emit that signal
- * for every channel. This is the end of a netsplit.
- * \param net The network
- * \param channel The IRC channel
- * \param users A list of all users that joined that channel
- * \param modes A list of all modes the users got set after joining again
- * \param quitMessage The Quitmessage and thus the servers that got split
- */
- void netsplitJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes, const QString &quitMessage);
+ * for every channel. This is the end of a netsplit.
+ * \param net The network
+ * \param channel The IRC channel
+ * \param users A list of all users that joined that channel
+ * \param modes A list of all modes the users got set after joining again
+ * \param quitMessage The Quitmessage and thus the servers that got split
+ */
+ void netsplitJoin(Network* net, const QString& channel, const QStringList& users, const QStringList& modes, const QString& quitMessage);
//! A (probably bulk-) join of netsplitted users.
/** If users hit by the split joined before the netsplit is considered over, join the users with a normal join.
- * \param net The network
- * \param channel The IRC channel
- * \param users A list of all users that joined that channel
- * \param modes A list of all modes the users got set after joining again
- */
- void earlyJoin(Network *net, const QString &channel, const QStringList &users, const QStringList &modes);
+ * \param net The network
+ * \param channel The IRC channel
+ * \param users A list of all users that joined that channel
+ * \param modes A list of all modes the users got set after joining again
+ */
+ void earlyJoin(Network* net, const QString& channel, const QStringList& users, const QStringList& modes);
//! A bulk-quit of netsplitted users timed out
/** Whenever the internal quit-timer times out, we consider the bulk-quit to be finished and emit that signal
- * for every channel.
- * \param net The network
- * \param channel The IRC channel
- * \param users A list of all users that quitted in that channel
- * \param quitMessage The Quitmessage and thus the servers that got split
- */
- void netsplitQuit(Network *net, const QString &channel, const QStringList &users, const QString &quitMessage);
+ * for every channel.
+ * \param net The network
+ * \param channel The IRC channel
+ * \param users A list of all users that quitted in that channel
+ * \param quitMessage The Quitmessage and thus the servers that got split
+ */
+ void netsplitQuit(Network* net, const QString& channel, const QStringList& users, const QString& quitMessage);
//! The Netsplit is considered finished
/** This signal is emitted right after all netsplitJoin signals have been sent or whenever the
- * internal timer signals a timeout.
- * Simply delete the object and remove it from structures when you receive that signal.
- */
+ * internal timer signals a timeout.
+ * Simply delete the object and remove it from structures when you receive that signal.
+ */
void finished();
private slots:
void quitTimeout();
private:
- Network *_network;
+ Network* _network;
QString _quitMsg;
// key: channel name
// value: senderstring, list of modes
- QHash<QString, QPair<QStringList, QStringList> > _joins;
+ QHash<QString, QPair<QStringList, QStringList>> _joins;
QHash<QString, QStringList> _quits;
QHash<QString, QStringList> _quitsWithMessageSent;
bool _sentQuit;
int _quitCounter;
};
-
-#endif // NETSPLIT_H
+#endif // NETSPLIT_H
***************************************************************************/
#ifdef HAVE_UMASK
-# include <sys/types.h>
-# include <sys/stat.h>
+# include <sys/stat.h>
+# include <sys/types.h>
#endif /* HAVE_UMASK */
#include <QString>
#include "corenetwork.h"
#include "oidentdconfiggenerator.h"
-OidentdConfigGenerator::OidentdConfigGenerator(QObject *parent) :
- QObject(parent)
+OidentdConfigGenerator::OidentdConfigGenerator(QObject* parent)
+ : QObject(parent)
{
if (!_initialized)
init();
}
-
OidentdConfigGenerator::~OidentdConfigGenerator()
{
_quasselConfig.clear();
_configFile->deleteLater();
}
-
bool OidentdConfigGenerator::init()
{
_configDir = QDir::homePath();
return _initialized;
}
-
-QString OidentdConfigGenerator::sysIdentForIdentity(const CoreIdentity *identity) const {
+QString OidentdConfigGenerator::sysIdentForIdentity(const CoreIdentity* identity) const
+{
// Make sure the identity's ident complies with strict mode if enabled
- const CoreNetwork *network = qobject_cast<CoreNetwork *>(sender());
+ const CoreNetwork* network = qobject_cast<CoreNetwork*>(sender());
return network->coreSession()->strictCompliantIdent(identity);
}
-
-bool OidentdConfigGenerator::addSocket(const CoreIdentity *identity,
- const QHostAddress &localAddress, quint16 localPort,
- const QHostAddress &peerAddress, quint16 peerPort,
+bool OidentdConfigGenerator::addSocket(const CoreIdentity* identity,
+ const QHostAddress& localAddress,
+ quint16 localPort,
+ const QHostAddress& peerAddress,
+ quint16 peerPort,
qint64 socketId)
{
Q_UNUSED(localAddress)
return ret;
}
-
//! not yet implemented
-bool OidentdConfigGenerator::removeSocket(const CoreIdentity *identity,
- const QHostAddress &localAddress, quint16 localPort,
- const QHostAddress &peerAddress, quint16 peerPort,
+bool OidentdConfigGenerator::removeSocket(const CoreIdentity* identity,
+ const QHostAddress& localAddress,
+ quint16 localPort,
+ const QHostAddress& peerAddress,
+ quint16 peerPort,
qint64 socketId)
{
Q_UNUSED(identity)
return true;
}
-
bool OidentdConfigGenerator::parseConfig(bool readQuasselStanzas)
{
if (!_configFile->exists())
return true;
}
-
bool OidentdConfigGenerator::writeConfig()
{
#ifdef HAVE_UMASK
- mode_t prev_umask = umask(S_IXUSR | S_IWGRP | S_IXGRP | S_IWOTH | S_IXOTH); // == 0133, rw-r--r--
+ mode_t prev_umask = umask(S_IXUSR | S_IWGRP | S_IXGRP | S_IWOTH | S_IXOTH); // == 0133, rw-r--r--
#endif
bool not_open = (!_configFile->isOpen() && !_configFile->open(QIODevice::ReadWrite | QIODevice::Text));
#ifdef HAVE_UMASK
return true;
}
-
-bool OidentdConfigGenerator::lineByUs(const QByteArray &line)
+bool OidentdConfigGenerator::lineByUs(const QByteArray& line)
{
return _quasselStanzaRx.exactMatch(line);
}
#ifndef OIDENTDCONFIGGENERATOR_H
#define OIDENTDCONFIGGENERATOR_H
-#include <QObject>
-#include <QString>
+#include <QByteArray>
+#include <QDateTime>
#include <QDir>
#include <QFile>
-#include <QDateTime>
#include <QHostAddress>
#include <QMutex>
-#include <QByteArray>
+#include <QObject>
+#include <QString>
-#include "quassel.h"
#include "coreidentity.h"
+#include "quassel.h"
//! Produces oidentd configuration files
/*!
{
Q_OBJECT
public:
- explicit OidentdConfigGenerator(QObject *parent = nullptr);
+ explicit OidentdConfigGenerator(QObject* parent = nullptr);
~OidentdConfigGenerator() override;
public slots:
- bool addSocket(const CoreIdentity *identity, const QHostAddress &localAddress,
- quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort,
+ bool addSocket(const CoreIdentity* identity,
+ const QHostAddress& localAddress,
+ quint16 localPort,
+ const QHostAddress& peerAddress,
+ quint16 peerPort,
qint64 socketId);
- bool removeSocket(const CoreIdentity *identity, const QHostAddress &localAddress,
- quint16 localPort, const QHostAddress &peerAddress, quint16 peerPort,
+ bool removeSocket(const CoreIdentity* identity,
+ const QHostAddress& localAddress,
+ quint16 localPort,
+ const QHostAddress& peerAddress,
+ quint16 peerPort,
qint64 socketId);
private:
- QString sysIdentForIdentity(const CoreIdentity *identity) const;
+ QString sysIdentForIdentity(const CoreIdentity* identity) const;
bool init();
bool writeConfig();
bool parseConfig(bool readQuasselStanzas = false);
- bool lineByUs(const QByteArray &line);
+ bool lineByUs(const QByteArray& line);
bool _initialized{false};
bool _strict;
QDateTime _lastSync;
- QFile *_configFile;
+ QFile* _configFile;
QByteArray _parsedConfig;
QByteArray _quasselConfig;
// Mutex isn't strictly necessary at the moment, since with the current invocation in Core only one instance at a time exists
QString _quasselStanzaTemplate;
};
-
-#endif // OIDENTDCONFIGGENERATOR_H
+#endif // OIDENTDCONFIGGENERATOR_H
#include "network.h"
#include "quassel.h"
-PostgreSqlStorage::PostgreSqlStorage(QObject *parent)
+PostgreSqlStorage::PostgreSqlStorage(QObject* parent)
: AbstractSqlStorage(parent)
-{
-}
-
+{}
std::unique_ptr<AbstractSqlMigrationWriter> PostgreSqlStorage::createMigrationWriter()
{
return std::unique_ptr<AbstractSqlMigrationWriter>{writer};
}
-
bool PostgreSqlStorage::isAvailable() const
{
if (!QSqlDatabase::isDriverAvailable("QPSQL")) {
return true;
}
-
QString PostgreSqlStorage::backendId() const
{
return QString("PostgreSQL");
}
-
QString PostgreSqlStorage::displayName() const
{
- return backendId(); // Note: Pre-0.13 clients use the displayName property for backend idenfication
+ return backendId(); // Note: Pre-0.13 clients use the displayName property for backend idenfication
}
-
QString PostgreSqlStorage::description() const
{
// FIXME: proper description
return tr("PostgreSQL Turbo Bomber HD!");
}
-
QVariantList PostgreSqlStorage::setupData() const
{
QVariantList data;
- data << "Username" << tr("Username") << QString("quassel")
- << "Password" << tr("Password") << QString()
- << "Hostname" << tr("Hostname") << QString("localhost")
- << "Port" << tr("Port") << 5432
- << "Database" << tr("Database") << QString("quassel")
- ;
+ data << "Username" << tr("Username") << QString("quassel") << "Password" << tr("Password") << QString() << "Hostname" << tr("Hostname")
+ << QString("localhost") << "Port" << tr("Port") << 5432 << "Database" << tr("Database") << QString("quassel");
return data;
}
-
-bool PostgreSqlStorage::initDbSession(QSqlDatabase &db)
+bool PostgreSqlStorage::initDbSession(QSqlDatabase& db)
{
// check whether the Qt driver performs string escaping or not.
// i.e. test if it doubles slashes.
testField.setType(QVariant::String);
testField.setValue("\\");
QString formattedString = db.driver()->formatValue(testField);
- switch(formattedString.count('\\')) {
+ switch (formattedString.count('\\')) {
case 2:
// yes it does... and we cannot do anything to change the behavior of Qt.
// If this is a legacy DB (Postgres < 8.2), then everything is already ok,
return true;
}
-
-void PostgreSqlStorage::setConnectionProperties(const QVariantMap &properties,
- const QProcessEnvironment &environment,
- bool loadFromEnvironment)
+void PostgreSqlStorage::setConnectionProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment)
{
if (loadFromEnvironment) {
_userName = environment.value("DB_PGSQL_USERNAME");
_hostName = environment.value("DB_PGSQL_HOSTNAME");
_port = environment.value("DB_PGSQL_PORT").toInt();
_databaseName = environment.value("DB_PGSQL_DATABASE");
- } else {
+ }
+ else {
_userName = properties["Username"].toString();
_password = properties["Password"].toString();
_hostName = properties["Hostname"].toString();
}
}
-
int PostgreSqlStorage::installedSchemaVersion()
{
QSqlQuery query(logDb());
return AbstractSqlStorage::installedSchemaVersion();
}
-
bool PostgreSqlStorage::updateSchemaVersion(int newVersion)
{
QSqlQuery query(logDb());
return success;
}
-
bool PostgreSqlStorage::setupSchemaVersion(int version)
{
QSqlQuery query(logDb());
return success;
}
-
-UserId PostgreSqlStorage::addUser(const QString &user, const QString &password, const QString &authenticator)
+UserId PostgreSqlStorage::addUser(const QString& user, const QString& password, const QString& authenticator)
{
QSqlQuery query(logDb());
query.prepare(queryString("insert_quasseluser"));
return uid;
}
-
-bool PostgreSqlStorage::updateUser(UserId user, const QString &password)
+bool PostgreSqlStorage::updateUser(UserId user, const QString& password)
{
QSqlQuery query(logDb());
query.prepare(queryString("update_userpassword"));
return query.numRowsAffected() != 0;
}
-
-void PostgreSqlStorage::renameUser(UserId user, const QString &newName)
+void PostgreSqlStorage::renameUser(UserId user, const QString& newName)
{
QSqlQuery query(logDb());
query.prepare(queryString("update_username"));
emit userRenamed(user, newName);
}
-
-UserId PostgreSqlStorage::validateUser(const QString &user, const QString &password)
+UserId PostgreSqlStorage::validateUser(const QString& user, const QString& password)
{
QSqlQuery query(logDb());
query.prepare(queryString("select_authuser"));
safeExec(query);
watchQuery(query);
- if (query.first() && checkHashedPassword(query.value(0).toInt(), password, query.value(1).toString(), static_cast<Storage::HashVersion>(query.value(2).toInt()))) {
+ if (query.first()
+ && checkHashedPassword(query.value(0).toInt(),
+ password,
+ query.value(1).toString(),
+ static_cast<Storage::HashVersion>(query.value(2).toInt()))) {
return query.value(0).toInt();
}
else {
}
}
-
-UserId PostgreSqlStorage::getUserId(const QString &user)
+UserId PostgreSqlStorage::getUserId(const QString& user)
{
QSqlQuery query(logDb());
query.prepare(queryString("select_userid"));
}
}
-
void PostgreSqlStorage::delUser(UserId user)
{
QSqlDatabase db = logDb();
}
}
-
-void PostgreSqlStorage::setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
+void PostgreSqlStorage::setUserSetting(UserId userId, const QString& settingName, const QVariant& data)
{
QByteArray rawData;
QDataStream out(&rawData, QIODevice::WriteOnly);
watchQuery(setQuery);
}
-
-QVariant PostgreSqlStorage::getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultData)
+QVariant PostgreSqlStorage::getUserSetting(UserId userId, const QString& settingName, const QVariant& defaultData)
{
QSqlQuery query(logDb());
query.prepare(queryString("select_user_setting"));
}
}
-
-void PostgreSqlStorage::setCoreState(const QVariantList &data)
+void PostgreSqlStorage::setCoreState(const QVariantList& data)
{
QByteArray rawData;
QDataStream out(&rawData, QIODevice::WriteOnly);
watchQuery(setQuery);
}
-
-QVariantList PostgreSqlStorage::getCoreState(const QVariantList &defaultData)
+QVariantList PostgreSqlStorage::getCoreState(const QVariantList& defaultData)
{
QSqlQuery query(logDb());
query.prepare(queryString("select_core_state"));
in.setVersion(QDataStream::Qt_4_2);
in >> data;
return data;
- } else {
+ }
+ else {
return defaultData;
}
}
-
-IdentityId PostgreSqlStorage::createIdentity(UserId user, CoreIdentity &identity)
+IdentityId PostgreSqlStorage::createIdentity(UserId user, CoreIdentity& identity)
{
IdentityId identityId;
QSqlQuery insertNickQuery(db);
insertNickQuery.prepare(queryString("insert_nick"));
- foreach(QString nick, identity.nicks()) {
+ foreach (QString nick, identity.nicks()) {
insertNickQuery.bindValue(":identityid", identityId.toInt());
insertNickQuery.bindValue(":nick", nick);
safeExec(insertNickQuery);
return identityId;
}
-
-bool PostgreSqlStorage::updateIdentity(UserId user, const CoreIdentity &identity)
+bool PostgreSqlStorage::updateIdentity(UserId user, const CoreIdentity& identity)
{
QSqlDatabase db = logDb();
if (!beginTransaction(db)) {
QSqlQuery insertNickQuery(db);
insertNickQuery.prepare(queryString("insert_nick"));
- foreach(QString nick, identity.nicks()) {
+ foreach (QString nick, identity.nicks()) {
insertNickQuery.bindValue(":identityid", identity.id().toInt());
insertNickQuery.bindValue(":nick", nick);
safeExec(insertNickQuery);
return true;
}
-
void PostgreSqlStorage::removeIdentity(UserId user, IdentityId identityId)
{
QSqlDatabase db = logDb();
}
}
-
QList<CoreIdentity> PostgreSqlStorage::identities(UserId user)
{
QList<CoreIdentity> identities;
return identities;
}
-
-NetworkId PostgreSqlStorage::createNetwork(UserId user, const NetworkInfo &info)
+NetworkId PostgreSqlStorage::createNetwork(UserId user, const NetworkInfo& info)
{
NetworkId networkId;
QSqlQuery insertServersQuery(db);
insertServersQuery.prepare(queryString("insert_server"));
- foreach(Network::Server server, info.serverList) {
+ foreach (Network::Server server, info.serverList) {
insertServersQuery.bindValue(":userid", user.toInt());
insertServersQuery.bindValue(":networkid", networkId.toInt());
bindServerInfo(insertServersQuery, server);
return networkId;
}
-
-void PostgreSqlStorage::bindNetworkInfo(QSqlQuery &query, const NetworkInfo &info)
+void PostgreSqlStorage::bindNetworkInfo(QSqlQuery& query, const NetworkInfo& info)
{
query.bindValue(":networkname", info.networkName);
query.bindValue(":identityid", info.identity.isValid() ? info.identity.toInt() : QVariant());
query.bindValue(":networkid", info.networkId.toInt());
}
-
-void PostgreSqlStorage::bindServerInfo(QSqlQuery &query, const Network::Server &server)
+void PostgreSqlStorage::bindServerInfo(QSqlQuery& query, const Network::Server& server)
{
query.bindValue(":hostname", server.host);
query.bindValue(":port", server.port);
query.bindValue(":sslverify", server.sslVerify);
}
-
-bool PostgreSqlStorage::updateNetwork(UserId user, const NetworkInfo &info)
+bool PostgreSqlStorage::updateNetwork(UserId user, const NetworkInfo& info)
{
QSqlDatabase db = logDb();
if (!beginTransaction(db)) {
QSqlQuery insertServersQuery(db);
insertServersQuery.prepare(queryString("insert_server"));
- foreach(Network::Server server, info.serverList) {
+ foreach (Network::Server server, info.serverList) {
insertServersQuery.bindValue(":userid", user.toInt());
insertServersQuery.bindValue(":networkid", info.networkId.toInt());
bindServerInfo(insertServersQuery, server);
return true;
}
-
-bool PostgreSqlStorage::removeNetwork(UserId user, const NetworkId &networkId)
+bool PostgreSqlStorage::removeNetwork(UserId user, const NetworkId& networkId)
{
QSqlDatabase db = logDb();
if (!beginTransaction(db)) {
return true;
}
-
QList<NetworkInfo> PostgreSqlStorage::networks(UserId user)
{
QList<NetworkInfo> nets;
return nets;
}
-
QList<NetworkId> PostgreSqlStorage::connectedNetworks(UserId user)
{
QList<NetworkId> connectedNets;
return connectedNets;
}
-
-void PostgreSqlStorage::setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
+void PostgreSqlStorage::setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected)
{
QSqlQuery query(logDb());
query.prepare(queryString("update_network_connected"));
watchQuery(query);
}
-
-QHash<QString, QString> PostgreSqlStorage::persistentChannels(UserId user, const NetworkId &networkId)
+QHash<QString, QString> PostgreSqlStorage::persistentChannels(UserId user, const NetworkId& networkId)
{
QHash<QString, QString> persistentChans;
return persistentChans;
}
-
-void PostgreSqlStorage::setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
+void PostgreSqlStorage::setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined)
{
QSqlQuery query(logDb());
query.prepare(queryString("update_buffer_persistent_channel"));
watchQuery(query);
}
-
-void PostgreSqlStorage::setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
+void PostgreSqlStorage::setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key)
{
QSqlQuery query(logDb());
query.prepare(queryString("update_buffer_set_channel_key"));
watchQuery(query);
}
-
QString PostgreSqlStorage::awayMessage(UserId user, NetworkId networkId)
{
QSqlQuery query(logDb());
return awayMsg;
}
-
-void PostgreSqlStorage::setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
+void PostgreSqlStorage::setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg)
{
QSqlQuery query(logDb());
query.prepare(queryString("update_network_set_awaymsg"));
watchQuery(query);
}
-
QString PostgreSqlStorage::userModes(UserId user, NetworkId networkId)
{
QSqlQuery query(logDb());
return modes;
}
-
-void PostgreSqlStorage::setUserModes(UserId user, NetworkId networkId, const QString &userModes)
+void PostgreSqlStorage::setUserModes(UserId user, NetworkId networkId, const QString& userModes)
{
QSqlQuery query(logDb());
query.prepare(queryString("update_network_set_usermode"));
watchQuery(query);
}
-
-BufferInfo PostgreSqlStorage::bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer, bool create)
+BufferInfo PostgreSqlStorage::bufferInfo(UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer, bool create)
{
QSqlDatabase db = logDb();
if (!beginTransaction(db)) {
return bufferInfo;
}
-
-BufferInfo PostgreSqlStorage::getBufferInfo(UserId user, const BufferId &bufferId)
+BufferInfo PostgreSqlStorage::getBufferInfo(UserId user, const BufferId& bufferId)
{
QSqlQuery query(logDb());
query.prepare(queryString("select_buffer_by_id"));
if (!query.first())
return {};
- BufferInfo bufferInfo(query.value(0).toInt(), query.value(1).toInt(), (BufferInfo::Type)query.value(2).toInt(), 0, query.value(4).toString());
+ BufferInfo bufferInfo(query.value(0).toInt(),
+ query.value(1).toInt(),
+ (BufferInfo::Type)query.value(2).toInt(),
+ 0,
+ query.value(4).toString());
Q_ASSERT(!query.next());
return bufferInfo;
}
-
QList<BufferInfo> PostgreSqlStorage::requestBuffers(UserId user)
{
QList<BufferInfo> bufferlist;
safeExec(query);
watchQuery(query);
while (query.next()) {
- bufferlist << BufferInfo(query.value(0).toInt(), query.value(1).toInt(), (BufferInfo::Type)query.value(2).toInt(), query.value(3).toInt(), query.value(4).toString());
+ bufferlist << BufferInfo(query.value(0).toInt(),
+ query.value(1).toInt(),
+ (BufferInfo::Type)query.value(2).toInt(),
+ query.value(3).toInt(),
+ query.value(4).toString());
}
db.commit();
return bufferlist;
}
-
QList<BufferId> PostgreSqlStorage::requestBufferIdsForNetwork(UserId user, NetworkId networkId)
{
QList<BufferId> bufferList;
return bufferList;
}
-
-bool PostgreSqlStorage::removeBuffer(const UserId &user, const BufferId &bufferId)
+bool PostgreSqlStorage::removeBuffer(const UserId& user, const BufferId& bufferId)
{
QSqlDatabase db = logDb();
if (!beginTransaction(db)) {
return true;
default:
// there was more then one buffer deleted...
- qWarning() << "PostgreSqlStorage::removeBuffer(): Userid" << user << "BufferId" << "caused deletion of" << numRows << "Buffers! Rolling back transaction...";
+ qWarning() << "PostgreSqlStorage::removeBuffer(): Userid" << user << "BufferId"
+ << "caused deletion of" << numRows << "Buffers! Rolling back transaction...";
db.rollback();
return false;
}
}
-
-bool PostgreSqlStorage::renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
+bool PostgreSqlStorage::renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName)
{
QSqlDatabase db = logDb();
if (!beginTransaction(db)) {
return true;
default:
// there was more then one buffer deleted...
- qWarning() << "PostgreSqlStorage::renameBuffer(): Userid" << user << "BufferId" << "affected" << numRows << "Buffers! Rolling back transaction...";
+ qWarning() << "PostgreSqlStorage::renameBuffer(): Userid" << user << "BufferId"
+ << "affected" << numRows << "Buffers! Rolling back transaction...";
db.rollback();
return false;
}
}
-
-bool PostgreSqlStorage::mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
+bool PostgreSqlStorage::mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2)
{
QSqlDatabase db = logDb();
if (!beginTransaction(db)) {
return true;
}
-
-void PostgreSqlStorage::setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
+void PostgreSqlStorage::setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId)
{
QSqlQuery query(logDb());
query.prepare(queryString("update_buffer_lastseen"));
watchQuery(query);
}
-
QHash<BufferId, MsgId> PostgreSqlStorage::bufferLastSeenMsgIds(UserId user)
{
QHash<BufferId, MsgId> lastSeenHash;
return lastSeenHash;
}
-
-void PostgreSqlStorage::setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
+void PostgreSqlStorage::setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId)
{
QSqlQuery query(logDb());
query.prepare(queryString("update_buffer_markerlinemsgid"));
watchQuery(query);
}
-
QHash<BufferId, MsgId> PostgreSqlStorage::bufferMarkerLineMsgIds(UserId user)
{
QHash<BufferId, MsgId> markerLineHash;
return markerLineHash;
}
-
void PostgreSqlStorage::setBufferActivity(UserId user, BufferId bufferId, Message::Types bufferActivity)
{
QSqlQuery query(logDb());
query.bindValue(":userid", user.toInt());
query.bindValue(":bufferid", bufferId.toInt());
- query.bindValue(":bufferactivity", (int) bufferActivity);
+ query.bindValue(":bufferactivity", (int)bufferActivity);
safeExec(query);
watchQuery(query);
}
return result;
}
-QHash<QString, QByteArray> PostgreSqlStorage::bufferCiphers(UserId user, const NetworkId &networkId)
+QHash<QString, QByteArray> PostgreSqlStorage::bufferCiphers(UserId user, const NetworkId& networkId)
{
QHash<QString, QByteArray> bufferCiphers;
return bufferCiphers;
}
-void PostgreSqlStorage::setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher)
+void PostgreSqlStorage::setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher)
{
QSqlQuery query(logDb());
query.prepare(queryString("update_buffer_cipher"));
watchQuery(query);
}
-
void PostgreSqlStorage::setHighlightCount(UserId user, BufferId bufferId, int highlightcount)
{
QSqlQuery query(logDb());
return result;
}
-bool PostgreSqlStorage::logMessage(Message &msg)
+bool PostgreSqlStorage::logMessage(Message& msg)
{
QSqlDatabase db = logDb();
if (!beginTransaction(db)) {
}
QVariantList senderParams;
- senderParams << msg.sender()
- << msg.realName()
- << msg.avatarUrl();
+ senderParams << msg.sender() << msg.realName() << msg.avatarUrl();
QSqlQuery getSenderIdQuery = executePreparedQuery("select_senderid", senderParams, db);
qint64 senderId;
if (getSenderIdQuery.first()) {
QVariantList params;
// PostgreSQL handles QDateTime()'s serialized format by default, and QDateTime() serializes
// to a 64-bit time compatible format by default.
- params << msg.timestamp()
- << msg.bufferInfo().bufferId().toInt()
- << msg.type()
- << (int)msg.flags()
- << senderId
- << msg.senderPrefixes()
+ params << msg.timestamp() << msg.bufferInfo().bufferId().toInt() << msg.type() << (int)msg.flags() << senderId << msg.senderPrefixes()
<< msg.contents();
QSqlQuery logMessageQuery = executePreparedQuery("insert_message", params, db);
}
}
-
-bool PostgreSqlStorage::logMessages(MessageList &msgs)
+bool PostgreSqlStorage::logMessages(MessageList& msgs)
{
QSqlDatabase db = logDb();
if (!beginTransaction(db)) {
QList<int> senderIdList;
QHash<SenderData, qint64> senderIds;
QSqlQuery addSenderQuery;
- QSqlQuery selectSenderQuery;;
+ QSqlQuery selectSenderQuery;
+ ;
for (int i = 0; i < msgs.count(); i++) {
- auto &msg = msgs.at(i);
- SenderData sender = { msg.sender(), msg.realName(), msg.avatarUrl() };
+ auto& msg = msgs.at(i);
+ SenderData sender = {msg.sender(), msg.realName(), msg.avatarUrl()};
if (senderIds.contains(sender)) {
senderIdList << senderIds[sender];
continue;
}
QVariantList senderParams;
- senderParams << sender.sender
- << sender.realname
- << sender.avatarurl;
+ senderParams << sender.sender << sender.realname << sender.avatarurl;
selectSenderQuery = executePreparedQuery("select_senderid", senderParams, db);
if (selectSenderQuery.first()) {
// yes we loop twice over the same list. This avoids alternating queries.
bool error = false;
for (int i = 0; i < msgs.count(); i++) {
- Message &msg = msgs[i];
+ Message& msg = msgs[i];
QVariantList params;
// PostgreSQL handles QDateTime()'s serialized format by default, and QDateTime() serializes
// to a 64-bit time compatible format by default.
- params << msg.timestamp()
- << msg.bufferInfo().bufferId().toInt()
- << msg.type()
- << (int)msg.flags()
- << senderIdList.at(i)
- << msg.senderPrefixes()
- << msg.contents();
+ params << msg.timestamp() << msg.bufferInfo().bufferId().toInt() << msg.type() << (int)msg.flags() << senderIdList.at(i)
+ << msg.senderPrefixes() << msg.contents();
QSqlQuery logMessageQuery = executePreparedQuery("insert_message", params, db);
if (!watchQuery(logMessageQuery)) {
db.rollback();
return true;
}
-
QList<Message> PostgreSqlStorage::requestMsgs(UserId user, BufferId bufferId, MsgId first, MsgId last, int limit)
{
QList<Message> messagelist;
timestamp = query.value(1).toDateTime();
timestamp.setTimeSpec(Qt::UTC);
Message msg(timestamp,
- bufferInfo,
- (Message::Type)query.value(2).toInt(),
- query.value(8).toString(),
- query.value(4).toString(),
- query.value(5).toString(),
- query.value(6).toString(),
- query.value(7).toString(),
- (Message::Flags)query.value(3).toInt());
+ bufferInfo,
+ (Message::Type)query.value(2).toInt(),
+ query.value(8).toString(),
+ query.value(4).toString(),
+ query.value(5).toString(),
+ query.value(6).toString(),
+ query.value(7).toString(),
+ (Message::Flags)query.value(3).toInt());
msg.setMsgId(query.value(0).toLongLong());
messagelist << msg;
}
return messagelist;
}
-
-QList<Message> PostgreSqlStorage::requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first, MsgId last, int limit, Message::Types type, Message::Flags flags)
+QList<Message> PostgreSqlStorage::requestMsgsFiltered(
+ UserId user, BufferId bufferId, MsgId first, MsgId last, int limit, Message::Types type, Message::Flags flags)
{
QList<Message> messagelist;
QSqlQuery query(db);
if (last == -1 && first == -1) {
query.prepare(queryString("select_messagesNewestK_filtered"));
- } else if (last == -1) {
+ }
+ else if (last == -1) {
query.prepare(queryString("select_messagesNewerThan_filtered"));
query.bindValue(":first", first.toQint64());
- } else {
+ }
+ else {
query.prepare(queryString("select_messagesRange_filtered"));
query.bindValue(":last", last.toQint64());
query.bindValue(":first", first.toQint64());
return messagelist;
}
-
QList<Message> PostgreSqlStorage::requestAllMsgs(UserId user, MsgId first, MsgId last, int limit)
{
QList<Message> messagelist;
// requestBuffers uses it's own transaction.
QHash<BufferId, BufferInfo> bufferInfoHash;
- foreach(BufferInfo bufferInfo, requestBuffers(user)) {
+ foreach (BufferInfo bufferInfo, requestBuffers(user)) {
bufferInfoHash[bufferInfo.bufferId()] = bufferInfo;
}
timestamp = query.value(2).toDateTime();
timestamp.setTimeSpec(Qt::UTC);
Message msg(timestamp,
- bufferInfoHash[query.value(1).toInt()],
- (Message::Type)query.value(3).toInt(),
- query.value(9).toString(),
- query.value(5).toString(),
- query.value(6).toString(),
- query.value(7).toString(),
- query.value(8).toString(),
- (Message::Flags)query.value(4).toInt());
+ bufferInfoHash[query.value(1).toInt()],
+ (Message::Type)query.value(3).toInt(),
+ query.value(9).toString(),
+ query.value(5).toString(),
+ query.value(6).toString(),
+ query.value(7).toString(),
+ query.value(8).toString(),
+ (Message::Flags)query.value(4).toInt());
msg.setMsgId(query.value(0).toLongLong());
messagelist << msg;
}
return messagelist;
}
-
-QList<Message> PostgreSqlStorage::requestAllMsgsFiltered(UserId user, MsgId first, MsgId last, int limit, Message::Types type, Message::Flags flags)
+QList<Message> PostgreSqlStorage::requestAllMsgsFiltered(
+ UserId user, MsgId first, MsgId last, int limit, Message::Types type, Message::Flags flags)
{
QList<Message> messagelist;
// requestBuffers uses it's own transaction.
QHash<BufferId, BufferInfo> bufferInfoHash;
- foreach(BufferInfo bufferInfo, requestBuffers(user)) {
- bufferInfoHash[bufferInfo.bufferId()] = bufferInfo;
- }
+ foreach (BufferInfo bufferInfo, requestBuffers(user)) {
+ bufferInfoHash[bufferInfo.bufferId()] = bufferInfo;
+ }
QSqlDatabase db = logDb();
if (!beginReadOnlyTransaction(db)) {
return authusernames;
}
-
// void PostgreSqlStorage::safeExec(QSqlQuery &query) {
// qDebug() << "PostgreSqlStorage::safeExec";
// qDebug() << " executing:\n" << query.executedQuery();
// return;
// }
-
-bool PostgreSqlStorage::beginTransaction(QSqlDatabase &db)
+bool PostgreSqlStorage::beginTransaction(QSqlDatabase& db)
{
bool result = db.transaction();
if (!db.isOpen()) {
return result;
}
-bool PostgreSqlStorage::beginReadOnlyTransaction(QSqlDatabase &db)
+bool PostgreSqlStorage::beginReadOnlyTransaction(QSqlDatabase& db)
{
QSqlQuery query = db.exec("BEGIN TRANSACTION READ ONLY");
if (!db.isOpen()) {
return !query.lastError().isValid();
}
-
-QSqlQuery PostgreSqlStorage::prepareAndExecuteQuery(const QString &queryname, const QString ¶mstring, QSqlDatabase &db)
+QSqlQuery PostgreSqlStorage::prepareAndExecuteQuery(const QString& queryname, const QString& paramstring, QSqlDatabase& db)
{
// Query preparing is done lazily. That means that instead of always checking if the query is already prepared
// we just EXECUTE and catch the error
if (!db.isOpen()) {
db = logDb();
if (!beginTransaction(db)) {
- qWarning() << "PostgreSqlStorage::prepareAndExecuteQuery(): cannot start transaction while recovering from connection loss!";
+ qWarning()
+ << "PostgreSqlStorage::prepareAndExecuteQuery(): cannot start transaction while recovering from connection loss!";
qWarning() << " -" << qPrintable(db.lastError().text());
return query;
}
db.exec("SAVEPOINT quassel_prepare_query");
- } else {
+ }
+ else {
db.exec("ROLLBACK TO SAVEPOINT quassel_prepare_query");
}
// and once again: Qt leaves us without error codes so we either parse (language dependent(!)) strings
// or we just guess the error. As we're only interested in unprepared queries, this will be our guess. :)
- QSqlQuery checkQuery = db.exec(QString("SELECT count(name) FROM pg_prepared_statements WHERE name = 'quassel_%1' AND from_sql = TRUE").arg(queryname.toLower()));
+ QSqlQuery checkQuery = db.exec(
+ QString("SELECT count(name) FROM pg_prepared_statements WHERE name = 'quassel_%1' AND from_sql = TRUE").arg(queryname.toLower()));
checkQuery.first();
if (checkQuery.value(0).toInt() == 0) {
db.exec(QString("PREPARE quassel_%1 AS %2").arg(queryname).arg(queryString(queryname)));
return query;
}
-
-QSqlQuery PostgreSqlStorage::executePreparedQuery(const QString &queryname, const QVariantList ¶ms, QSqlDatabase &db)
+QSqlQuery PostgreSqlStorage::executePreparedQuery(const QString& queryname, const QVariantList& params, QSqlDatabase& db)
{
- QSqlDriver *driver = db.driver();
+ QSqlDriver* driver = db.driver();
QStringList paramStrings;
QSqlField field;
for (int i = 0; i < params.count(); i++) {
- const QVariant &value = params.at(i);
+ const QVariant& value = params.at(i);
field.setType(value.type());
if (value.isNull())
field.clear();
}
}
-
-QSqlQuery PostgreSqlStorage::executePreparedQuery(const QString &queryname, const QVariant ¶m, QSqlDatabase &db)
+QSqlQuery PostgreSqlStorage::executePreparedQuery(const QString& queryname, const QVariant& param, QSqlDatabase& db)
{
QSqlField field;
field.setType(param.type());
return prepareAndExecuteQuery(queryname, paramString, db);
}
-
-void PostgreSqlStorage::deallocateQuery(const QString &queryname, const QSqlDatabase &db)
+void PostgreSqlStorage::deallocateQuery(const QString& queryname, const QSqlDatabase& db)
{
db.exec(QString("DEALLOCATE quassel_%1").arg(queryname));
}
-
-void PostgreSqlStorage::safeExec(QSqlQuery &query)
+void PostgreSqlStorage::safeExec(QSqlQuery& query)
{
// If the query fails due to the connection being gone, it seems to cause
// exec() to return false but no lastError to be set
- if(!query.exec() && !query.lastError().isValid())
- {
+ if (!query.exec() && !query.lastError().isValid()) {
QSqlDatabase db = logDb();
QSqlQuery retryQuery(db);
retryQuery.prepare(query.lastQuery());
QMapIterator<QString, QVariant> i(query.boundValues());
- while (i.hasNext())
- {
+ while (i.hasNext()) {
i.next();
- retryQuery.bindValue(i.key(),i.value());
+ retryQuery.bindValue(i.key(), i.value());
}
query = retryQuery;
query.exec();
// ========================================
PostgreSqlMigrationWriter::PostgreSqlMigrationWriter()
: PostgreSqlStorage()
-{
-}
-
+{}
bool PostgreSqlMigrationWriter::prepareQuery(MigrationObject mo)
{
return true;
}
-
-//bool PostgreSqlMigrationWriter::writeUser(const QuasselUserMO &user) {
-bool PostgreSqlMigrationWriter::writeMo(const QuasselUserMO &user)
+// bool PostgreSqlMigrationWriter::writeUser(const QuasselUserMO &user) {
+bool PostgreSqlMigrationWriter::writeMo(const QuasselUserMO& user)
{
bindValue(0, user.id.toInt());
bindValue(1, user.username);
return exec();
}
-
-//bool PostgreSqlMigrationWriter::writeSender(const SenderMO &sender) {
-bool PostgreSqlMigrationWriter::writeMo(const SenderMO &sender)
+// bool PostgreSqlMigrationWriter::writeSender(const SenderMO &sender) {
+bool PostgreSqlMigrationWriter::writeMo(const SenderMO& sender)
{
bindValue(0, sender.senderId);
bindValue(1, sender.sender);
return exec();
}
-
-//bool PostgreSqlMigrationWriter::writeIdentity(const IdentityMO &identity) {
-bool PostgreSqlMigrationWriter::writeMo(const IdentityMO &identity)
+// bool PostgreSqlMigrationWriter::writeIdentity(const IdentityMO &identity) {
+bool PostgreSqlMigrationWriter::writeMo(const IdentityMO& identity)
{
_validIdentities << identity.id.toInt();
bindValue(0, identity.id.toInt());
return exec();
}
-
-//bool PostgreSqlMigrationWriter::writeIdentityNick(const IdentityNickMO &identityNick) {
-bool PostgreSqlMigrationWriter::writeMo(const IdentityNickMO &identityNick)
+// bool PostgreSqlMigrationWriter::writeIdentityNick(const IdentityNickMO &identityNick) {
+bool PostgreSqlMigrationWriter::writeMo(const IdentityNickMO& identityNick)
{
bindValue(0, identityNick.nickid);
bindValue(1, identityNick.identityId.toInt());
return exec();
}
-
-//bool PostgreSqlMigrationWriter::writeNetwork(const NetworkMO &network) {
-bool PostgreSqlMigrationWriter::writeMo(const NetworkMO &network)
+// bool PostgreSqlMigrationWriter::writeNetwork(const NetworkMO &network) {
+bool PostgreSqlMigrationWriter::writeMo(const NetworkMO& network)
{
bindValue(0, network.networkid.toInt());
bindValue(1, network.userid.toInt());
return exec();
}
-
-//bool PostgreSqlMigrationWriter::writeBuffer(const BufferMO &buffer) {
-bool PostgreSqlMigrationWriter::writeMo(const BufferMO &buffer)
+// bool PostgreSqlMigrationWriter::writeBuffer(const BufferMO &buffer) {
+bool PostgreSqlMigrationWriter::writeMo(const BufferMO& buffer)
{
bindValue(0, buffer.bufferid.toInt());
bindValue(1, buffer.userid.toInt());
return exec();
}
-
-//bool PostgreSqlMigrationWriter::writeBacklog(const BacklogMO &backlog) {
-bool PostgreSqlMigrationWriter::writeMo(const BacklogMO &backlog)
+// bool PostgreSqlMigrationWriter::writeBacklog(const BacklogMO &backlog) {
+bool PostgreSqlMigrationWriter::writeMo(const BacklogMO& backlog)
{
bindValue(0, backlog.messageid.toQint64());
bindValue(1, backlog.time);
return exec();
}
-
-//bool PostgreSqlMigrationWriter::writeIrcServer(const IrcServerMO &ircserver) {
-bool PostgreSqlMigrationWriter::writeMo(const IrcServerMO &ircserver)
+// bool PostgreSqlMigrationWriter::writeIrcServer(const IrcServerMO &ircserver) {
+bool PostgreSqlMigrationWriter::writeMo(const IrcServerMO& ircserver)
{
bindValue(0, ircserver.serverid);
bindValue(1, ircserver.userid.toInt());
return exec();
}
-
-//bool PostgreSqlMigrationWriter::writeUserSetting(const UserSettingMO &userSetting) {
-bool PostgreSqlMigrationWriter::writeMo(const UserSettingMO &userSetting)
+// bool PostgreSqlMigrationWriter::writeUserSetting(const UserSettingMO &userSetting) {
+bool PostgreSqlMigrationWriter::writeMo(const UserSettingMO& userSetting)
{
bindValue(0, userSetting.userid.toInt());
bindValue(1, userSetting.settingname);
return exec();
}
-bool PostgreSqlMigrationWriter::writeMo(const CoreStateMO &coreState)
+bool PostgreSqlMigrationWriter::writeMo(const CoreStateMO& coreState)
{
bindValue(0, coreState.key);
bindValue(1, coreState.value);
return exec();
}
-
bool PostgreSqlMigrationWriter::postProcess()
{
QSqlDatabase db = logDb();
QList<Sequence> sequences;
- sequences << Sequence("backlog", "messageid")
- << Sequence("buffer", "bufferid")
- << Sequence("identity", "identityid")
- << Sequence("identity_nick", "nickid")
- << Sequence("ircserver", "serverid")
- << Sequence("network", "networkid")
- << Sequence("quasseluser", "userid")
- << Sequence("sender", "senderid");
+ sequences << Sequence("backlog", "messageid") << Sequence("buffer", "bufferid") << Sequence("identity", "identityid")
+ << Sequence("identity_nick", "nickid") << Sequence("ircserver", "serverid") << Sequence("network", "networkid")
+ << Sequence("quasseluser", "userid") << Sequence("sender", "senderid");
QList<Sequence>::const_iterator iter;
for (iter = sequences.constBegin(); iter != sequences.constEnd(); ++iter) {
resetQuery();
#pragma once
-#include "abstractsqlstorage.h"
-
#include <QSqlDatabase>
#include <QSqlQuery>
+#include "abstractsqlstorage.h"
+
class PostgreSqlStorage : public AbstractSqlStorage
{
Q_OBJECT
public:
- PostgreSqlStorage(QObject *parent = nullptr);
+ PostgreSqlStorage(QObject* parent = nullptr);
std::unique_ptr<AbstractSqlMigrationWriter> createMigrationWriter() override;
/* User handling */
- UserId addUser(const QString &user, const QString &password, const QString &authenticator = "Database") override;
- bool updateUser(UserId user, const QString &password) override;
- void renameUser(UserId user, const QString &newName) override;
- UserId validateUser(const QString &user, const QString &password) override;
- UserId getUserId(const QString &username) override;
+ UserId addUser(const QString& user, const QString& password, const QString& authenticator = "Database") override;
+ bool updateUser(UserId user, const QString& password) override;
+ void renameUser(UserId user, const QString& newName) override;
+ UserId validateUser(const QString& user, const QString& password) override;
+ UserId getUserId(const QString& username) override;
QString getUserAuthenticator(const UserId userid) override;
UserId internalUser() override;
void delUser(UserId user) override;
- void setUserSetting(UserId userId, const QString &settingName, const QVariant &data) override;
- QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultData = QVariant()) override;
- void setCoreState(const QVariantList &data) override;
- QVariantList getCoreState(const QVariantList &data) override;
+ void setUserSetting(UserId userId, const QString& settingName, const QVariant& data) override;
+ QVariant getUserSetting(UserId userId, const QString& settingName, const QVariant& defaultData = QVariant()) override;
+ void setCoreState(const QVariantList& data) override;
+ QVariantList getCoreState(const QVariantList& data) override;
/* Identity handling */
- IdentityId createIdentity(UserId user, CoreIdentity &identity) override;
- bool updateIdentity(UserId user, const CoreIdentity &identity) override;
+ IdentityId createIdentity(UserId user, CoreIdentity& identity) override;
+ bool updateIdentity(UserId user, const CoreIdentity& identity) override;
void removeIdentity(UserId user, IdentityId identityId) override;
QList<CoreIdentity> identities(UserId user) override;
/* Network handling */
- NetworkId createNetwork(UserId user, const NetworkInfo &info) override;
- bool updateNetwork(UserId user, const NetworkInfo &info) override;
- bool removeNetwork(UserId user, const NetworkId &networkId) override;
+ NetworkId createNetwork(UserId user, const NetworkInfo& info) override;
+ bool updateNetwork(UserId user, const NetworkInfo& info) override;
+ bool removeNetwork(UserId user, const NetworkId& networkId) override;
QList<NetworkInfo> networks(UserId user) override;
QList<NetworkId> connectedNetworks(UserId user) override;
- void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) override;
+ void setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected) override;
/* persistent channels */
- QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId) override;
- void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) override;
- void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) override;
+ QHash<QString, QString> persistentChannels(UserId user, const NetworkId& networkId) override;
+ void setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined) override;
+ void setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key) override;
/* persistent user states */
QString awayMessage(UserId user, NetworkId networkId) override;
- void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg) override;
+ void setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg) override;
QString userModes(UserId user, NetworkId networkId) override;
- void setUserModes(UserId user, NetworkId networkId, const QString &userModes) override;
+ void setUserModes(UserId user, NetworkId networkId, const QString& userModes) override;
/* Buffer handling */
- BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true) override;
- BufferInfo getBufferInfo(UserId user, const BufferId &bufferId) override;
+ BufferInfo bufferInfo(UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer = "", bool create = true) override;
+ BufferInfo getBufferInfo(UserId user, const BufferId& bufferId) override;
QList<BufferInfo> requestBuffers(UserId user) override;
QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId) override;
- bool removeBuffer(const UserId &user, const BufferId &bufferId) override;
- bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName) override;
- bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2) override;
- void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) override;
+ bool removeBuffer(const UserId& user, const BufferId& bufferId) override;
+ bool renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName) override;
+ bool mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2) override;
+ void setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) override;
QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user) override;
- void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) override;
+ void setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) override;
QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user) override;
void setBufferActivity(UserId id, BufferId bufferId, Message::Types type) override;
QHash<BufferId, Message::Types> bufferActivities(UserId id) override;
void setHighlightCount(UserId id, BufferId bufferId, int count) override;
QHash<BufferId, int> highlightCounts(UserId id) override;
int highlightCount(BufferId bufferId, MsgId lastSeenMsgId) override;
- QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId &networkId) override;
- void setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher) override;
+ QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId& networkId) override;
+ void setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher) override;
/* Message handling */
- bool logMessage(Message &msg) override;
- bool logMessages(MessageList &msgs) override;
+ bool logMessage(Message& msg) override;
+ bool logMessages(MessageList& msgs) override;
QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1) override;
- QList<Message> requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1,
- int limit = -1, Message::Types type = Message::Types{-1},
+ QList<Message> requestMsgsFiltered(UserId user,
+ BufferId bufferId,
+ MsgId first = -1,
+ MsgId last = -1,
+ int limit = -1,
+ Message::Types type = Message::Types{-1},
Message::Flags flags = Message::Flags{-1}) override;
QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1) override;
- QList<Message> requestAllMsgsFiltered(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1,
+ QList<Message> requestAllMsgsFiltered(UserId user,
+ MsgId first = -1,
+ MsgId last = -1,
+ int limit = -1,
Message::Types type = Message::Types{-1},
Message::Flags flags = Message::Flags{-1}) override;
QMap<UserId, QString> getAllAuthUserNames() override;
protected:
- bool initDbSession(QSqlDatabase &db) override;
- void setConnectionProperties(const QVariantMap &properties,
- const QProcessEnvironment &environment,
- bool loadFromEnvironment) override;
- QString driverName() override { return "QPSQL"; }
- QString hostName() override { return _hostName; }
- int port() override { return _port; }
- QString databaseName() override { return _databaseName; }
- QString userName() override { return _userName; }
- QString password() override { return _password; }
+ bool initDbSession(QSqlDatabase& db) override;
+ void setConnectionProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment) override;
+ QString driverName() override { return "QPSQL"; }
+ QString hostName() override { return _hostName; }
+ int port() override { return _port; }
+ QString databaseName() override { return _databaseName; }
+ QString userName() override { return _userName; }
+ QString password() override { return _password; }
int installedSchemaVersion() override;
bool updateSchemaVersion(int newVersion) override;
bool setupSchemaVersion(int version) override;
- void safeExec(QSqlQuery &query);
+ void safeExec(QSqlQuery& query);
- bool beginTransaction(QSqlDatabase &db);
- bool beginReadOnlyTransaction(QSqlDatabase &db);
+ bool beginTransaction(QSqlDatabase& db);
+ bool beginReadOnlyTransaction(QSqlDatabase& db);
- QSqlQuery executePreparedQuery(const QString &queryname, const QVariantList ¶ms, QSqlDatabase &db);
- QSqlQuery executePreparedQuery(const QString &queryname, const QVariant ¶m, QSqlDatabase &db);
- void deallocateQuery(const QString &queryname, const QSqlDatabase &db);
+ QSqlQuery executePreparedQuery(const QString& queryname, const QVariantList& params, QSqlDatabase& db);
+ QSqlQuery executePreparedQuery(const QString& queryname, const QVariant& param, QSqlDatabase& db);
+ void deallocateQuery(const QString& queryname, const QSqlDatabase& db);
- void savePoint(const QString &handle, const QSqlDatabase &db) { db.exec(QString("SAVEPOINT %1").arg(handle)); }
- void rollbackSavePoint(const QString &handle, const QSqlDatabase &db) { db.exec(QString("ROLLBACK TO SAVEPOINT %1").arg(handle)); }
- void releaseSavePoint(const QString &handle, const QSqlDatabase &db) { db.exec(QString("RELEASE SAVEPOINT %1").arg(handle)); }
+ void savePoint(const QString& handle, const QSqlDatabase& db) { db.exec(QString("SAVEPOINT %1").arg(handle)); }
+ void rollbackSavePoint(const QString& handle, const QSqlDatabase& db) { db.exec(QString("ROLLBACK TO SAVEPOINT %1").arg(handle)); }
+ void releaseSavePoint(const QString& handle, const QSqlDatabase& db) { db.exec(QString("RELEASE SAVEPOINT %1").arg(handle)); }
private:
- void bindNetworkInfo(QSqlQuery &query, const NetworkInfo &info);
- void bindServerInfo(QSqlQuery &query, const Network::Server &server);
- QSqlQuery prepareAndExecuteQuery(const QString &queryname, const QString ¶mstring, QSqlDatabase &db);
- QSqlQuery prepareAndExecuteQuery(const QString &queryname, QSqlDatabase &db) { return prepareAndExecuteQuery(queryname, QString(), db); }
+ void bindNetworkInfo(QSqlQuery& query, const NetworkInfo& info);
+ void bindServerInfo(QSqlQuery& query, const Network::Server& server);
+ QSqlQuery prepareAndExecuteQuery(const QString& queryname, const QString& paramstring, QSqlDatabase& db);
+ QSqlQuery prepareAndExecuteQuery(const QString& queryname, QSqlDatabase& db)
+ {
+ return prepareAndExecuteQuery(queryname, QString(), db);
+ }
QString _hostName;
int _port{-1};
QString _password;
};
-
// ========================================
// PostgreSqlMigration
// ========================================
public:
PostgreSqlMigrationWriter();
- bool writeMo(const QuasselUserMO &user) override;
- bool writeMo(const SenderMO &sender) override;
- bool writeMo(const IdentityMO &identity) override;
- bool writeMo(const IdentityNickMO &identityNick) override;
- bool writeMo(const NetworkMO &network) override;
- bool writeMo(const BufferMO &buffer) override;
- bool writeMo(const BacklogMO &backlog) override;
- bool writeMo(const IrcServerMO &ircserver) override;
- bool writeMo(const UserSettingMO &userSetting) override;
- bool writeMo(const CoreStateMO &coreState) override;
+ bool writeMo(const QuasselUserMO& user) override;
+ bool writeMo(const SenderMO& sender) override;
+ bool writeMo(const IdentityMO& identity) override;
+ bool writeMo(const IdentityNickMO& identityNick) override;
+ bool writeMo(const NetworkMO& network) override;
+ bool writeMo(const BufferMO& buffer) override;
+ bool writeMo(const BacklogMO& backlog) override;
+ bool writeMo(const IrcServerMO& ircserver) override;
+ bool writeMo(const UserSettingMO& userSetting) override;
+ bool writeMo(const CoreStateMO& coreState) override;
bool prepareQuery(MigrationObject mo) override;
bool postProcess() override;
protected:
- inline bool transaction() override { return logDb().transaction(); }
- inline void rollback() override { logDb().rollback(); }
- inline bool commit() override { return logDb().commit(); }
+ inline bool transaction() override { return logDb().transaction(); }
+ inline void rollback() override { logDb().rollback(); }
+ inline bool commit() override { return logDb().commit(); }
private:
// helper struct
- struct Sequence {
+ struct Sequence
+ {
QLatin1String table;
QLatin1String field;
- Sequence(const char *table, const char *field) : table(table), field(field) {}
+ Sequence(const char* table, const char* field)
+ : table(table)
+ , field(field)
+ {}
};
QSet<int> _validIdentities;
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "sessionthread.h"
+
#include <QPointer>
#include <QTimer>
#include "coresession.h"
#include "internalpeer.h"
#include "remotepeer.h"
-#include "sessionthread.h"
#include "signalproxy.h"
namespace {
: _userId{userId}
, _restoreState{restoreState}
, _strictIdentEnabled{strictIdentEnabled}
- {
- }
+ {}
public slots:
void initialize()
}
}
- void addClient(Peer *peer)
+ void addClient(Peer* peer)
{
if (!_session) {
qWarning() << "Session not initialized!";
QPointer<CoreSession> _session;
};
-} // anon
+} // namespace
-SessionThread::SessionThread(UserId uid, bool restoreState, bool strictIdentEnabled, QObject *parent)
+SessionThread::SessionThread(UserId uid, bool restoreState, bool strictIdentEnabled, QObject* parent)
: QObject(parent)
{
auto worker = new Worker(uid, restoreState, strictIdentEnabled);
QTimer::singleShot(0, &_sessionThread, SLOT(start()));
}
-
SessionThread::~SessionThread()
{
// shut down thread gracefully
_sessionThread.wait(30000);
}
-
void SessionThread::shutdown()
{
emit shutdownSession();
}
-
void SessionThread::onSessionInitialized()
{
_sessionInitialized = true;
- for (auto &&peer : _clientQueue) {
+ for (auto&& peer : _clientQueue) {
peer->setParent(nullptr);
peer->moveToThread(&_sessionThread);
emit addClientToWorker(peer);
_clientQueue.clear();
}
-
void SessionThread::onSessionDestroyed()
{
emit shutdownComplete(this);
}
-void SessionThread::addClient(Peer *peer)
+void SessionThread::addClient(Peer* peer)
{
if (_sessionInitialized) {
peer->setParent(nullptr);
Q_OBJECT
public:
- SessionThread(UserId user, bool restoreState, bool strictIdentEnabled, QObject *parent = nullptr);
+ SessionThread(UserId user, bool restoreState, bool strictIdentEnabled, QObject* parent = nullptr);
~SessionThread() override;
public slots:
- void addClient(Peer *peer);
+ void addClient(Peer* peer);
void shutdown();
private slots:
signals:
void initialized();
void shutdownSession();
- void shutdownComplete(SessionThread *);
+ void shutdownComplete(SessionThread*);
- void addClientToWorker(Peer *peer);
+ void addClientToWorker(Peer* peer);
private:
QThread _sessionThread;
bool _sessionInitialized{false};
- std::vector<Peer *> _clientQueue;
+ std::vector<Peer*> _clientQueue;
};
#include "sqlauthenticator.h"
+#include "core.h"
#include "logmessage.h"
#include "network.h"
#include "quassel.h"
-#include "core.h"
-
-SqlAuthenticator::SqlAuthenticator(QObject *parent)
+SqlAuthenticator::SqlAuthenticator(QObject* parent)
: Authenticator(parent)
-{
-}
-
+{}
bool SqlAuthenticator::isAvailable() const
{
return true;
}
-
QString SqlAuthenticator::backendId() const
{
// We identify the backend to use for the monolithic core by this identifier.
return QString("Database");
}
-
QString SqlAuthenticator::displayName() const
{
return tr("Database");
}
-
QString SqlAuthenticator::description() const
{
return tr("Do not authenticate against any remote service, but instead save a hashed and salted password "
"in the database selected in the next step.");
}
-
-UserId SqlAuthenticator::validateUser(const QString &user, const QString &password)
+UserId SqlAuthenticator::validateUser(const QString& user, const QString& password)
{
return Core::validateUser(user, password);
}
-
-bool SqlAuthenticator::setup(const QVariantMap &settings, const QProcessEnvironment &environment,
- bool loadFromEnvironment)
+bool SqlAuthenticator::setup(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment)
{
Q_UNUSED(settings)
Q_UNUSED(environment)
return true;
}
-
-Authenticator::State SqlAuthenticator::init(const QVariantMap &settings,
- const QProcessEnvironment &environment,
- bool loadFromEnvironment)
+Authenticator::State SqlAuthenticator::init(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment)
{
Q_UNUSED(settings)
Q_UNUSED(environment)
Q_OBJECT
public:
- SqlAuthenticator(QObject *parent = nullptr);
+ SqlAuthenticator(QObject* parent = nullptr);
public slots:
/* General */
inline bool canChangePassword() const override { return true; }
- bool setup(const QVariantMap &settings, const QProcessEnvironment &environment,
- bool loadFromEnvironment) override;
- State init(const QVariantMap &settings, const QProcessEnvironment &environment,
- bool loadFromEnvironment) override;
- UserId validateUser(const QString &user, const QString &password) override;
+ bool setup(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) override;
+ State init(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment) override;
+ UserId validateUser(const QString& user, const QString& password) override;
/* User handling */
- //virtual UserId getUserId(const QString &username);
+ // virtual UserId getUserId(const QString &username);
};
int SqliteStorage::_maxRetryCount = 150;
-SqliteStorage::SqliteStorage(QObject *parent)
+SqliteStorage::SqliteStorage(QObject* parent)
: AbstractSqlStorage(parent)
-{
-}
-
+{}
bool SqliteStorage::isAvailable() const
{
- if (!QSqlDatabase::isDriverAvailable("QSQLITE")) return false;
+ if (!QSqlDatabase::isDriverAvailable("QSQLITE"))
+ return false;
return true;
}
-
QString SqliteStorage::backendId() const
{
return QString("SQLite");
}
-
QString SqliteStorage::displayName() const
{
// Note: Pre-0.13 clients use the displayName property for backend idenfication
return backendId();
}
-
QString SqliteStorage::description() const
{
return tr("SQLite is a file-based database engine that does not require any setup. It is suitable for small and medium-sized "
"it is running on, and if you only expect a few users to use your core.");
}
-
int SqliteStorage::installedSchemaVersion()
{
// only used when there is a singlethread (during startup)
return AbstractSqlStorage::installedSchemaVersion();
}
-
bool SqliteStorage::updateSchemaVersion(int newVersion)
{
// only used when there is a singlethread (during startup)
return success;
}
-
bool SqliteStorage::setupSchemaVersion(int version)
{
// only used when there is a singlethread (during startup)
return success;
}
-
-UserId SqliteStorage::addUser(const QString &user, const QString &password, const QString &authenticator)
+UserId SqliteStorage::addUser(const QString& user, const QString& password, const QString& authenticator)
{
QSqlDatabase db = logDb();
UserId uid;
query.bindValue(":authenticator", authenticator);
lockForWrite();
safeExec(query);
- if (query.lastError().isValid() && query.lastError().number() == 19) { // user already exists - sadly 19 seems to be the general constraint violation error...
+ if (query.lastError().isValid()
+ && query.lastError().number() == 19) { // user already exists - sadly 19 seems to be the general constraint violation error...
db.rollback();
}
else {
return uid;
}
-
-bool SqliteStorage::updateUser(UserId user, const QString &password)
+bool SqliteStorage::updateUser(UserId user, const QString& password)
{
QSqlDatabase db = logDb();
bool success = false;
return success;
}
-
-void SqliteStorage::renameUser(UserId user, const QString &newName)
+void SqliteStorage::renameUser(UserId user, const QString& newName)
{
QSqlDatabase db = logDb();
db.transaction();
emit userRenamed(user, newName);
}
-
-UserId SqliteStorage::validateUser(const QString &user, const QString &password)
+UserId SqliteStorage::validateUser(const QString& user, const QString& password)
{
UserId userId;
QString hashedPassword;
return returnUserId;
}
-
-UserId SqliteStorage::getUserId(const QString &username)
+UserId SqliteStorage::getUserId(const QString& username)
{
UserId userId;
return userId;
}
-
void SqliteStorage::delUser(UserId user)
{
QSqlDatabase db = logDb();
emit userRemoved(user);
}
-
-void SqliteStorage::setUserSetting(UserId userId, const QString &settingName, const QVariant &data)
+void SqliteStorage::setUserSetting(UserId userId, const QString& settingName, const QVariant& data)
{
QByteArray rawData;
QDataStream out(&rawData, QIODevice::WriteOnly);
unlock();
}
-
-QVariant SqliteStorage::getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultData)
+QVariant SqliteStorage::getUserSetting(UserId userId, const QString& settingName, const QVariant& defaultData)
{
QVariant data = defaultData;
{
return data;
}
-
-void SqliteStorage::setCoreState(const QVariantList &data)
+void SqliteStorage::setCoreState(const QVariantList& data)
{
QByteArray rawData;
QDataStream out(&rawData, QIODevice::WriteOnly);
unlock();
}
-
-QVariantList SqliteStorage::getCoreState(const QVariantList &defaultData)
+QVariantList SqliteStorage::getCoreState(const QVariantList& defaultData)
{
QVariantList data;
{
QDataStream in(&rawData, QIODevice::ReadOnly);
in.setVersion(QDataStream::Qt_4_2);
in >> data;
- } else {
+ }
+ else {
data = defaultData;
}
}
return data;
}
-
-IdentityId SqliteStorage::createIdentity(UserId user, CoreIdentity &identity)
+IdentityId SqliteStorage::createIdentity(UserId user, CoreIdentity& identity)
{
IdentityId identityId;
QSqlQuery insertNickQuery(db);
insertNickQuery.prepare(queryString("insert_nick"));
- foreach(QString nick, identity.nicks()) {
+ foreach (QString nick, identity.nicks()) {
insertNickQuery.bindValue(":identityid", identityId.toInt());
insertNickQuery.bindValue(":nick", nick);
safeExec(insertNickQuery);
return identityId;
}
-
-bool SqliteStorage::updateIdentity(UserId user, const CoreIdentity &identity)
+bool SqliteStorage::updateIdentity(UserId user, const CoreIdentity& identity)
{
QSqlDatabase db = logDb();
bool error = false;
QSqlQuery insertNickQuery(db);
insertNickQuery.prepare(queryString("insert_nick"));
- foreach(QString nick, identity.nicks()) {
+ foreach (QString nick, identity.nicks()) {
insertNickQuery.bindValue(":identityid", identity.id().toInt());
insertNickQuery.bindValue(":nick", nick);
safeExec(insertNickQuery);
return true;
}
-
void SqliteStorage::removeIdentity(UserId user, IdentityId identityId)
{
QSqlDatabase db = logDb();
unlock();
}
-
QList<CoreIdentity> SqliteStorage::identities(UserId user)
{
QList<CoreIdentity> identities;
return identities;
}
-
-NetworkId SqliteStorage::createNetwork(UserId user, const NetworkInfo &info)
+NetworkId SqliteStorage::createNetwork(UserId user, const NetworkInfo& info)
{
NetworkId networkId;
{
QSqlQuery insertServersQuery(db);
insertServersQuery.prepare(queryString("insert_server"));
- foreach(Network::Server server, info.serverList) {
+ foreach (Network::Server server, info.serverList) {
insertServersQuery.bindValue(":userid", user.toInt());
insertServersQuery.bindValue(":networkid", networkId.toInt());
bindServerInfo(insertServersQuery, server);
return networkId;
}
-
-void SqliteStorage::bindNetworkInfo(QSqlQuery &query, const NetworkInfo &info)
+void SqliteStorage::bindNetworkInfo(QSqlQuery& query, const NetworkInfo& info)
{
query.bindValue(":networkname", info.networkName);
query.bindValue(":identityid", info.identity.toInt());
query.bindValue(":networkid", info.networkId.toInt());
}
-
-void SqliteStorage::bindServerInfo(QSqlQuery &query, const Network::Server &server)
+void SqliteStorage::bindServerInfo(QSqlQuery& query, const Network::Server& server)
{
query.bindValue(":hostname", server.host);
query.bindValue(":port", server.port);
query.bindValue(":sslverify", server.sslVerify ? 1 : 0);
}
-
-bool SqliteStorage::updateNetwork(UserId user, const NetworkInfo &info)
+bool SqliteStorage::updateNetwork(UserId user, const NetworkInfo& info)
{
QSqlDatabase db = logDb();
bool error = false;
{
QSqlQuery insertServersQuery(db);
insertServersQuery.prepare(queryString("insert_server"));
- foreach(Network::Server server, info.serverList) {
+ foreach (Network::Server server, info.serverList) {
insertServersQuery.bindValue(":userid", user.toInt());
insertServersQuery.bindValue(":networkid", info.networkId.toInt());
bindServerInfo(insertServersQuery, server);
return !error;
}
-
-bool SqliteStorage::removeNetwork(UserId user, const NetworkId &networkId)
+bool SqliteStorage::removeNetwork(UserId user, const NetworkId& networkId)
{
QSqlDatabase db = logDb();
bool error = false;
return true;
}
-
QList<NetworkInfo> SqliteStorage::networks(UserId user)
{
QList<NetworkInfo> nets;
return nets;
}
-
QList<NetworkId> SqliteStorage::connectedNetworks(UserId user)
{
QList<NetworkId> connectedNets;
return connectedNets;
}
-
-void SqliteStorage::setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected)
+void SqliteStorage::setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected)
{
QSqlDatabase db = logDb();
db.transaction();
unlock();
}
-
-QHash<QString, QString> SqliteStorage::persistentChannels(UserId user, const NetworkId &networkId)
+QHash<QString, QString> SqliteStorage::persistentChannels(UserId user, const NetworkId& networkId)
{
QHash<QString, QString> persistentChans;
return persistentChans;
}
-
-void SqliteStorage::setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined)
+void SqliteStorage::setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined)
{
QSqlDatabase db = logDb();
db.transaction();
unlock();
}
-
-void SqliteStorage::setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key)
+void SqliteStorage::setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key)
{
QSqlDatabase db = logDb();
db.transaction();
unlock();
}
-
QString SqliteStorage::awayMessage(UserId user, NetworkId networkId)
{
QSqlDatabase db = logDb();
return awayMsg;
}
-
-void SqliteStorage::setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg)
+void SqliteStorage::setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg)
{
QSqlDatabase db = logDb();
db.transaction();
unlock();
}
-
QString SqliteStorage::userModes(UserId user, NetworkId networkId)
{
QSqlDatabase db = logDb();
return modes;
}
-
-void SqliteStorage::setUserModes(UserId user, NetworkId networkId, const QString &userModes)
+void SqliteStorage::setUserModes(UserId user, NetworkId networkId, const QString& userModes)
{
QSqlDatabase db = logDb();
db.transaction();
unlock();
}
-
-BufferInfo SqliteStorage::bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer, bool create)
+BufferInfo SqliteStorage::bufferInfo(UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer, bool create)
{
QSqlDatabase db = logDb();
db.transaction();
return bufferInfo;
}
-
-BufferInfo SqliteStorage::getBufferInfo(UserId user, const BufferId &bufferId)
+BufferInfo SqliteStorage::getBufferInfo(UserId user, const BufferId& bufferId)
{
QSqlDatabase db = logDb();
db.transaction();
safeExec(query);
if (watchQuery(query) && query.first()) {
- bufferInfo = BufferInfo(query.value(0).toInt(), query.value(1).toInt(), (BufferInfo::Type)query.value(2).toInt(), 0, query.value(4).toString());
+ bufferInfo = BufferInfo(query.value(0).toInt(),
+ query.value(1).toInt(),
+ (BufferInfo::Type)query.value(2).toInt(),
+ 0,
+ query.value(4).toString());
Q_ASSERT(!query.next());
}
db.commit();
return bufferInfo;
}
-
QList<BufferInfo> SqliteStorage::requestBuffers(UserId user)
{
QList<BufferInfo> bufferlist;
safeExec(query);
watchQuery(query);
while (query.next()) {
- bufferlist << BufferInfo(query.value(0).toInt(), query.value(1).toInt(), (BufferInfo::Type)query.value(2).toInt(), query.value(3).toInt(), query.value(4).toString());
+ bufferlist << BufferInfo(query.value(0).toInt(),
+ query.value(1).toInt(),
+ (BufferInfo::Type)query.value(2).toInt(),
+ query.value(3).toInt(),
+ query.value(4).toString());
}
db.commit();
}
return bufferlist;
}
-
QList<BufferId> SqliteStorage::requestBufferIdsForNetwork(UserId user, NetworkId networkId)
{
QList<BufferId> bufferList;
return bufferList;
}
-
-bool SqliteStorage::removeBuffer(const UserId &user, const BufferId &bufferId)
+bool SqliteStorage::removeBuffer(const UserId& user, const BufferId& bufferId)
{
QSqlDatabase db = logDb();
db.transaction();
return !error;
}
-
-bool SqliteStorage::renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName)
+bool SqliteStorage::renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName)
{
QSqlDatabase db = logDb();
db.transaction();
return !error;
}
-
-bool SqliteStorage::mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2)
+bool SqliteStorage::mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2)
{
QSqlDatabase db = logDb();
db.transaction();
return !error;
}
-
-void SqliteStorage::setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
+void SqliteStorage::setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId)
{
QSqlDatabase db = logDb();
db.transaction();
unlock();
}
-
QHash<BufferId, MsgId> SqliteStorage::bufferLastSeenMsgIds(UserId user)
{
QHash<BufferId, MsgId> lastSeenHash;
return lastSeenHash;
}
-
-void SqliteStorage::setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId)
+void SqliteStorage::setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId)
{
QSqlDatabase db = logDb();
db.transaction();
unlock();
}
-
QHash<BufferId, MsgId> SqliteStorage::bufferMarkerLineMsgIds(UserId user)
{
QHash<BufferId, MsgId> markerLineHash;
query.prepare(queryString("update_buffer_bufferactivity"));
query.bindValue(":userid", user.toInt());
query.bindValue(":bufferid", bufferId.toInt());
- query.bindValue(":bufferactivity", (int) bufferActivity);
+ query.bindValue(":bufferactivity", (int)bufferActivity);
lockForWrite();
safeExec(query);
unlock();
}
-
QHash<BufferId, Message::Types> SqliteStorage::bufferActivities(UserId user)
{
QHash<BufferId, Message::Types> bufferActivityHash;
return bufferActivityHash;
}
-
Message::Types SqliteStorage::bufferActivity(BufferId bufferId, MsgId lastSeenMsgId)
{
QSqlDatabase db = logDb();
return result;
}
-QHash<QString, QByteArray> SqliteStorage::bufferCiphers(UserId user, const NetworkId &networkId)
+QHash<QString, QByteArray> SqliteStorage::bufferCiphers(UserId user, const NetworkId& networkId)
{
QHash<QString, QByteArray> bufferCiphers;
return bufferCiphers;
}
-void SqliteStorage::setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher)
+void SqliteStorage::setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher)
{
QSqlDatabase db = logDb();
db.transaction();
unlock();
}
-
QHash<BufferId, int> SqliteStorage::highlightCounts(UserId user)
{
QHash<BufferId, int> highlightCountHash;
return highlightCountHash;
}
-
int SqliteStorage::highlightCount(BufferId bufferId, MsgId lastSeenMsgId)
{
QSqlDatabase db = logDb();
return result;
}
-bool SqliteStorage::logMessage(Message &msg)
+bool SqliteStorage::logMessage(Message& msg)
{
QSqlDatabase db = logDb();
db.transaction();
return !error;
}
-
-bool SqliteStorage::logMessages(MessageList &msgs)
+bool SqliteStorage::logMessages(MessageList& msgs)
{
QSqlDatabase db = logDb();
db.transaction();
addSenderQuery.prepare(queryString("insert_sender"));
lockForWrite();
for (int i = 0; i < msgs.count(); i++) {
- auto &msg = msgs.at(i);
- SenderData sender = { msg.sender(), msg.realName(), msg.avatarUrl() };
+ auto& msg = msgs.at(i);
+ SenderData sender = {msg.sender(), msg.realName(), msg.avatarUrl()};
if (senders.contains(sender))
continue;
senders << sender;
QSqlQuery logMessageQuery(db);
logMessageQuery.prepare(queryString("insert_message"));
for (int i = 0; i < msgs.count(); i++) {
- Message &msg = msgs[i];
+ Message& msg = msgs[i];
// As of SQLite schema version 31, timestamps are stored in milliseconds instead of
// seconds. This nets us more precision as well as simplifying 64-bit time.
logMessageQuery.bindValue(":time", msg.timestamp().toMSecsSinceEpoch());
return !error;
}
-
QList<Message> SqliteStorage::requestMsgs(UserId user, BufferId bufferId, MsgId first, MsgId last, int limit)
{
QList<Message> messagelist;
safeExec(bufferInfoQuery);
error = !watchQuery(bufferInfoQuery) || !bufferInfoQuery.first();
if (!error) {
- bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(), bufferInfoQuery.value(1).toInt(), (BufferInfo::Type)bufferInfoQuery.value(2).toInt(), 0, bufferInfoQuery.value(4).toString());
+ bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(),
+ bufferInfoQuery.value(1).toInt(),
+ (BufferInfo::Type)bufferInfoQuery.value(2).toInt(),
+ 0,
+ bufferInfoQuery.value(4).toString());
error = !bufferInfo.isValid();
}
}
return messagelist;
}
-
-QList<Message> SqliteStorage::requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first, MsgId last, int limit, Message::Types type, Message::Flags flags)
+QList<Message> SqliteStorage::requestMsgsFiltered(
+ UserId user, BufferId bufferId, MsgId first, MsgId last, int limit, Message::Types type, Message::Flags flags)
{
QList<Message> messagelist;
safeExec(bufferInfoQuery);
error = !watchQuery(bufferInfoQuery) || !bufferInfoQuery.first();
if (!error) {
- bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(), bufferInfoQuery.value(1).toInt(), (BufferInfo::Type)bufferInfoQuery.value(2).toInt(), 0, bufferInfoQuery.value(4).toString());
+ bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(),
+ bufferInfoQuery.value(1).toInt(),
+ (BufferInfo::Type)bufferInfoQuery.value(2).toInt(),
+ 0,
+ bufferInfoQuery.value(4).toString());
error = !bufferInfo.isValid();
}
}
while (query.next()) {
Message msg(
- // As of SQLite schema version 31, timestamps are stored in milliseconds
- // instead of seconds. This nets us more precision as well as simplifying
- // 64-bit time.
- QDateTime::fromMSecsSinceEpoch(query.value(1).toLongLong()),
- bufferInfo,
- (Message::Type)query.value(2).toInt(),
- query.value(8).toString(),
- query.value(4).toString(),
- query.value(5).toString(),
- query.value(6).toString(),
- query.value(7).toString(),
- Message::Flags{query.value(3).toInt()});
+ // As of SQLite schema version 31, timestamps are stored in milliseconds
+ // instead of seconds. This nets us more precision as well as simplifying
+ // 64-bit time.
+ QDateTime::fromMSecsSinceEpoch(query.value(1).toLongLong()),
+ bufferInfo,
+ (Message::Type)query.value(2).toInt(),
+ query.value(8).toString(),
+ query.value(4).toString(),
+ query.value(5).toString(),
+ query.value(6).toString(),
+ query.value(7).toString(),
+ Message::Flags{query.value(3).toInt()});
msg.setMsgId(query.value(0).toLongLong());
messagelist << msg;
}
return messagelist;
}
-
QList<Message> SqliteStorage::requestAllMsgs(UserId user, MsgId first, MsgId last, int limit)
{
QList<Message> messagelist;
safeExec(bufferInfoQuery);
watchQuery(bufferInfoQuery);
while (bufferInfoQuery.next()) {
- BufferInfo bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(), bufferInfoQuery.value(1).toInt(), (BufferInfo::Type)bufferInfoQuery.value(2).toInt(), bufferInfoQuery.value(3).toInt(), bufferInfoQuery.value(4).toString());
+ BufferInfo bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(),
+ bufferInfoQuery.value(1).toInt(),
+ (BufferInfo::Type)bufferInfoQuery.value(2).toInt(),
+ bufferInfoQuery.value(3).toInt(),
+ bufferInfoQuery.value(4).toString());
bufferInfoHash[bufferInfo.bufferId()] = bufferInfo;
}
safeExec(bufferInfoQuery);
watchQuery(bufferInfoQuery);
while (bufferInfoQuery.next()) {
- BufferInfo bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(), bufferInfoQuery.value(1).toInt(), (BufferInfo::Type)bufferInfoQuery.value(2).toInt(), bufferInfoQuery.value(3).toInt(), bufferInfoQuery.value(4).toString());
+ BufferInfo bufferInfo = BufferInfo(bufferInfoQuery.value(0).toInt(),
+ bufferInfoQuery.value(1).toInt(),
+ (BufferInfo::Type)bufferInfoQuery.value(2).toInt(),
+ bufferInfoQuery.value(3).toInt(),
+ bufferInfoQuery.value(4).toString());
bufferInfoHash[bufferInfo.bufferId()] = bufferInfo;
}
while (query.next()) {
Message msg(
- // As of SQLite schema version 31, timestamps are stored in milliseconds
- // instead of seconds. This nets us more precision as well as simplifying
- // 64-bit time.
- QDateTime::fromMSecsSinceEpoch(query.value(2).toLongLong()),
- bufferInfoHash[query.value(1).toInt()],
- (Message::Type)query.value(3).toInt(),
- query.value(9).toString(),
- query.value(5).toString(),
- query.value(6).toString(),
- query.value(7).toString(),
- query.value(8).toString(),
- Message::Flags{query.value(4).toInt()});
+ // As of SQLite schema version 31, timestamps are stored in milliseconds
+ // instead of seconds. This nets us more precision as well as simplifying
+ // 64-bit time.
+ QDateTime::fromMSecsSinceEpoch(query.value(2).toLongLong()),
+ bufferInfoHash[query.value(1).toInt()],
+ (Message::Type)query.value(3).toInt(),
+ query.value(9).toString(),
+ query.value(5).toString(),
+ query.value(6).toString(),
+ query.value(7).toString(),
+ query.value(8).toString(),
+ Message::Flags{query.value(4).toInt()});
msg.setMsgId(query.value(0).toLongLong());
messagelist << msg;
}
return authusernames;
}
-
QString SqliteStorage::backlogFile()
{
return Quassel::configDirPath() + "quassel-storage.sqlite";
}
-
-bool SqliteStorage::safeExec(QSqlQuery &query, int retryCount)
+bool SqliteStorage::safeExec(QSqlQuery& query, int retryCount)
{
query.exec();
return true;
switch (query.lastError().number()) {
- case 5: // SQLITE_BUSY 5 /* The database file is locked */
- // fallthrough
- case 6: // SQLITE_LOCKED 6 /* A table in the database is locked */
+ case 5: // SQLITE_BUSY 5 /* The database file is locked */
+ // fallthrough
+ case 6: // SQLITE_LOCKED 6 /* A table in the database is locked */
if (retryCount < _maxRetryCount)
return safeExec(query, retryCount + 1);
break;
return false;
}
-
// ========================================
// SqliteMigration
// ========================================
SqliteMigrationReader::SqliteMigrationReader()
: SqliteStorage()
-{
-}
-
+{}
void SqliteMigrationReader::setMaxId(MigrationObject mo)
{
_maxId = query.value(0).toLongLong();
}
-
bool SqliteMigrationReader::prepareQuery(MigrationObject mo)
{
setMaxId(mo);
return exec();
}
-
-bool SqliteMigrationReader::readMo(QuasselUserMO &user)
+bool SqliteMigrationReader::readMo(QuasselUserMO& user)
{
if (!next())
return false;
return true;
}
-
-bool SqliteMigrationReader::readMo(IdentityMO &identity)
+bool SqliteMigrationReader::readMo(IdentityMO& identity)
{
if (!next())
return false;
return true;
}
-
-bool SqliteMigrationReader::readMo(IdentityNickMO &identityNick)
+bool SqliteMigrationReader::readMo(IdentityNickMO& identityNick)
{
if (!next())
return false;
return true;
}
-
-bool SqliteMigrationReader::readMo(NetworkMO &network)
+bool SqliteMigrationReader::readMo(NetworkMO& network)
{
if (!next())
return false;
return true;
}
-
-bool SqliteMigrationReader::readMo(BufferMO &buffer)
+bool SqliteMigrationReader::readMo(BufferMO& buffer)
{
if (!next())
return false;
return true;
}
-
-bool SqliteMigrationReader::readMo(SenderMO &sender)
+bool SqliteMigrationReader::readMo(SenderMO& sender)
{
int skipSteps = 0;
while (!next()) {
return true;
}
-
-bool SqliteMigrationReader::readMo(BacklogMO &backlog)
+bool SqliteMigrationReader::readMo(BacklogMO& backlog)
{
qint64 skipSteps = 0;
while (!next()) {
return true;
}
-
-bool SqliteMigrationReader::readMo(IrcServerMO &ircserver)
+bool SqliteMigrationReader::readMo(IrcServerMO& ircserver)
{
if (!next())
return false;
return true;
}
-
-bool SqliteMigrationReader::readMo(UserSettingMO &userSetting)
+bool SqliteMigrationReader::readMo(UserSettingMO& userSetting)
{
if (!next())
return false;
return true;
}
-
-bool SqliteMigrationReader::readMo(CoreStateMO &coreState)
+bool SqliteMigrationReader::readMo(CoreStateMO& coreState)
{
if (!next())
return false;
#pragma once
-#include "abstractsqlstorage.h"
-
#include <QSqlDatabase>
+#include "abstractsqlstorage.h"
+
class QSqlQuery;
class SqliteStorage : public AbstractSqlStorage
Q_OBJECT
public:
- SqliteStorage(QObject *parent = nullptr);
+ SqliteStorage(QObject* parent = nullptr);
std::unique_ptr<AbstractSqlMigrationReader> createMigrationReader() override;
public slots:
/* General */
- bool isAvailable() const override;
+ bool isAvailable() const override;
QString backendId() const override;
QString displayName() const override;
- QVariantList setupData() const override { return {}; }
+ QVariantList setupData() const override { return {}; }
QString description() const override;
// TODO: Add functions for configuring the backlog handling, i.e. defining auto-cleanup settings etc
/* User handling */
- UserId addUser(const QString &user, const QString &password, const QString &authenticator = "Database") override;
- bool updateUser(UserId user, const QString &password) override;
- void renameUser(UserId user, const QString &newName) override;
- UserId validateUser(const QString &user, const QString &password) override;
- UserId getUserId(const QString &username) override;
+ UserId addUser(const QString& user, const QString& password, const QString& authenticator = "Database") override;
+ bool updateUser(UserId user, const QString& password) override;
+ void renameUser(UserId user, const QString& newName) override;
+ UserId validateUser(const QString& user, const QString& password) override;
+ UserId getUserId(const QString& username) override;
QString getUserAuthenticator(const UserId userid) override;
UserId internalUser() override;
void delUser(UserId user) override;
- void setUserSetting(UserId userId, const QString &settingName, const QVariant &data) override;
- QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &defaultData = QVariant()) override;
- void setCoreState(const QVariantList &data) override;
- QVariantList getCoreState(const QVariantList &data) override;
+ void setUserSetting(UserId userId, const QString& settingName, const QVariant& data) override;
+ QVariant getUserSetting(UserId userId, const QString& settingName, const QVariant& defaultData = QVariant()) override;
+ void setCoreState(const QVariantList& data) override;
+ QVariantList getCoreState(const QVariantList& data) override;
/* Identity handling */
- IdentityId createIdentity(UserId user, CoreIdentity &identity) override;
- bool updateIdentity(UserId user, const CoreIdentity &identity) override;
+ IdentityId createIdentity(UserId user, CoreIdentity& identity) override;
+ bool updateIdentity(UserId user, const CoreIdentity& identity) override;
void removeIdentity(UserId user, IdentityId identityId) override;
QList<CoreIdentity> identities(UserId user) override;
/* Network handling */
- NetworkId createNetwork(UserId user, const NetworkInfo &info) override;
- bool updateNetwork(UserId user, const NetworkInfo &info) override;
- bool removeNetwork(UserId user, const NetworkId &networkId) override;
+ NetworkId createNetwork(UserId user, const NetworkInfo& info) override;
+ bool updateNetwork(UserId user, const NetworkInfo& info) override;
+ bool removeNetwork(UserId user, const NetworkId& networkId) override;
QList<NetworkInfo> networks(UserId user) override;
QList<NetworkId> connectedNetworks(UserId user) override;
- void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) override;
+ void setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected) override;
/* persistent channels */
- QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId) override;
- void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) override;
- void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) override;
+ QHash<QString, QString> persistentChannels(UserId user, const NetworkId& networkId) override;
+ void setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined) override;
+ void setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key) override;
/* persistent user states */
QString awayMessage(UserId user, NetworkId networkId) override;
- void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg) override;
+ void setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg) override;
QString userModes(UserId user, NetworkId networkId) override;
- void setUserModes(UserId user, NetworkId networkId, const QString &userModes) override;
+ void setUserModes(UserId user, NetworkId networkId, const QString& userModes) override;
/* Buffer handling */
- BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true) override;
- BufferInfo getBufferInfo(UserId user, const BufferId &bufferId) override;
+ BufferInfo bufferInfo(UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer = "", bool create = true) override;
+ BufferInfo getBufferInfo(UserId user, const BufferId& bufferId) override;
QList<BufferInfo> requestBuffers(UserId user) override;
QList<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId) override;
- bool removeBuffer(const UserId &user, const BufferId &bufferId) override;
- bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName) override;
- bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2) override;
- void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) override;
+ bool removeBuffer(const UserId& user, const BufferId& bufferId) override;
+ bool renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName) override;
+ bool mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2) override;
+ void setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) override;
QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user) override;
- void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) override;
+ void setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) override;
QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user) override;
void setBufferActivity(UserId id, BufferId bufferId, Message::Types type) override;
QHash<BufferId, Message::Types> bufferActivities(UserId id) override;
void setHighlightCount(UserId id, BufferId bufferId, int count) override;
QHash<BufferId, int> highlightCounts(UserId id) override;
int highlightCount(BufferId bufferId, MsgId lastSeenMsgId) override;
- QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId &networkId) override;
- void setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher) override;
+ QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId& networkId) override;
+ void setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher) override;
/* Message handling */
- bool logMessage(Message &msg) override;
- bool logMessages(MessageList &msgs) override;
+ bool logMessage(Message& msg) override;
+ bool logMessages(MessageList& msgs) override;
QList<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1) override;
- QList<Message> requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1,
- int limit = -1, Message::Types type = Message::Types{-1},
+ QList<Message> requestMsgsFiltered(UserId user,
+ BufferId bufferId,
+ MsgId first = -1,
+ MsgId last = -1,
+ int limit = -1,
+ Message::Types type = Message::Types{-1},
Message::Flags flags = Message::Flags{-1}) override;
QList<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1) override;
- QList<Message> requestAllMsgsFiltered(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1,
+ QList<Message> requestAllMsgsFiltered(UserId user,
+ MsgId first = -1,
+ MsgId last = -1,
+ int limit = -1,
Message::Types type = Message::Types{-1},
Message::Flags flags = Message::Flags{-1}) override;
QMap<UserId, QString> getAllAuthUserNames() override;
protected:
- void setConnectionProperties(const QVariantMap &properties,
- const QProcessEnvironment &environment,
- bool loadFromEnvironment) override {
+ void setConnectionProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment) override
+ {
Q_UNUSED(properties);
Q_UNUSED(environment);
Q_UNUSED(loadFromEnvironment);
}
// SQLite does not have any connection properties to set
- QString driverName() override { return "QSQLITE"; }
- QString databaseName() override { return backlogFile(); }
+ QString driverName() override { return "QSQLITE"; }
+ QString databaseName() override { return backlogFile(); }
int installedSchemaVersion() override;
bool updateSchemaVersion(int newVersion) override;
bool setupSchemaVersion(int version) override;
- bool safeExec(QSqlQuery &query, int retryCount = 0);
+ bool safeExec(QSqlQuery& query, int retryCount = 0);
private:
static QString backlogFile();
- void bindNetworkInfo(QSqlQuery &query, const NetworkInfo &info);
- void bindServerInfo(QSqlQuery &query, const Network::Server &server);
+ void bindNetworkInfo(QSqlQuery& query, const NetworkInfo& info);
+ void bindServerInfo(QSqlQuery& query, const Network::Server& server);
inline void lockForRead() { _dbLock.lockForRead(); }
inline void lockForWrite() { _dbLock.lockForWrite(); }
static int _maxRetryCount;
};
-
// ========================================
// SqliteMigration
// ========================================
public:
SqliteMigrationReader();
- bool readMo(QuasselUserMO &user) override;
- bool readMo(SenderMO &sender) override;
- bool readMo(IdentityMO &identity) override;
- bool readMo(IdentityNickMO &identityNick) override;
- bool readMo(NetworkMO &network) override;
- bool readMo(BufferMO &buffer) override;
- bool readMo(BacklogMO &backlog) override;
- bool readMo(IrcServerMO &ircserver) override;
- bool readMo(UserSettingMO &userSetting) override;
- bool readMo(CoreStateMO &coreState) override;
+ bool readMo(QuasselUserMO& user) override;
+ bool readMo(SenderMO& sender) override;
+ bool readMo(IdentityMO& identity) override;
+ bool readMo(IdentityNickMO& identityNick) override;
+ bool readMo(NetworkMO& network) override;
+ bool readMo(BufferMO& buffer) override;
+ bool readMo(BacklogMO& backlog) override;
+ bool readMo(IrcServerMO& ircserver) override;
+ bool readMo(UserSettingMO& userSetting) override;
+ bool readMo(CoreStateMO& coreState) override;
bool prepareQuery(MigrationObject mo) override;
qint64 stepSize() { return 50000; }
protected:
- bool transaction() override { return logDb().transaction(); }
- void rollback() override { logDb().rollback(); }
- bool commit() override { return logDb().commit(); }
+ bool transaction() override { return logDb().transaction(); }
+ void rollback() override { logDb().rollback(); }
+ bool commit() override { return logDb().commit(); }
private:
void setMaxId(MigrationObject mo);
qint64 _maxId{0};
};
-
inline std::unique_ptr<AbstractSqlMigrationReader> SqliteStorage::createMigrationReader()
{
return std::unique_ptr<AbstractSqlMigrationReader>{new SqliteMigrationReader()};
#include "sslserver.h"
#ifdef HAVE_SSL
-# include <QSslSocket>
+# include <QSslSocket>
#endif
#include <QDateTime>
-#include "quassel.h"
#include "logmessage.h"
+#include "quassel.h"
#ifdef HAVE_SSL
-SslServer::SslServer(QObject *parent)
+SslServer::SslServer(QObject* parent)
: QTcpServer(parent)
{
// Keep track if the SSL warning has been mentioned at least once before
static bool sslWarningShown = false;
- if(Quassel::isOptionSet("ssl-cert")) {
+ if (Quassel::isOptionSet("ssl-cert")) {
_sslCertPath = Quassel::optionValue("ssl-cert");
- } else {
+ }
+ else {
_sslCertPath = Quassel::configDirPath() + "quasselCert.pem";
}
- if(Quassel::isOptionSet("ssl-key")) {
+ if (Quassel::isOptionSet("ssl-key")) {
_sslKeyPath = Quassel::optionValue("ssl-key");
- } else {
+ }
+ else {
_sslKeyPath = _sslCertPath;
}
// Initialize the certificates for first-time usage
if (!loadCerts()) {
if (!sslWarningShown) {
- quWarning()
- << "SslServer: Unable to set certificate file\n"
- << " Quassel Core will still work, but cannot provide SSL for client connections.\n"
- << " Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support.";
+ quWarning() << "SslServer: Unable to set certificate file\n"
+ << " Quassel Core will still work, but cannot provide SSL for client connections.\n"
+ << " Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support.";
sslWarningShown = true;
}
}
}
-
-QTcpSocket *SslServer::nextPendingConnection()
+QTcpSocket* SslServer::nextPendingConnection()
{
if (_pendingConnections.isEmpty())
return nullptr;
return _pendingConnections.takeFirst();
}
-
void SslServer::incomingConnection(qintptr socketDescriptor)
{
- auto *serverSocket = new QSslSocket(this);
+ auto* serverSocket = new QSslSocket(this);
if (serverSocket->setSocketDescriptor(socketDescriptor)) {
if (isCertValid()) {
serverSocket->setLocalCertificate(_cert);
}
}
-
bool SslServer::loadCerts()
{
// Load the certificates specified in the path. If needed, other prep work can be done here.
return setCertificate(_sslCertPath, _sslKeyPath);
}
-
bool SslServer::reloadCerts()
{
if (loadCerts()) {
return true;
- } else {
+ }
+ else {
// Reloading certificates currently only occur in response to a request. Always print an
// error if something goes wrong, in order to simplify checking if it's working.
if (isCertValid()) {
- quWarning()
- << "SslServer: Unable to reload certificate file, reverting\n"
- << " Quassel Core will use the previous key to provide SSL for client connections.\n"
- << " Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support.";
- } else {
- quWarning()
- << "SslServer: Unable to reload certificate file\n"
- << " Quassel Core will still work, but cannot provide SSL for client connections.\n"
- << " Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support.";
+ quWarning() << "SslServer: Unable to reload certificate file, reverting\n"
+ << " Quassel Core will use the previous key to provide SSL for client connections.\n"
+ << " Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support.";
+ }
+ else {
+ quWarning() << "SslServer: Unable to reload certificate file\n"
+ << " Quassel Core will still work, but cannot provide SSL for client connections.\n"
+ << " Please see https://quassel-irc.org/faq/cert to learn how to enable SSL support.";
}
return false;
}
}
-
-bool SslServer::setCertificate(const QString &path, const QString &keyPath)
+bool SslServer::setCertificate(const QString& path, const QString& keyPath)
{
// Don't reset _isCertValid here, in case an older but valid certificate is still loaded.
// Use temporary variables in order to avoid overwriting the existing certificates until
}
if (!certFile.open(QIODevice::ReadOnly)) {
- quWarning()
- << "SslServer: Failed to open certificate file" << qPrintable(path)
- << "error:" << certFile.error();
+ quWarning() << "SslServer: Failed to open certificate file" << qPrintable(path) << "error:" << certFile.error();
return false;
}
}
untestedCert = certList[0];
- certList.removeFirst(); // remove server cert
+ certList.removeFirst(); // remove server cert
// store CA and intermediates certs
untestedCA = certList;
}
// load key from keyPath if it differs from path, otherwise load key from path
- if(path != keyPath) {
+ if (path != keyPath) {
QFile keyFile(keyPath);
- if(!keyFile.exists()) {
+ if (!keyFile.exists()) {
quWarning() << "SslServer: Key file" << qPrintable(keyPath) << "does not exist";
return false;
}
if (!keyFile.open(QIODevice::ReadOnly)) {
- quWarning()
- << "SslServer: Failed to open key file" << qPrintable(keyPath)
- << "error:" << keyFile.error();
+ quWarning() << "SslServer: Failed to open key file" << qPrintable(keyPath) << "error:" << keyFile.error();
return false;
}
untestedKey = loadKey(&keyFile);
keyFile.close();
- } else {
+ }
+ else {
untestedKey = loadKey(&certFile);
}
return _isCertValid;
}
-
-QSslKey SslServer::loadKey(QFile *keyFile)
+QSslKey SslServer::loadKey(QFile* keyFile)
{
QSslKey key;
key = QSslKey(keyFile, QSsl::Rsa);
return key;
}
-
-#endif // HAVE_SSL
+#endif // HAVE_SSL
#ifdef HAVE_SSL
-#include <QSslCertificate>
-#include <QSslKey>
-#include <QTcpServer>
-#include <QLinkedList>
-#include <QFile>
+# include <QFile>
+# include <QLinkedList>
+# include <QSslCertificate>
+# include <QSslKey>
+# include <QTcpServer>
class SslServer : public QTcpServer
{
Q_OBJECT
public:
- SslServer(QObject *parent = nullptr);
+ SslServer(QObject* parent = nullptr);
bool hasPendingConnections() const override { return !_pendingConnections.isEmpty(); }
- QTcpSocket *nextPendingConnection() override;
+ QTcpSocket* nextPendingConnection() override;
- const QSslCertificate &certificate() const { return _cert; }
- const QSslKey &key() const { return _key; }
+ const QSslCertificate& certificate() const { return _cert; }
+ const QSslKey& key() const { return _key; }
bool isCertValid() const { return _isCertValid; }
/**
protected:
void incomingConnection(qintptr socketDescriptor) override;
- bool setCertificate(const QString &path, const QString &keyPath);
+ bool setCertificate(const QString& path, const QString& keyPath);
private:
/**
* @return True if certificates loaded successfully, otherwise false.
*/
bool loadCerts();
- QSslKey loadKey(QFile *keyFile);
+ QSslKey loadKey(QFile* keyFile);
- QLinkedList<QTcpSocket *> _pendingConnections;
+ QLinkedList<QTcpSocket*> _pendingConnections;
QSslCertificate _cert;
QSslKey _key;
QList<QSslCertificate> _ca;
bool _isCertValid{false};
// Used when reloading certificates later
- QString _sslCertPath; /// Path to the certificate file
- QString _sslKeyPath; /// Path to the private key file (may be in same file as above)
+ QString _sslCertPath; /// Path to the certificate file
+ QString _sslKeyPath; /// Path to the private key file (may be in same file as above)
};
-
-#endif //HAVE_SSL
+#endif // HAVE_SSL
#include <QCryptographicHash>
-Storage::Storage(QObject *parent)
+Storage::Storage(QObject* parent)
: QObject(parent)
-{
-}
+{}
-QString Storage::hashPassword(const QString &password)
+QString Storage::hashPassword(const QString& password)
{
return hashPasswordSha2_512(password);
}
-bool Storage::checkHashedPassword(const UserId user, const QString &password, const QString &hashedPassword, const Storage::HashVersion version)
+bool Storage::checkHashedPassword(const UserId user, const QString& password, const QString& hashedPassword, const Storage::HashVersion version)
{
bool passwordCorrect = false;
return passwordCorrect;
}
-QString Storage::hashPasswordSha1(const QString &password)
+QString Storage::hashPasswordSha1(const QString& password)
{
return QString(QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Sha1).toHex());
}
-bool Storage::checkHashedPasswordSha1(const QString &password, const QString &hashedPassword)
+bool Storage::checkHashedPasswordSha1(const QString& password, const QString& hashedPassword)
{
return hashPasswordSha1(password) == hashedPassword;
}
-QString Storage::hashPasswordSha2_512(const QString &password)
+QString Storage::hashPasswordSha2_512(const QString& password)
{
// Generate a salt of 512 bits (64 bytes) using the Mersenne Twister
std::random_device seed;
QByteArray saltBytes;
saltBytes.resize(64);
for (int i = 0; i < 64; i++) {
- saltBytes[i] = (unsigned char) distribution(generator);
+ saltBytes[i] = (unsigned char)distribution(generator);
}
QString salt(saltBytes.toHex());
return sha2_512(password + salt) + ":" + salt;
}
-bool Storage::checkHashedPasswordSha2_512(const QString &password, const QString &hashedPassword)
+bool Storage::checkHashedPasswordSha2_512(const QString& password, const QString& hashedPassword)
{
QRegExp colonSplitter("\\:");
QStringList hashedPasswordAndSalt = hashedPassword.split(colonSplitter);
- if (hashedPasswordAndSalt.size() == 2){
+ if (hashedPasswordAndSalt.size() == 2) {
return sha2_512(password + hashedPasswordAndSalt[1]) == hashedPasswordAndSalt[0];
}
else {
}
}
-QString Storage::sha2_512(const QString &input)
+QString Storage::sha2_512(const QString& input)
{
return QString(QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Sha512).toHex());
}
#include <QtCore>
-#include "types.h"
#include "coreidentity.h"
#include "message.h"
#include "network.h"
+#include "types.h"
class Storage : public QObject
{
Q_OBJECT
public:
- Storage(QObject *parent = nullptr);
+ Storage(QObject* parent = nullptr);
- enum State {
- IsReady, // ready to go
- NeedsSetup, // need basic setup (ask the user for input)
- NotAvailable // remove the storage backend from the list of avaliable backends
+ enum State
+ {
+ IsReady, // ready to go
+ NeedsSetup, // need basic setup (ask the user for input)
+ NotAvailable // remove the storage backend from the list of avaliable backends
};
- enum HashVersion {
+ enum HashVersion
+ {
Sha1,
Sha2_512,
- Latest=Sha2_512
+ Latest = Sha2_512
};
* \param settings Hostname, port, username, password, ...
* \return True if and only if the storage provider was initialized successfully.
*/
- virtual bool setup(const QVariantMap &settings = QVariantMap(),
- const QProcessEnvironment &environment = {},
- bool loadFromEnvironment = false) = 0;
+ virtual bool setup(const QVariantMap& settings = QVariantMap(),
+ const QProcessEnvironment& environment = {},
+ bool loadFromEnvironment = false)
+ = 0;
//! Initialize the storage provider
/** \param settings Hostname, port, username, password, ...
* \return the State the storage backend is now in (see Storage::State)
*/
- virtual State init(const QVariantMap &settings = QVariantMap(),
- const QProcessEnvironment &environment = {},
- bool loadFromEnvironment = false) = 0;
+ virtual State init(const QVariantMap& settings = QVariantMap(),
+ const QProcessEnvironment& environment = {},
+ bool loadFromEnvironment = false)
+ = 0;
//! Makes temp data persistent
/** This Method is periodically called by the Quassel Core to make temporary
* \param password The cleartext password for the new user
* \return The new user's UserId
*/
- virtual UserId addUser(const QString &user, const QString &password, const QString &authenticator = "Database") = 0;
+ virtual UserId addUser(const QString& user, const QString& password, const QString& authenticator = "Database") = 0;
//! Update a core user's password.
/** \param user The user's id
* \param password The user's new password
* \return true on success.
*/
- virtual bool updateUser(UserId user, const QString &password) = 0;
+ virtual bool updateUser(UserId user, const QString& password) = 0;
//! Rename a user
/** \param user The user's id
* \param newName The user's new name
*/
- virtual void renameUser(UserId user, const QString &newName) = 0;
+ virtual void renameUser(UserId user, const QString& newName) = 0;
//! Validate a username with a given password.
/** \param user The username to validate
* \param password The user's alleged password
* \return A valid UserId if the password matches the username; 0 else
*/
- virtual UserId validateUser(const QString &user, const QString &password) = 0;
+ virtual UserId validateUser(const QString& user, const QString& password) = 0;
//! Check if a user with given username exists. Do not use for login purposes!
/** \param username The username to validate
* \return A valid UserId if the user exists; 0 else
*/
- virtual UserId getUserId(const QString &username) = 0;
+ virtual UserId getUserId(const QString& username) = 0;
//! Get the authentication provider for a given user.
/** \param username The username to validate
*/
virtual QString getUserAuthenticator(const UserId userid) = 0;
-
//! Determine the UserId of the internal user
/** \return A valid UserId if the password matches the username; 0 else
*/
* \param settingName The Name of the Setting
* \param data The Value
*/
- virtual void setUserSetting(UserId userId, const QString &settingName, const QVariant &data) = 0;
+ virtual void setUserSetting(UserId userId, const QString& settingName, const QVariant& data) = 0;
//! Retrieve a persistent user setting
/**
* \param default Value to return in case it's unset.
* \return the Value of the Setting or the default value if it is unset.
*/
- virtual QVariant getUserSetting(UserId userId, const QString &settingName, const QVariant &data = QVariant()) = 0;
+ virtual QVariant getUserSetting(UserId userId, const QString& settingName, const QVariant& data = QVariant()) = 0;
//! Store core state
/**
* \param data Active Sessions
*/
- virtual void setCoreState(const QVariantList &data) = 0;
+ virtual void setCoreState(const QVariantList& data) = 0;
//! Retrieve core state
/**
* \param default Value to return in case it's unset.
* \return Active Sessions
*/
- virtual QVariantList getCoreState(const QVariantList &data = QVariantList()) = 0;
+ virtual QVariantList getCoreState(const QVariantList& data = QVariantList()) = 0;
/* Identity handling */
- virtual IdentityId createIdentity(UserId user, CoreIdentity &identity) = 0;
- virtual bool updateIdentity(UserId user, const CoreIdentity &identity) = 0;
+ virtual IdentityId createIdentity(UserId user, CoreIdentity& identity) = 0;
+ virtual bool updateIdentity(UserId user, const CoreIdentity& identity) = 0;
virtual void removeIdentity(UserId user, IdentityId identityId) = 0;
virtual QList<CoreIdentity> identities(UserId user) = 0;
* \param networkInfo The networkInfo holding the network definition
* \return the NetworkId of the newly created Network. Possibly invalid.
*/
- virtual NetworkId createNetwork(UserId user, const NetworkInfo &info) = 0;
+ virtual NetworkId createNetwork(UserId user, const NetworkInfo& info) = 0;
//! Apply the changes to NetworkInfo info to the storage engine
/**
* \param networkInfo The Updated NetworkInfo
* \return true if successfull.
*/
- virtual bool updateNetwork(UserId user, const NetworkInfo &info) = 0;
+ virtual bool updateNetwork(UserId user, const NetworkInfo& info) = 0;
//! Permanently remove a Network and all the data associated with it.
/** \note This method is thredsafe.
* \param networkId The network to delete
* \return true if successfull.
*/
- virtual bool removeNetwork(UserId user, const NetworkId &networkId) = 0;
+ virtual bool removeNetwork(UserId user, const NetworkId& networkId) = 0;
//! Returns a list of all NetworkInfos for the given UserId user
/** \note This method is thredsafe.
* \param networkId The Id of the network
* \param isConnected whether the network is connected or not
*/
- virtual void setNetworkConnected(UserId user, const NetworkId &networkId, bool isConnected) = 0;
+ virtual void setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected) = 0;
//! Get a hash of channels with their channel keys for a given network
/** The keys are channel names and values are passwords (possibly empty)
* \param user The id of the networks owner
* \param networkId The Id of the network
*/
- virtual QHash<QString, QString> persistentChannels(UserId user, const NetworkId &networkId) = 0;
+ virtual QHash<QString, QString> persistentChannels(UserId user, const NetworkId& networkId) = 0;
//! Update the connected state of a channel
/** \note This method is threadsafe
* \param channel The name of the channel
* \param isJoined whether the channel is connected or not
*/
- virtual void setChannelPersistent(UserId user, const NetworkId &networkId, const QString &channel, bool isJoined) = 0;
+ virtual void setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined) = 0;
//! Update the key of a channel
/** \note This method is threadsafe
* \param channel The name of the channel
* \param key The key of the channel (possibly empty)
*/
- virtual void setPersistentChannelKey(UserId user, const NetworkId &networkId, const QString &channel, const QString &key) = 0;
+ virtual void setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key) = 0;
//! retrieve last known away message for session restore
/** \note This method is threadsafe
* \param networkId The Id of the network
* \param awayMsg The current away message of own user
*/
- virtual void setAwayMessage(UserId user, NetworkId networkId, const QString &awayMsg) = 0;
+ virtual void setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg) = 0;
//! retrieve last known user mode for session restore
/** \note This method is threadsafe
* \param networkId The Id of the network
* \param userModes The current user modes of own user
*/
- virtual void setUserModes(UserId user, NetworkId networkId, const QString &userModes) = 0;
+ virtual void setUserModes(UserId user, NetworkId networkId, const QString& userModes) = 0;
/* Buffer handling */
* \param create Whether or not the buffer should be created if it doesnt exist
* \return The BufferInfo corresponding to the given network and buffer name, or an invalid BufferInfo if not found
*/
- virtual BufferInfo bufferInfo(UserId user, const NetworkId &networkId, BufferInfo::Type type, const QString &buffer = "", bool create = true) = 0;
+ virtual BufferInfo bufferInfo(UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer = "", bool create = true)
+ = 0;
//! Get the unique BufferInfo for a bufferId
/** \param user The core user who owns this buffername
* \param bufferId The id of the buffer
* \return The BufferInfo corresponding to the given buffer id, or an invalid BufferInfo if not found.
*/
- virtual BufferInfo getBufferInfo(UserId user, const BufferId &bufferId) = 0;
+ virtual BufferInfo getBufferInfo(UserId user, const BufferId& bufferId) = 0;
//! Request a list of all buffers known to a user.
/** This method is used to get a list of all buffers we have stored a backlog from.
* \param bufferId The bufferId
* \return true if successfull
*/
- virtual bool removeBuffer(const UserId &user, const BufferId &bufferId) = 0;
+ virtual bool removeBuffer(const UserId& user, const BufferId& bufferId) = 0;
//! Rename a Buffer
/** \note This method is threadsafe.
* \param newName The new name of the buffer
* \return true if successfull
*/
- virtual bool renameBuffer(const UserId &user, const BufferId &bufferId, const QString &newName) = 0;
+ virtual bool renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName) = 0;
//! Merge the content of two Buffers permanently. This cannot be reversed!
/** \note This method is threadsafe.
* \param bufferId2 The buffer that is about to be removed
* \return true if successfull
*/
- virtual bool mergeBuffersPermanently(const UserId &user, const BufferId &bufferId1, const BufferId &bufferId2) = 0;
+ virtual bool mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2) = 0;
//! Update the LastSeenDate for a Buffer
/** This Method is used to make the LastSeenDate of a Buffer persistent
* \param bufferId The buffer id
* \param MsgId The Message id of the message that has been just seen
*/
- virtual void setBufferLastSeenMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) = 0;
+ virtual void setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) = 0;
//! Get a Hash of all last seen message ids
/** This Method is called when the Quassel Core is started to restore the lastSeenMsgIds
* \param bufferId The buffer id
* \param MsgId The Message id where the marker line should be placed
*/
- virtual void setBufferMarkerLineMsg(UserId user, const BufferId &bufferId, const MsgId &msgId) = 0;
+ virtual void setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) = 0;
//! Get a Hash of all marker line message ids
/** This Method is called when the Quassel Core is started to restore the MarkerLineMsgIds
* \param user The id of the networks owner
* \param networkId The Id of the network
*/
- virtual QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId &networkId) = 0;
+ virtual QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId& networkId) = 0;
//! Update the cipher of a buffer
/** \note This method is threadsafe
* \param bufferName The Cname of the buffer
* \param cipher The cipher for the buffer
*/
- virtual void setBufferCipher(UserId user, const NetworkId &networkId, const QString &bufferName, const QByteArray &cipher) = 0;
+ virtual void setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher) = 0;
//! Update the highlight count for a Buffer
/** This Method is used to make the activity state of a Buffer persistent
/** \param msg The message object to be stored
* \return true on success
*/
- virtual bool logMessage(Message &msg) = 0;
+ virtual bool logMessage(Message& msg) = 0;
//! Store a list of Messages in the storage backend and set their unique Id.
/** \param msgs The list message objects to be stored
* \return true on success
*/
- virtual bool logMessages(MessageList &msgs) = 0;
+ virtual bool logMessages(MessageList& msgs) = 0;
//! Request a certain number messages stored in a given buffer.
/** \param buffer The buffer we request messages from
* \param type The Message::Types that should be returned
* \return The requested list of messages
*/
- virtual QList<Message> requestMsgsFiltered(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1,
- int limit = -1, Message::Types type = Message::Types{-1},
- Message::Flags flags = Message::Flags{-1}) = 0;
+ virtual QList<Message> requestMsgsFiltered(UserId user,
+ BufferId bufferId,
+ MsgId first = -1,
+ MsgId last = -1,
+ int limit = -1,
+ Message::Types type = Message::Types{-1},
+ Message::Flags flags = Message::Flags{-1})
+ = 0;
//! Request a certain number of messages across all buffers
/** \param first if != -1 return only messages with a MsgId >= first
* \param type The Message::Types that should be returned
* \return The requested list of messages
*/
- virtual QList<Message> requestAllMsgsFiltered(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1,
+ virtual QList<Message> requestAllMsgsFiltered(UserId user,
+ MsgId first = -1,
+ MsgId last = -1,
+ int limit = -1,
Message::Types type = Message::Types{-1},
- Message::Flags flags = Message::Flags{-1}) = 0;
+ Message::Flags flags = Message::Flags{-1})
+ = 0;
//! Fetch all authusernames
/** \return Map of all current UserIds to permitted idents
signals:
//! Sent when a new BufferInfo is created, or an existing one changed somehow.
- void bufferInfoUpdated(UserId user, const BufferInfo &);
+ void bufferInfoUpdated(UserId user, const BufferInfo&);
//! Sent when a Buffer was renamed
- void bufferRenamed(const QString &newName, const QString &oldName);
+ void bufferRenamed(const QString& newName, const QString& oldName);
//! Sent when a new user has been added
- void userAdded(UserId, const QString &username);
+ void userAdded(UserId, const QString& username);
//! Sent when a user has been renamed
- void userRenamed(UserId, const QString &newname);
+ void userRenamed(UserId, const QString& newname);
//! Sent when a user has been removed
void userRemoved(UserId);
void dbUpgradeInProgress(bool inProgress);
protected:
- QString hashPassword(const QString &password);
- bool checkHashedPassword(const UserId user, const QString &password, const QString &hashedPassword, const Storage::HashVersion version);
+ QString hashPassword(const QString& password);
+ bool checkHashedPassword(const UserId user, const QString& password, const QString& hashedPassword, const Storage::HashVersion version);
private:
- QString hashPasswordSha1(const QString &password);
- bool checkHashedPasswordSha1(const QString &password, const QString &hashedPassword);
+ QString hashPasswordSha1(const QString& password);
+ bool checkHashedPasswordSha1(const QString& password, const QString& hashedPassword);
- QString hashPasswordSha2_512(const QString &password);
- bool checkHashedPasswordSha2_512(const QString &password, const QString &hashedPassword);
- QString sha2_512(const QString &input);
+ QString hashPasswordSha2_512(const QString& password);
+ bool checkHashedPasswordSha2_512(const QString& password, const QString& hashedPassword);
+ QString sha2_512(const QString& input);
};
-
#endif
#include <memory>
#ifdef HAVE_UMASK
-# include <sys/types.h>
-# include <sys/stat.h>
+# include <sys/stat.h>
+# include <sys/types.h>
#endif /* HAVE_UMASK */
#include <QCoreApplication>
#include <QTextCodec>
#ifdef BUILD_CORE
-# include "coreapplication.h"
+# include "coreapplication.h"
#elif defined BUILD_QTUI
-# include "aboutdata.h"
-# include "qtuiapplication.h"
+# include "aboutdata.h"
+# include "qtuiapplication.h"
#elif defined BUILD_MONO
-# include "aboutdata.h"
-# include "monoapplication.h"
+# include "aboutdata.h"
+# include "monoapplication.h"
#else
-#error "Something is wrong - you need to #define a build mode!"
+# error "Something is wrong - you need to #define a build mode!"
#endif
// We don't want quasselcore to depend on KDE
#if defined HAVE_KF5 && defined BUILD_CORE
-# undef HAVE_KF5
+# undef HAVE_KF5
#endif
#if defined HAVE_KF5
-# include <KCoreAddons/KAboutData>
-# include <KCoreAddons/Kdelibs4ConfigMigrator>
+# include <KCoreAddons/KAboutData>
+# include <KCoreAddons/Kdelibs4ConfigMigrator>
#endif
#include "quassel.h"
#include "types.h"
-int main(int argc, char **argv)
+int main(int argc, char** argv)
{
// Set umask so files are created with restricted permissions
#ifdef HAVE_UMASK
// Migrate settings from KDE4 to KF5 if appropriate
#ifdef HAVE_KF5
Kdelibs4ConfigMigrator migrator(QCoreApplication::applicationName());
- migrator.setConfigFiles(QStringList() << "quasselrc" << "quassel.notifyrc");
+ migrator.setConfigFiles(QStringList() << "quasselrc"
+ << "quassel.notifyrc");
migrator.migrate();
#endif
- //Setup the High-DPI settings
-# if QT_VERSION >= 0x050600 && defined(Q_OS_WIN)
- QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); //Added in Qt 5.6
+ // Setup the High-DPI settings
+#if QT_VERSION >= 0x050600 && defined(Q_OS_WIN)
+ QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); // Added in Qt 5.6
#endif
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
***************************************************************************/
#include "monoapplication.h"
-#include "coreapplication.h"
+
#include "client.h"
#include "core.h"
+#include "coreapplication.h"
#include "internalpeer.h"
#include "logmessage.h"
#include "qtui.h"
class InternalPeer;
-MonolithicApplication::MonolithicApplication(int &argc, char **argv)
+MonolithicApplication::MonolithicApplication(int& argc, char** argv)
: QtUiApplication(argc, argv)
-{
-}
-
+{}
void MonolithicApplication::init()
{
}
}
-
Quassel::QuitHandler MonolithicApplication::quitHandler()
{
return [this]() {
};
}
-
void MonolithicApplication::onClientDestroyed()
{
if (_core) {
}
}
-
void MonolithicApplication::onCoreShutdown()
{
if (_core) {
}
}
-
void MonolithicApplication::startInternalCore()
{
if (_core) {
_coreThread.start();
}
-
void MonolithicApplication::onConnectionRequest(QPointer<InternalPeer> peer)
{
if (!_core) {
Q_OBJECT
public:
- MonolithicApplication(int &, char **);
+ MonolithicApplication(int&, char**);
void init() override;
#include "quassel.h"
#include "util.h"
-AboutDlg::AboutDlg(QWidget *parent)
+AboutDlg::AboutDlg(QWidget* parent)
: QDialog(parent)
, _aboutData(new AboutData(this))
{
versionDate = QString("<i>%1</i>").arg(tr("Unknown date"));
}
else {
- versionDate = tryFormatUnixEpoch(Quassel::buildInfo().commitDate,
- Qt::DateFormat::DefaultLocaleShortDate);
+ versionDate = tryFormatUnixEpoch(Quassel::buildInfo().commitDate, Qt::DateFormat::DefaultLocaleShortDate);
}
ui.versionLabel->setText(QString(tr("<b>Version:</b> %1<br>"
"<b>Version date:</b> %2<br>"
"<b>Protocol version:</b> %3"))
- .arg(Quassel::buildInfo().fancyVersionString)
- .arg(versionDate)
- .arg(Quassel::buildInfo().protocolVersion));
+ .arg(Quassel::buildInfo().fancyVersionString)
+ .arg(versionDate)
+ .arg(Quassel::buildInfo().protocolVersion));
ui.aboutTextBrowser->setHtml(about());
ui.authorTextBrowser->setHtml(authors());
ui.contributorTextBrowser->setHtml(contributors());
setWindowIcon(icon::get("quassel"));
}
-
QString AboutDlg::about() const
{
- QString res {tr("<b>A modern, distributed IRC Client</b><br><br>"
- "©%1 by the Quassel Project<br>"
- "<a href=\"https://quassel-irc.org\">https://quassel-irc.org</a><br>"
- "<a href=\"irc://irc.freenode.net/quassel\">#quassel</a> on <a href=\"https://www.freenode.net\">Freenode</a><br><br>"
- "Quassel IRC is dual-licensed under <a href=\"https://www.gnu.org/licenses/gpl-2.0.txt\">GPLv2</a> and "
- "<a href=\"https://www.gnu.org/licenses/gpl-3.0.txt\">GPLv3</a>.<br>"
- "<a href=\"https://api.kde.org/frameworks/breeze-icons/html\">Breeze icon theme</a> © Uri Herrera and others, licensed under the "
- "<a href=\"https://github.com/KDE/breeze-icons/blob/21ffd9b/COPYING-ICONS\">LGPLv3</a>.<br>"
- "<a href=\"https://api.kde.org/frameworks/oxygen-icons5/html\">Oxygen icon theme</a> © Nuno Pinheiro and others, licensed under the "
- "<a href=\"https://github.com/KDE/oxygen-icons/blob/master/COPYING\">LGPLv3</a>.<br><br>"
- "Please use <a href=\"https://bugs.quassel-irc.org\">https://bugs.quassel-irc.org</a> to report bugs."
- ).arg("2005-2018")
- };
+ QString res{tr("<b>A modern, distributed IRC Client</b><br><br>"
+ "©%1 by the Quassel Project<br>"
+ "<a href=\"https://quassel-irc.org\">https://quassel-irc.org</a><br>"
+ "<a href=\"irc://irc.freenode.net/quassel\">#quassel</a> on <a href=\"https://www.freenode.net\">Freenode</a><br><br>"
+ "Quassel IRC is dual-licensed under <a href=\"https://www.gnu.org/licenses/gpl-2.0.txt\">GPLv2</a> and "
+ "<a href=\"https://www.gnu.org/licenses/gpl-3.0.txt\">GPLv3</a>.<br>"
+ "<a href=\"https://api.kde.org/frameworks/breeze-icons/html\">Breeze icon theme</a> © Uri Herrera and others, "
+ "licensed under the "
+ "<a href=\"https://github.com/KDE/breeze-icons/blob/21ffd9b/COPYING-ICONS\">LGPLv3</a>.<br>"
+ "<a href=\"https://api.kde.org/frameworks/oxygen-icons5/html\">Oxygen icon theme</a> © Nuno Pinheiro and others, "
+ "licensed under the "
+ "<a href=\"https://github.com/KDE/oxygen-icons/blob/master/COPYING\">LGPLv3</a>.<br><br>"
+ "Please use <a href=\"https://bugs.quassel-irc.org\">https://bugs.quassel-irc.org</a> to report bugs.")
+ .arg("2005-2018")};
return res;
}
-
QString AboutDlg::authors() const
{
- QString res {tr("Quassel IRC is mainly developed by:") + "<dl>"};
- for (auto &&person : _aboutData->authors()) {
+ QString res{tr("Quassel IRC is mainly developed by:") + "<dl>"};
+ for (auto&& person : _aboutData->authors()) {
res.append("<dt><b>" + person.prettyName() + "</b></dt><dd>");
if (!person.emailAddress().isEmpty())
res.append("<a href=\"mailto:" + person.emailAddress() + "\">" + person.emailAddress() + "</a><br>");
return res;
}
-
QString AboutDlg::contributors() const
{
- QString res {tr("We would like to thank the following contributors (in alphabetical order) and everybody we forgot to mention here:") + "<br><dl>"};
- for (auto &&person : _aboutData->credits()) {
+ QString res{tr("We would like to thank the following contributors (in alphabetical order) and everybody we forgot to mention here:")
+ + "<br><dl>"};
+ for (auto&& person : _aboutData->credits()) {
res.append("<dt><b>" + person.prettyName() + "</b></dt><dd><i>" + person.task() + "</i><br></dd>");
}
- res.append("</dl>" + tr("...and anybody else finding and reporting bugs, giving feedback, helping others and being part of the community!"));
+ res.append("</dl>"
+ + tr("...and anybody else finding and reporting bugs, giving feedback, helping others and being part of the community!"));
return res;
}
-
QString AboutDlg::thanksTo() const
{
- QString res {tr("Special thanks goes to:") + "<br>"
- "<table>"
- "<tr><td rowspan='2' valign='middle'><img src=':/pics/quassel-eye.png'> </td>"
- "<td><b>John \"nox\" Hand</b></td></tr>"
- "<tr><td><i>" + tr("for the original Quassel logo - The All-Seeing Eye") + "</i></td></tr>"
- "<tr/>"
- "<tr><td rowspan='2' valign='middle'><img src=':/pics/quassel-oxygen-32.png'></td>"
- "<td><b>Nuno Pinheiro</b></td></tr>"
- "<tr><td><i>" + tr("for the Oxygen Quassel logo") + "</i></td></tr>"
- "<tr/>"
- "<tr><td rowspan='2' valign='middle'><img src=':/pics/kde-vdg.png'></td>"
- "<td><b><a href='https://vdesign.kde.org'>The KDE Visual Design Group</a></b></td></tr>"
- "<tr><td><i>" + tr("for the amazing Breeze and Oxygen icon themes") + "</i></td></tr>"
- "<tr/>"
- "<tr><td rowspan='2' valign='middle'><img src=':/pics/qt-logo-32.png'></td>"
- "<td><b><a href='https://www.qt.io/'>The Qt Company</a></b> (formerly known as Qt Software, Nokia, Trolltech)</td></tr>"
- "<tr><td><i>" + tr("for creating an awesome framework, and for sponsoring development with Greenphones, N810s, N950s and more") + "</i></td></tr>"
- "</table>"
- };
+ QString res{tr("Special thanks goes to:")
+ + "<br>"
+ "<table>"
+ "<tr><td rowspan='2' valign='middle'><img src=':/pics/quassel-eye.png'> </td>"
+ "<td><b>John \"nox\" Hand</b></td></tr>"
+ "<tr><td><i>"
+ + tr("for the original Quassel logo - The All-Seeing Eye")
+ + "</i></td></tr>"
+ "<tr/>"
+ "<tr><td rowspan='2' valign='middle'><img src=':/pics/quassel-oxygen-32.png'></td>"
+ "<td><b>Nuno Pinheiro</b></td></tr>"
+ "<tr><td><i>"
+ + tr("for the Oxygen Quassel logo")
+ + "</i></td></tr>"
+ "<tr/>"
+ "<tr><td rowspan='2' valign='middle'><img src=':/pics/kde-vdg.png'></td>"
+ "<td><b><a href='https://vdesign.kde.org'>The KDE Visual Design Group</a></b></td></tr>"
+ "<tr><td><i>"
+ + tr("for the amazing Breeze and Oxygen icon themes")
+ + "</i></td></tr>"
+ "<tr/>"
+ "<tr><td rowspan='2' valign='middle'><img src=':/pics/qt-logo-32.png'></td>"
+ "<td><b><a href='https://www.qt.io/'>The Qt Company</a></b> (formerly known as Qt Software, Nokia, Trolltech)</td></tr>"
+ "<tr><td><i>"
+ + tr("for creating an awesome framework, and for sponsoring development with Greenphones, N810s, N950s and more")
+ + "</i></td></tr>"
+ "</table>"};
return res;
}
Q_OBJECT
public:
- AboutDlg(QWidget *parent = nullptr);
+ AboutDlg(QWidget* parent = nullptr);
private:
Ui::AboutDlg ui;
QString contributors() const;
QString thanksTo() const;
- AboutData *_aboutData;
+ AboutData* _aboutData;
};
-
#endif
***************************************************************************/
#include "awaylogfilter.h"
+
#include "clientignorelistmanager.h"
-AwayLogFilter::AwayLogFilter(MessageModel *model, QObject *parent)
+AwayLogFilter::AwayLogFilter(MessageModel* model, QObject* parent)
: ChatMonitorFilter(model, parent)
-{
-}
+{}
-
-bool AwayLogFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
+bool AwayLogFilter::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const
{
Q_UNUSED(sourceParent)
// ignorelist handling
// only match if message is not flagged as server msg
if (!(flags & Message::ServerMsg) && Client::ignoreListManager()
- && Client::ignoreListManager()->match(source_index.data(MessageModel::MessageRole).value<Message>(), Client::networkModel()->networkName(bufferId))) {
+ && Client::ignoreListManager()->match(source_index.data(MessageModel::MessageRole).value<Message>(),
+ Client::networkModel()->networkName(bufferId))) {
return false;
}
return true;
}
-
-QVariant AwayLogFilter::data(const QModelIndex &index, int role) const
+QVariant AwayLogFilter::data(const QModelIndex& index, int role) const
{
if (role != MessageModel::FlagsRole)
return ChatMonitorFilter::data(index, role);
Q_OBJECT
public:
- AwayLogFilter(MessageModel *model, QObject *parent = nullptr);
+ AwayLogFilter(MessageModel* model, QObject* parent = nullptr);
- bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override;
+ bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override;
QString idString() const override { return "AwayLog"; }
- QVariant data(const QModelIndex &index, int role) const override;
+ QVariant data(const QModelIndex& index, int role) const override;
};
-
-#endif //AWAYLOGFILTER_H
+#endif // AWAYLOGFILTER_H
#include "chatlinemodel.h"
#include "chatscene.h"
-AwayLogView::AwayLogView(AwayLogFilter *filter, QWidget *parent)
+AwayLogView::AwayLogView(AwayLogFilter* filter, QWidget* parent)
: ChatMonitorView(filter, parent)
{
setWindowTitle(tr("Away Log"));
}
-
-void AwayLogView::addActionsToMenu(QMenu *menu, const QPointF &pos)
+void AwayLogView::addActionsToMenu(QMenu* menu, const QPointF& pos)
{
ChatView::addActionsToMenu(menu, pos);
if (!menu->isEmpty())
if (scene()->columnByScenePos(pos) == ChatLineModel::SenderColumn) {
menu->addSeparator();
- auto *showNetworkAction = new Action(tr("Show Network Name"), menu, this, &AwayLogView::showFieldsChanged);
+ auto* showNetworkAction = new Action(tr("Show Network Name"), menu, this, &AwayLogView::showFieldsChanged);
showNetworkAction->setCheckable(true);
showNetworkAction->setChecked(filter()->showFields() & ChatMonitorFilter::NetworkField);
showNetworkAction->setData(ChatMonitorFilter::NetworkField);
menu->addAction(showNetworkAction);
- auto *showBufferAction = new Action(tr("Show Buffer Name"), menu, this, &AwayLogView::showFieldsChanged);
+ auto* showBufferAction = new Action(tr("Show Buffer Name"), menu, this, &AwayLogView::showFieldsChanged);
showBufferAction->setCheckable(true);
showBufferAction->setChecked(filter()->showFields() & ChatMonitorFilter::BufferField);
showBufferAction->setData(ChatMonitorFilter::BufferField);
Q_OBJECT
public:
- AwayLogView(AwayLogFilter *filter, QWidget *parent = nullptr);
- void addActionsToMenu(QMenu *menu, const QPointF &pos) override;
+ AwayLogView(AwayLogFilter* filter, QWidget* parent = nullptr);
+ void addActionsToMenu(QMenu* menu, const QPointF& pos) override;
};
-
-#endif //AWAYLOGVIEW_H
+#endif // AWAYLOGVIEW_H
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include <QLayout>
+#include "bufferwidget.h"
+
#include <QKeyEvent>
+#include <QLayout>
#include <QMenu>
#include <QScrollBar>
#include "action.h"
#include "actioncollection.h"
-#include "bufferwidget.h"
#include "chatline.h"
#include "chatview.h"
#include "chatviewsearchbar.h"
#include "qtui.h"
#include "settings.h"
-BufferWidget::BufferWidget(QWidget *parent)
- : AbstractBufferContainer(parent),
- _chatViewSearchController(new ChatViewSearchController(this)),
- _autoMarkerLine(true),
- _autoMarkerLineOnLostFocus(true)
+BufferWidget::BufferWidget(QWidget* parent)
+ : AbstractBufferContainer(parent)
+ , _chatViewSearchController(new ChatViewSearchController(this))
+ , _autoMarkerLine(true)
+ , _autoMarkerLineOnLostFocus(true)
{
ui.setupUi(this);
layout()->setContentsMargins(0, 0, 0, 0);
_chatViewSearchController->setSearchMsgs(ui.searchBar->searchMsgsBox()->isChecked());
_chatViewSearchController->setSearchOnlyRegularMsgs(ui.searchBar->searchOnlyRegularMsgsBox()->isChecked());
- connect(ui.searchBar, &ChatViewSearchBar::searchChanged,
- _chatViewSearchController, &ChatViewSearchController::setSearchString);
- connect(ui.searchBar->caseSensitiveBox(), &QAbstractButton::toggled,
- _chatViewSearchController, &ChatViewSearchController::setCaseSensitive);
- connect(ui.searchBar->searchSendersBox(), &QAbstractButton::toggled,
- _chatViewSearchController, &ChatViewSearchController::setSearchSenders);
- connect(ui.searchBar->searchMsgsBox(), &QAbstractButton::toggled,
- _chatViewSearchController, &ChatViewSearchController::setSearchMsgs);
- connect(ui.searchBar->searchOnlyRegularMsgsBox(), &QAbstractButton::toggled,
- _chatViewSearchController, &ChatViewSearchController::setSearchOnlyRegularMsgs);
- connect(ui.searchBar->searchUpButton(), &QAbstractButton::clicked,
- _chatViewSearchController, &ChatViewSearchController::highlightPrev);
- connect(ui.searchBar->searchDownButton(), &QAbstractButton::clicked,
- _chatViewSearchController, &ChatViewSearchController::highlightNext);
+ connect(ui.searchBar, &ChatViewSearchBar::searchChanged, _chatViewSearchController, &ChatViewSearchController::setSearchString);
+ connect(ui.searchBar->caseSensitiveBox(), &QAbstractButton::toggled, _chatViewSearchController, &ChatViewSearchController::setCaseSensitive);
+ connect(ui.searchBar->searchSendersBox(), &QAbstractButton::toggled, _chatViewSearchController, &ChatViewSearchController::setSearchSenders);
+ connect(ui.searchBar->searchMsgsBox(), &QAbstractButton::toggled, _chatViewSearchController, &ChatViewSearchController::setSearchMsgs);
+ connect(ui.searchBar->searchOnlyRegularMsgsBox(),
+ &QAbstractButton::toggled,
+ _chatViewSearchController,
+ &ChatViewSearchController::setSearchOnlyRegularMsgs);
+ connect(ui.searchBar->searchUpButton(), &QAbstractButton::clicked, _chatViewSearchController, &ChatViewSearchController::highlightPrev);
+ connect(ui.searchBar->searchDownButton(), &QAbstractButton::clicked, _chatViewSearchController, &ChatViewSearchController::highlightNext);
connect(ui.searchBar, &ChatViewSearchBar::hidden, this, selectOverload<>(&QWidget::setFocus));
- connect(_chatViewSearchController, &ChatViewSearchController::newCurrentHighlight,
- this, &BufferWidget::scrollToHighlight);
+ connect(_chatViewSearchController, &ChatViewSearchController::newCurrentHighlight, this, &BufferWidget::scrollToHighlight);
- ActionCollection *coll = QtUi::actionCollection();
- coll->addActions({
- {"ZoomInChatView", new Action{icon::get("zoom-in"), tr("Zoom In"), coll, this, &BufferWidget::zoomIn, QKeySequence::ZoomIn}},
- {"ZoomOutChatView", new Action{icon::get("zoom-out"), tr("Zoom Out"), coll, this, &BufferWidget::zoomOut, QKeySequence::ZoomOut}},
- {"ZoomOriginalChatView", new Action{icon::get("zoom-original"), tr("Actual Size"), coll, this, &BufferWidget::zoomOriginal}},
- {"SetMarkerLineToBottom", new Action{tr("Set Marker Line"), coll, this, [this]() { setMarkerLine(); }, QKeySequence(Qt::CTRL + Qt::Key_R)}}
- });
+ ActionCollection* coll = QtUi::actionCollection();
+ coll->addActions(
+ {{"ZoomInChatView", new Action{icon::get("zoom-in"), tr("Zoom In"), coll, this, &BufferWidget::zoomIn, QKeySequence::ZoomIn}},
+ {"ZoomOutChatView", new Action{icon::get("zoom-out"), tr("Zoom Out"), coll, this, &BufferWidget::zoomOut, QKeySequence::ZoomOut}},
+ {"ZoomOriginalChatView", new Action{icon::get("zoom-original"), tr("Actual Size"), coll, this, &BufferWidget::zoomOriginal}},
+ {"SetMarkerLineToBottom",
+ new Action{tr("Set Marker Line"), coll, this, [this]() { setMarkerLine(); }, QKeySequence(Qt::CTRL + Qt::Key_R)}}});
coll = QtUi::actionCollection("Navigation");
- coll->addAction("JumpToMarkerLine", new Action{tr("Go to Marker Line"), coll, this, [this]() { jumpToMarkerLine(); }, QKeySequence(Qt::CTRL + Qt::Key_K)});
+ coll->addAction("JumpToMarkerLine",
+ new Action{tr("Go to Marker Line"), coll, this, [this]() { jumpToMarkerLine(); }, QKeySequence(Qt::CTRL + Qt::Key_K)});
ChatViewSettings s;
s.initAndNotify("AutoMarkerLine", this, &BufferWidget::setAutoMarkerLine, true);
s.initAndNotify("AutoMarkerLineOnLostFocus", this, &BufferWidget::setAutoMarkerLineOnLostFocus, true);
}
-
BufferWidget::~BufferWidget()
{
delete _chatViewSearchController;
_chatViewSearchController = nullptr;
}
-
-void BufferWidget::setAutoMarkerLine(const QVariant &v)
+void BufferWidget::setAutoMarkerLine(const QVariant& v)
{
_autoMarkerLine = v.toBool();
}
-void BufferWidget::setAutoMarkerLineOnLostFocus(const QVariant &v)
+void BufferWidget::setAutoMarkerLineOnLostFocus(const QVariant& v)
{
_autoMarkerLineOnLostFocus = v.toBool();
}
-
-AbstractChatView *BufferWidget::createChatView(BufferId id)
+AbstractChatView* BufferWidget::createChatView(BufferId id)
{
- ChatView *chatView;
+ ChatView* chatView;
chatView = new ChatView(id, this);
chatView->setBufferContainer(this);
_chatViews[id] = chatView;
return chatView;
}
-
void BufferWidget::removeChatView(BufferId id)
{
- QWidget *view = _chatViews.value(id, 0);
- if (!view) return;
+ QWidget* view = _chatViews.value(id, 0);
+ if (!view)
+ return;
ui.stackedWidget->removeWidget(view);
view->deleteLater();
_chatViews.take(id);
}
-
void BufferWidget::showChatView(BufferId id)
{
if (!id.isValid()) {
ui.stackedWidget->setCurrentWidget(ui.page);
}
else {
- auto *view = qobject_cast<ChatView *>(_chatViews.value(id));
+ auto* view = qobject_cast<ChatView*>(_chatViews.value(id));
Q_ASSERT(view);
ui.stackedWidget->setCurrentWidget(view);
_chatViewSearchController->setScene(view->scene());
}
}
-
-void BufferWidget::scrollToHighlight(QGraphicsItem *highlightItem)
+void BufferWidget::scrollToHighlight(QGraphicsItem* highlightItem)
{
- auto *view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+ auto* view = qobject_cast<ChatView*>(ui.stackedWidget->currentWidget());
if (view) {
view->centerOn(highlightItem);
}
}
-
void BufferWidget::zoomIn()
{
- auto *view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+ auto* view = qobject_cast<ChatView*>(ui.stackedWidget->currentWidget());
if (view)
view->zoomIn();
}
-
void BufferWidget::zoomOut()
{
- auto *view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+ auto* view = qobject_cast<ChatView*>(ui.stackedWidget->currentWidget());
if (view)
view->zoomOut();
}
-
void BufferWidget::zoomOriginal()
{
- auto *view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+ auto* view = qobject_cast<ChatView*>(ui.stackedWidget->currentWidget());
if (view)
view->zoomOriginal();
}
-
-void BufferWidget::addActionsToMenu(QMenu *menu, const QPointF &pos)
+void BufferWidget::addActionsToMenu(QMenu* menu, const QPointF& pos)
{
Q_UNUSED(pos);
- ActionCollection *coll = QtUi::actionCollection();
+ ActionCollection* coll = QtUi::actionCollection();
menu->addSeparator();
menu->addAction(coll->action("ZoomInChatView"));
menu->addAction(coll->action("ZoomOutChatView"));
menu->addAction(coll->action("ZoomOriginalChatView"));
}
-
-bool BufferWidget::eventFilter(QObject *watched, QEvent *event)
+bool BufferWidget::eventFilter(QObject* watched, QEvent* event)
{
if (event->type() != QEvent::KeyPress)
return false;
- auto *keyEvent = static_cast<QKeyEvent *>(event);
+ auto* keyEvent = static_cast<QKeyEvent*>(event);
- auto *inputLine = qobject_cast<MultiLineEdit *>(watched);
+ auto* inputLine = qobject_cast<MultiLineEdit*>(watched);
if (!inputLine)
return false;
if (keyEvent == QKeySequence::Copy) {
if (inputLine->hasSelectedText())
return false;
- auto *view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+ auto* view = qobject_cast<ChatView*>(ui.stackedWidget->currentWidget());
if (view)
view->scene()->selectionToClipboard();
return true;
case Qt::Key_PageUp:
case Qt::Key_PageDown:
// static cast to access public qobject::event
- return static_cast<QObject *>(ui.stackedWidget->currentWidget())->event(event);
+ return static_cast<QObject*>(ui.stackedWidget->currentWidget())->event(event);
default:
return false;
}
}
-
-void BufferWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
+void BufferWidget::currentChanged(const QModelIndex& current, const QModelIndex& previous)
{
- auto *prevView = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+ auto* prevView = qobject_cast<ChatView*>(ui.stackedWidget->currentWidget());
- AbstractBufferContainer::currentChanged(current, previous); // switch first to avoid a redraw
+ AbstractBufferContainer::currentChanged(current, previous); // switch first to avoid a redraw
// we need to hide the marker line if it's already/still at the bottom of the view (and not scrolled up)
- auto *curView = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+ auto* curView = qobject_cast<ChatView*>(ui.stackedWidget->currentWidget());
if (curView) {
BufferId curBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
if (curBufferId.isValid()) {
setMarkerLine(prevView, false);
}
-
-void BufferWidget::setMarkerLine(ChatView *view, bool allowGoingBack)
+void BufferWidget::setMarkerLine(ChatView* view, bool allowGoingBack)
{
if (!view)
- view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+ view = qobject_cast<ChatView*>(ui.stackedWidget->currentWidget());
if (!view)
return;
- ChatLine *lastLine = view->lastVisibleChatLine();
+ ChatLine* lastLine = view->lastVisibleChatLine();
if (lastLine) {
QModelIndex idx = lastLine->index();
MsgId msgId = idx.data(MessageModel::MsgIdRole).value<MsgId>();
}
}
-
-void BufferWidget::jumpToMarkerLine(ChatView *view, bool requestBacklog)
+void BufferWidget::jumpToMarkerLine(ChatView* view, bool requestBacklog)
{
if (!view)
- view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+ view = qobject_cast<ChatView*>(ui.stackedWidget->currentWidget());
if (!view)
return;
#pragma once
-#include "ui_bufferwidget.h"
-
#include "abstractbuffercontainer.h"
+#include "ui_bufferwidget.h"
+
class QGraphicsItem;
class ChatView;
class ChatViewSearchBar;
Q_OBJECT
public:
- BufferWidget(QWidget *parent);
+ BufferWidget(QWidget* parent);
~BufferWidget() override;
- bool eventFilter(QObject *watched, QEvent *event) override;
+ bool eventFilter(QObject* watched, QEvent* event) override;
- inline ChatViewSearchBar *searchBar() const { return ui.searchBar; }
- void addActionsToMenu(QMenu *, const QPointF &pos);
+ inline ChatViewSearchBar* searchBar() const { return ui.searchBar; }
+ void addActionsToMenu(QMenu*, const QPointF& pos);
virtual inline bool autoMarkerLineOnLostFocus() const { return _autoMarkerLineOnLostFocus; }
public slots:
- virtual void setMarkerLine(ChatView *view = nullptr, bool allowGoingBack = true);
- virtual void jumpToMarkerLine(ChatView *view = nullptr, bool requestBacklog = true);
+ virtual void setMarkerLine(ChatView* view = nullptr, bool allowGoingBack = true);
+ virtual void jumpToMarkerLine(ChatView* view = nullptr, bool requestBacklog = true);
protected:
- AbstractChatView *createChatView(BufferId) override;
+ AbstractChatView* createChatView(BufferId) override;
void removeChatView(BufferId) override;
inline bool autoMarkerLine() const override { return _autoMarkerLine; }
protected slots:
- void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) override;
+ void currentChanged(const QModelIndex& current, const QModelIndex& previous) override;
void showChatView(BufferId) override;
private slots:
- void scrollToHighlight(QGraphicsItem *highlightItem);
+ void scrollToHighlight(QGraphicsItem* highlightItem);
void zoomIn();
void zoomOut();
void zoomOriginal();
- void setAutoMarkerLine(const QVariant &);
- void setAutoMarkerLineOnLostFocus(const QVariant &);
+ void setAutoMarkerLine(const QVariant&);
+ void setAutoMarkerLineOnLostFocus(const QVariant&);
private:
Ui::BufferWidget ui;
- QHash<BufferId, QWidget *> _chatViews;
+ QHash<BufferId, QWidget*> _chatViews;
- ChatViewSearchController *_chatViewSearchController;
+ ChatViewSearchController* _chatViewSearchController;
bool _autoMarkerLine;
bool _autoMarkerLineOnLostFocus;
#include "channellistdlg.h"
-#include <QHeaderView>
#include <QHBoxLayout>
+#include <QHeaderView>
#include <QSpacerItem>
#include "client.h"
#include "clientirclisthelper.h"
#include "icon.h"
-ChannelListDlg::ChannelListDlg(QWidget *parent)
- : QDialog(parent),
- _ircListModel(this),
- _sortFilter(this)
+ChannelListDlg::ChannelListDlg(QWidget* parent)
+ : QDialog(parent)
+ , _ircListModel(this)
+ , _sortFilter(this)
{
_sortFilter.setSourceModel(&_ircListModel);
_sortFilter.setFilterCaseSensitivity(Qt::CaseInsensitive);
connect(ui.searchChannelsButton, &QAbstractButton::clicked, this, &ChannelListDlg::requestSearch);
connect(ui.channelNameLineEdit, &QLineEdit::returnPressed, this, &ChannelListDlg::requestSearch);
connect(ui.filterLineEdit, &QLineEdit::textChanged, &_sortFilter, &QSortFilterProxyModel::setFilterFixedString);
- connect(Client::ircListHelper(), &ClientIrcListHelper::channelListReceived,
- this, &ChannelListDlg::receiveChannelList);
+ connect(Client::ircListHelper(), &ClientIrcListHelper::channelListReceived, this, &ChannelListDlg::receiveChannelList);
connect(Client::ircListHelper(), &ClientIrcListHelper::finishedListReported, this, &ChannelListDlg::reportFinishedList);
connect(Client::ircListHelper(), &ClientIrcListHelper::errorReported, this, &ChannelListDlg::showError);
connect(ui.channelListView, &QAbstractItemView::activated, this, &ChannelListDlg::joinChannel);
updateInputFocus();
}
-
void ChannelListDlg::setNetwork(NetworkId netId)
{
if (_netId == netId)
showFilterLine(false);
}
-
-void ChannelListDlg::setChannelFilters(const QString &channelFilters)
+void ChannelListDlg::setChannelFilters(const QString& channelFilters)
{
// Enable advanced mode if searching
setAdvancedMode(!channelFilters.isEmpty());
ui.channelNameLineEdit->setText(channelFilters.trimmed());
}
-
void ChannelListDlg::requestSearch()
{
if (!_netId.isValid()) {
Client::ircListHelper()->requestChannelList(_netId, channelFilters);
}
-
-void ChannelListDlg::receiveChannelList(const NetworkId &netId, const QStringList &channelFilters, const QList<IrcListHelper::ChannelDescription> &channelList)
+void ChannelListDlg::receiveChannelList(const NetworkId& netId,
+ const QStringList& channelFilters,
+ const QList<IrcListHelper::ChannelDescription>& channelList)
{
Q_UNUSED(channelFilters)
if (netId != _netId)
updateInputFocus();
}
-
void ChannelListDlg::showFilterLine(bool show)
{
ui.line->setVisible(show);
ui.filterLineEdit->setVisible(show);
}
-
void ChannelListDlg::enableQuery(bool enable)
{
ui.channelNameLineEdit->setEnabled(enable);
ui.searchChannelsButton->setEnabled(enable);
}
-
void ChannelListDlg::setAdvancedMode(bool advanced)
{
_advancedMode = advanced;
ui.searchPatternLabel->setVisible(advanced);
}
-
void ChannelListDlg::updateInputFocus()
{
// Update keyboard focus to match what options are available. Prioritize the channel name
// editor as one likely won't need to filter when already limiting the list.
if (ui.channelNameLineEdit->isVisible()) {
ui.channelNameLineEdit->setFocus();
- } else if (ui.filterLineEdit->isVisible()) {
+ }
+ else if (ui.filterLineEdit->isVisible()) {
ui.filterLineEdit->setFocus();
}
}
-
void ChannelListDlg::showErrors(bool show)
{
if (!show) {
ui.errorTextEdit->setVisible(show);
}
-
void ChannelListDlg::reportFinishedList()
{
_listFinished = true;
}
-
-void ChannelListDlg::showError(const QString &error)
+void ChannelListDlg::showError(const QString& error)
{
showErrors(true);
ui.errorTextEdit->moveCursor(QTextCursor::End);
ui.errorTextEdit->insertPlainText(error + "\n");
}
-
-void ChannelListDlg::joinChannel(const QModelIndex &index)
+void ChannelListDlg::joinChannel(const QModelIndex& index)
{
- Client::instance()->userInput(BufferInfo::fakeStatusBuffer(_netId), QString("/JOIN %1").arg(index.sibling(index.row(), 0).data().toString()));
+ Client::instance()->userInput(BufferInfo::fakeStatusBuffer(_netId),
+ QString("/JOIN %1").arg(index.sibling(index.row(), 0).data().toString()));
}
#ifndef CHANNELLISTDLG_H
#define CHANNELLISTDLG_H
-#include "ui_channellistdlg.h"
+#include <QSortFilterProxyModel>
#include "irclisthelper.h"
#include "irclistmodel.h"
#include "types.h"
-#include <QSortFilterProxyModel>
+#include "ui_channellistdlg.h"
class QSpacerItem;
Q_OBJECT
public:
- ChannelListDlg(QWidget *parent = nullptr);
+ ChannelListDlg(QWidget* parent = nullptr);
void setNetwork(NetworkId netId);
*
* @param channelFilters Partial channel name to search for, or empty to not filter by name
*/
- void setChannelFilters(const QString &channelFilters);
+ void setChannelFilters(const QString& channelFilters);
public slots:
/**
void requestSearch();
protected slots:
- void receiveChannelList(const NetworkId &netId, const QStringList &channelFilters, const QList<IrcListHelper::ChannelDescription> &channelList);
+ void receiveChannelList(const NetworkId& netId,
+ const QStringList& channelFilters,
+ const QList<IrcListHelper::ChannelDescription>& channelList);
void reportFinishedList();
- void joinChannel(const QModelIndex &);
+ void joinChannel(const QModelIndex&);
private slots:
inline void toggleMode() { setAdvancedMode(!_advancedMode); }
- void showError(const QString &error);
+ void showError(const QString& error);
private:
void showFilterLine(bool show);
NetworkId _netId;
IrcListModel _ircListModel;
QSortFilterProxyModel _sortFilter;
- QSpacerItem *_simpleModeSpacer{nullptr};
+ QSpacerItem* _simpleModeSpacer{nullptr};
bool _advancedMode{false};
};
-
-#endif //CHANNELLIST_H
+#endif // CHANNELLIST_H
#include <QDesktopServices>
#include <QFontMetrics>
#include <QGraphicsSceneMouseEvent>
+#include <QMenu>
#include <QPainter>
#include <QPalette>
#include <QTextLayout>
-#include <QMenu>
#include "action.h"
#include "buffermodel.h"
#include "qtui.h"
#include "qtuistyle.h"
-ChatItem::ChatItem(const QRectF &boundingRect, ChatLine *parent)
- : _parent(parent),
- _boundingRect(boundingRect),
- _selectionMode(NoSelection),
- _selectionStart(-1),
- _cachedLayout(nullptr)
-{
-}
-
+ChatItem::ChatItem(const QRectF& boundingRect, ChatLine* parent)
+ : _parent(parent)
+ , _boundingRect(boundingRect)
+ , _selectionMode(NoSelection)
+ , _selectionStart(-1)
+ , _cachedLayout(nullptr)
+{}
ChatItem::~ChatItem()
{
delete _cachedLayout;
}
-
-ChatLine *ChatItem::chatLine() const
+ChatLine* ChatItem::chatLine() const
{
return _parent;
}
-
-ChatScene *ChatItem::chatScene() const
+ChatScene* ChatItem::chatScene() const
{
return chatLine()->chatScene();
}
-
-ChatView *ChatItem::chatView() const
+ChatView* ChatItem::chatView() const
{
return chatScene()->chatView();
}
-
-const QAbstractItemModel *ChatItem::model() const
+const QAbstractItemModel* ChatItem::model() const
{
return chatLine()->model();
}
-
int ChatItem::row() const
{
return chatLine()->row();
}
-
-QPointF ChatItem::mapToLine(const QPointF &p) const
+QPointF ChatItem::mapToLine(const QPointF& p) const
{
return p + pos();
}
-
-QPointF ChatItem::mapFromLine(const QPointF &p) const
+QPointF ChatItem::mapFromLine(const QPointF& p) const
{
return p - pos();
}
-
// relative to the ChatLine
-QPointF ChatItem::mapToScene(const QPointF &p) const
+QPointF ChatItem::mapToScene(const QPointF& p) const
{
return chatLine()->mapToScene(p /* + pos() */);
}
-
-QPointF ChatItem::mapFromScene(const QPointF &p) const
+QPointF ChatItem::mapFromScene(const QPointF& p) const
{
return chatLine()->mapFromScene(p) /* - pos() */;
}
-
QVariant ChatItem::data(int role) const
{
QModelIndex index = model()->index(row(), column());
return model()->data(index, role);
}
-
-QTextLayout *ChatItem::layout() const
+QTextLayout* ChatItem::layout() const
{
if (_cachedLayout)
return _cachedLayout;
return _cachedLayout;
}
-
void ChatItem::clearCache()
{
delete _cachedLayout;
_cachedLayout = nullptr;
}
-
-void ChatItem::initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const
+void ChatItem::initLayoutHelper(QTextLayout* layout, QTextOption::WrapMode wrapMode, Qt::Alignment alignment) const
{
Q_ASSERT(layout);
option.setAlignment(alignment);
layout->setTextOption(option);
- QList<QTextLayout::FormatRange> formatRanges
- = QtUi::style()->toTextLayoutList(formatList(), layout->text().length(), data(ChatLineModel::MsgLabelRole).value<UiStyle::MessageLabel>());
+ QList<QTextLayout::FormatRange> formatRanges = QtUi::style()
+ ->toTextLayoutList(formatList(),
+ layout->text().length(),
+ data(ChatLineModel::MsgLabelRole).value<UiStyle::MessageLabel>());
layout->setAdditionalFormats(formatRanges);
}
-
-void ChatItem::initLayout(QTextLayout *layout) const
+void ChatItem::initLayout(QTextLayout* layout) const
{
initLayoutHelper(layout, QTextOption::NoWrap);
doLayout(layout);
}
-
-void ChatItem::doLayout(QTextLayout *layout) const
+void ChatItem::doLayout(QTextLayout* layout) const
{
layout->beginLayout();
QTextLine line = layout->createLine();
layout->endLayout();
}
-
UiStyle::FormatList ChatItem::formatList() const
{
return data(MessageModel::FormatRole).value<UiStyle::FormatList>();
}
-
-qint16 ChatItem::posToCursor(const QPointF &posInLine) const
+qint16 ChatItem::posToCursor(const QPointF& posInLine) const
{
QPointF pos = mapFromLine(posInLine);
if (pos.y() > height())
return 0;
}
-
-void ChatItem::paintBackground(QPainter *painter)
+void ChatItem::paintBackground(QPainter* painter)
{
QVariant bgBrush;
if (_selectionMode == FullSelection)
painter->fillRect(boundingRect(), bgBrush.value<QBrush>());
}
-
// NOTE: This is not the most time-efficient implementation, but it saves space by not caching unnecessary data
// This is a deliberate trade-off. (-> selectFmt creation, data() call)
-void ChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
+void ChatItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
- Q_UNUSED(option); Q_UNUSED(widget);
+ Q_UNUSED(option);
+ Q_UNUSED(widget);
painter->save();
painter->setClipRect(boundingRect());
paintBackground(painter);
// uncomment partially or all of the following stuff:
//
// 0) alternativ painter color for debug stuff
-// if(row() % 2)
-// painter->setPen(Qt::red);
-// else
-// painter->setPen(Qt::blue);
-// 1) draw wordwrap points in the first line
-// if(column() == 2) {
-// ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
-// foreach(ChatLineModel::Word word, wrapList) {
-// if(word.endX > width())
-// break;
-// painter->drawLine(word.endX, 0, word.endX, height());
-// }
-// }
-// 2) draw MsgId over the time column
-// if(column() == 0) {
-// QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toLongLong());
-// QPointF bottomPoint = boundingRect().bottomLeft();
-// bottomPoint.ry() -= 2;
-// painter->drawText(bottomPoint, msgIdString);
-// }
-// 3) draw bounding rect
-// painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
+ // if(row() % 2)
+ // painter->setPen(Qt::red);
+ // else
+ // painter->setPen(Qt::blue);
+ // 1) draw wordwrap points in the first line
+ // if(column() == 2) {
+ // ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
+ // foreach(ChatLineModel::Word word, wrapList) {
+ // if(word.endX > width())
+ // break;
+ // painter->drawLine(word.endX, 0, word.endX, height());
+ // }
+ // }
+ // 2) draw MsgId over the time column
+ // if(column() == 0) {
+ // QString msgIdString = QString::number(data(MessageModel::MsgIdRole).value<MsgId>().toLongLong());
+ // QPointF bottomPoint = boundingRect().bottomLeft();
+ // bottomPoint.ry() -= 2;
+ // painter->drawText(bottomPoint, msgIdString);
+ // }
+ // 3) draw bounding rect
+ // painter->drawRect(_boundingRect.adjusted(0, 0, -1, -1));
painter->restore();
}
-
-void ChatItem::overlayFormat(UiStyle::FormatList &fmtList, quint16 start, quint16 end, UiStyle::FormatType overlayFmt) const
+void ChatItem::overlayFormat(UiStyle::FormatList& fmtList, quint16 start, quint16 end, UiStyle::FormatType overlayFmt) const
{
for (size_t i = 0; i < fmtList.size(); i++) {
int fmtStart = fmtList.at(i).first;
- int fmtEnd = (i < fmtList.size()-1 ? fmtList.at(i+1).first : data(MessageModel::DisplayRole).toString().length());
+ int fmtEnd = (i < fmtList.size() - 1 ? fmtList.at(i + 1).first : data(MessageModel::DisplayRole).toString().length());
if (fmtEnd <= start)
continue;
}
if (end < fmtEnd) {
fmtList.insert(fmtList.begin() + i, fmtList.at(i));
- fmtList[i+1].first = end;
+ fmtList[i + 1].first = end;
}
fmtList[i].second.type |= overlayFmt;
}
}
-
QVector<QTextLayout::FormatRange> ChatItem::additionalFormats() const
{
// Calculate formats to overlay (only) if there's a selection, and/or a hovered clickable
using Format = UiStyle::Format;
auto itemLabel = data(ChatLineModel::MsgLabelRole).value<Label>();
- const auto &fmtList = formatList();
+ const auto& fmtList = formatList();
- struct LabelFormat {
+ struct LabelFormat
+ {
quint16 offset;
Format format;
Label label;
// Transform formatList() into an extended list of LabelFormats
std::vector<LabelFormat> labelFmtList;
- std::transform(fmtList.cbegin(), fmtList.cend(), std::back_inserter(labelFmtList), [itemLabel](const std::pair<quint16, Format> &f) {
+ std::transform(fmtList.cbegin(), fmtList.cend(), std::back_inserter(labelFmtList), [itemLabel](const std::pair<quint16, Format>& f) {
return LabelFormat{f.first, f.second, itemLabel};
});
// Append dummy element to avoid special-casing handling the last real format
// Skip unaffected formats
for (; i < labelFmtList.size() - 1; ++i) {
- if (labelFmtList[i+1].offset > start)
+ if (labelFmtList[i + 1].offset > start)
break;
}
// Range start doesn't align; split affected format and let the index point to the newly inserted copy
// Apply label to formats fully affected
for (; i < labelFmtList.size() - 1; ++i) {
- if (labelFmtList[i+1].offset <= end) {
+ if (labelFmtList[i + 1].offset <= end) {
labelFmtList[i].label |= label;
continue;
}
// Last affected format, split if end of range doesn't align
- if (labelFmtList[i+1].offset > end) {
+ if (labelFmtList[i + 1].offset > end) {
labelFmtList.insert(labelFmtList.begin() + i, labelFmtList[i]);
labelFmtList[i].label |= label;
- labelFmtList[i+1].offset = end;
+ labelFmtList[i + 1].offset = end;
}
break;
}
for (size_t i = 0; i < labelFmtList.size() - 1; ++i) {
if (labelFmtList[i].label != itemLabel) {
additionalFormats << QtUi::style()->toTextLayoutList({std::make_pair(labelFmtList[i].offset, labelFmtList[i].format)},
- labelFmtList[i+1].offset,
+ labelFmtList[i + 1].offset,
labelFmtList[i].label);
}
}
return additionalFormats.toVector();
}
-
bool ChatItem::hasSelection() const
{
if (_selectionMode == NoSelection)
return _selectionStart != _selectionEnd;
}
-
QString ChatItem::selection() const
{
if (_selectionMode == FullSelection)
return QString();
}
-
void ChatItem::setSelection(SelectionMode mode, qint16 start, qint16 end)
{
_selectionMode = mode;
chatLine()->update();
}
-
void ChatItem::setFullSelection()
{
if (_selectionMode != FullSelection) {
}
}
-
void ChatItem::clearSelection()
{
if (_selectionMode != NoSelection) {
}
}
-
-void ChatItem::continueSelecting(const QPointF &pos)
+void ChatItem::continueSelecting(const QPointF& pos)
{
_selectionMode = PartialSelection;
_selectionEnd = posToCursor(pos);
chatLine()->update();
}
-
-bool ChatItem::isPosOverSelection(const QPointF &pos) const
+bool ChatItem::isPosOverSelection(const QPointF& pos) const
{
if (_selectionMode == FullSelection)
return true;
return false;
}
-
bool ChatItem::hasActiveClickable() const
{
return false;
}
-
std::pair<quint16, quint16> ChatItem::activeClickableRange() const
{
return {};
}
-
-QList<QRectF> ChatItem::findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive)
+QList<QRectF> ChatItem::findWords(const QString& searchWord, Qt::CaseSensitivity caseSensitive)
{
QList<QRectF> resultList;
- const QAbstractItemModel *model_ = model();
+ const QAbstractItemModel* model_ = model();
if (!model_)
return resultList;
searchIdx = plainText.indexOf(searchWord, searchIdx + 1, caseSensitive);
}
- foreach(int idx, indexList) {
+ foreach (int idx, indexList) {
QTextLine line = layout()->lineForTextPosition(idx);
qreal x = line.cursorToX(idx);
qreal width = line.cursorToX(idx + searchWord.count()) - x;
return resultList;
}
-
-void ChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode)
+void ChatItem::handleClick(const QPointF& pos, ChatScene::ClickMode clickMode)
{
// single clicks are already handled by the scene (for clearing the selection)
if (clickMode == ChatScene::DragStartClick) {
chatScene()->setSelectingItem(this);
_selectionStart = _selectionEnd = posToCursor(pos);
- _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
+ _selectionMode = NoSelection; // will be set to PartialSelection by mouseMoveEvent
chatLine()->update();
}
}
-
-void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
+void ChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
if (event->buttons() == Qt::LeftButton) {
if (boundingRect().contains(event->pos())) {
}
}
-
-void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
+void ChatItem::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
if (event->buttons() == Qt::LeftButton)
event->accept();
event->ignore();
}
-
-void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
+void ChatItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
if (_selectionMode != NoSelection && event->button() == Qt::LeftButton) {
chatScene()->selectionToClipboard(QClipboard::Selection);
event->ignore();
}
-
-void ChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos)
+void ChatItem::addActionsToMenu(QMenu* menu, const QPointF& pos)
{
Q_UNUSED(pos);
GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>());
}
-
// ************************************************************
// SenderChatItem
// ************************************************************
-void SenderChatItem::initLayout(QTextLayout *layout) const
+void SenderChatItem::initLayout(QTextLayout* layout) const
{
initLayoutHelper(layout, QTextOption::ManualWrap, Qt::AlignRight);
doLayout(layout);
}
-
-void SenderChatItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
+void SenderChatItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
- Q_UNUSED(option); Q_UNUSED(widget);
+ Q_UNUSED(option);
+ Q_UNUSED(widget);
painter->save();
painter->setClipRect(boundingRect());
paintBackground(painter);
gradient.setColorAt(1, Qt::white);
}
else {
- gradient.setStart(width()-10, 0);
+ gradient.setStart(width() - 10, 0);
gradient.setFinalStop(width(), 0);
gradient.setColorAt(0, Qt::white);
gradient.setColorAt(1, Qt::transparent);
}
- pixPainter.setCompositionMode(QPainter::CompositionMode_DestinationIn); // gradient's alpha gets applied to the pixmap
+ pixPainter.setCompositionMode(QPainter::CompositionMode_DestinationIn); // gradient's alpha gets applied to the pixmap
pixPainter.fillRect(pixmap.rect(), gradient);
painter->drawPixmap(pos(), pixmap);
}
painter->restore();
}
-
-void SenderChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode)
+void SenderChatItem::handleClick(const QPointF& pos, ChatScene::ClickMode clickMode)
{
if (clickMode == ChatScene::DoubleClick) {
BufferInfo curBufInfo = Client::networkModel()->bufferInfo(data(MessageModel::BufferIdRole).value<BufferId>());
ChatItem::handleClick(pos, clickMode);
}
-
// ************************************************************
// ContentsChatItem
// ************************************************************
ContentsChatItem::ActionProxy ContentsChatItem::_actionProxy;
-ContentsChatItem::ContentsChatItem(const QPointF &pos, const qreal &width, ChatLine *parent)
- : ChatItem(QRectF(pos, QSizeF(width, 0)), parent),
- _data(nullptr)
+ContentsChatItem::ContentsChatItem(const QPointF& pos, const qreal& width, ChatLine* parent)
+ : ChatItem(QRectF(pos, QSizeF(width, 0)), parent)
+ , _data(nullptr)
{
setPos(pos);
setGeometryByWidth(width);
}
-
-QFontMetricsF *ContentsChatItem::fontMetrics() const
+QFontMetricsF* ContentsChatItem::fontMetrics() const
{
- return QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second.type, UiStyle::MessageLabel::None);
+ return QtUi::style()->fontMetrics(data(ChatLineModel::FormatRole).value<UiStyle::FormatList>().at(0).second.type,
+ UiStyle::MessageLabel::None);
}
-
ContentsChatItem::~ContentsChatItem()
{
delete _data;
}
-
void ContentsChatItem::clearCache()
{
delete _data;
ChatItem::clearCache();
}
-
-ContentsChatItemPrivate *ContentsChatItem::privateData() const
+ContentsChatItemPrivate* ContentsChatItem::privateData() const
{
if (!_data) {
- auto *that = const_cast<ContentsChatItem *>(this);
+ auto* that = const_cast<ContentsChatItem*>(this);
that->_data = new ContentsChatItemPrivate(ClickableList::fromString(data(ChatLineModel::DisplayRole).toString()), that);
}
return _data;
}
-
qreal ContentsChatItem::setGeometryByWidth(qreal w)
{
// We use this for reloading layout info as well, so we can't bail out if the width doesn't change
WrapColumnFinder finder(this);
while (finder.nextWrapColumn(w) > 0)
lines++;
- qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
+ qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
qreal h = lines * spacing;
delete _data;
_data = nullptr;
return h;
}
-
-void ContentsChatItem::initLayout(QTextLayout *layout) const
+void ContentsChatItem::initLayout(QTextLayout* layout) const
{
initLayoutHelper(layout, QTextOption::WrapAtWordBoundaryOrAnywhere);
doLayout(layout);
}
-
-void ContentsChatItem::doLayout(QTextLayout *layout) const
+void ContentsChatItem::doLayout(QTextLayout* layout) const
{
ChatLineModel::WrapList wrapList = data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>();
- if (!wrapList.count()) return; // empty chatitem
+ if (!wrapList.count())
+ return; // empty chatitem
qreal h = 0;
- qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
+ qreal spacing = qMax(fontMetrics()->lineSpacing(), fontMetrics()->height()); // cope with negative leading()
WrapColumnFinder finder(this);
layout->beginLayout();
- forever {
+ forever
+ {
QTextLine line = layout->createLine();
if (!line.isValid())
break;
// Sometimes, setNumColumns will create a line that's too long (cf. Qt bug 238249)
// We verify this and try setting the width again, making it shorter each time until the lengths match.
// Dead fugly, but seems to work…
- for (int i = line.textLength()-1; i >= 0 && line.textLength() > num; i--) {
+ for (int i = line.textLength() - 1; i >= 0 && line.textLength() > num; i--) {
line.setNumColumns(i);
}
if (num != line.textLength()) {
layout->endLayout();
}
-
bool ContentsChatItem::hasActiveClickable() const
{
return privateData()->currentClickable.isValid();
}
-
std::pair<quint16, quint16> ContentsChatItem::activeClickableRange() const
{
- const auto &clickable = privateData()->currentClickable;
+ const auto& clickable = privateData()->currentClickable;
if (clickable.isValid()) {
return {clickable.start(), clickable.start() + clickable.length()};
}
return {};
}
-
-Clickable ContentsChatItem::clickableAt(const QPointF &pos) const
+Clickable ContentsChatItem::clickableAt(const QPointF& pos) const
{
return privateData()->clickables.atCursorPos(posToCursor(pos));
}
-
UiStyle::FormatList ContentsChatItem::formatList() const
{
UiStyle::FormatList fmtList = ChatItem::formatList();
return fmtList;
}
-
void ContentsChatItem::endHoverMode()
{
if (privateData()) {
}
}
-
-void ContentsChatItem::handleClick(const QPointF &pos, ChatScene::ClickMode clickMode)
+void ContentsChatItem::handleClick(const QPointF& pos, ChatScene::ClickMode clickMode)
{
if (clickMode == ChatScene::SingleClick) {
qint16 idx = posToCursor(pos);
qint16 cursor = posToCursor(pos);
qint16 start = str.lastIndexOf(QRegExp("\\W"), cursor) + 1;
qint16 end = qMin(str.indexOf(QRegExp("\\W"), cursor), str.length());
- if (end < 0) end = str.length();
+ if (end < 0)
+ end = str.length();
setSelectionStart(start);
setSelectionEnd(end);
}
ChatItem::handleClick(pos, clickMode);
}
-
-void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
+void ContentsChatItem::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
// mouse move events always mean we're not hovering anymore...
endHoverMode();
ChatItem::mouseMoveEvent(event);
}
-
-void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
+void ContentsChatItem::hoverLeaveEvent(QGraphicsSceneHoverEvent* event)
{
endHoverMode();
event->accept();
}
-
-void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
+void ContentsChatItem::hoverMoveEvent(QGraphicsSceneHoverEvent* event)
{
bool onClickable = false;
Clickable click = clickableAt(event->pos());
return;
}
}
- if (!onClickable) endHoverMode();
+ if (!onClickable)
+ endHoverMode();
event->accept();
}
-
-void ContentsChatItem::addActionsToMenu(QMenu *menu, const QPointF &pos)
+void ContentsChatItem::addActionsToMenu(QMenu* menu, const QPointF& pos)
{
if (privateData()->currentClickable.isValid()) {
Clickable click = privateData()->currentClickable;
switch (click.type()) {
- case Clickable::Url:
- {
+ case Clickable::Url: {
privateData()->activeClickable = click;
auto action = new Action{icon::get("edit-copy"), tr("Copy Link Address"), menu, &_actionProxy, &ActionProxy::copyLinkToClipboard};
- action->setData(QVariant::fromValue<void *>(this));
+ action->setData(QVariant::fromValue<void*>(this));
menu->addAction(action);
break;
}
- case Clickable::Channel:
- {
+ case Clickable::Channel: {
// Remove existing menu actions, they confuse us when right-clicking on a clickable
menu->clear();
QString name = data(ChatLineModel::DisplayRole).toString().mid(click.start(), click.length());
- GraphicalUi::contextMenuActionProvider()->addActions(menu, chatScene()->filter(), data(MessageModel::BufferIdRole).value<BufferId>(), name);
+ GraphicalUi::contextMenuActionProvider()->addActions(menu,
+ chatScene()->filter(),
+ data(MessageModel::BufferIdRole).value<BufferId>(),
+ name);
break;
}
default:
}
}
-
void ContentsChatItem::copyLinkToClipboard()
{
Clickable click = privateData()->activeClickable;
}
}
-
/******** WEB PREVIEW *****************************************************************************/
-void ContentsChatItem::showWebPreview(const Clickable &click)
+void ContentsChatItem::showWebPreview(const Clickable& click)
{
#if !defined HAVE_WEBKIT && !defined HAVE_WEBENGINE
Q_UNUSED(click);
#endif
}
-
void ContentsChatItem::clearWebPreview()
{
#if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
#endif
}
-
/*************************************************************************************************/
-ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem *_item)
- : item(_item),
- wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>()),
- wordidx(0),
- lineCount(0),
- choppedTrailing(0)
-{
-}
-
+ContentsChatItem::WrapColumnFinder::WrapColumnFinder(const ChatItem* _item)
+ : item(_item)
+ , wrapList(item->data(ChatLineModel::WrapListRole).value<ChatLineModel::WrapList>())
+ , wordidx(0)
+ , lineCount(0)
+ , choppedTrailing(0)
+{}
qint16 ContentsChatItem::WrapColumnFinder::nextWrapColumn(qreal width)
{
qint16 end = wrapList.count() - 1;
// check if the whole line fits
- if (wrapList.at(end).endX <= targetWidth) // || start == end)
+ if (wrapList.at(end).endX <= targetWidth) // || start == end)
return -1;
// check if we have a very long word that needs inter word wrap
while (true) {
if (start + 1 == end) {
wordidx = end;
- const ChatLineModel::Word &lastWord = wrapList.at(start); // the last word we were able to squeeze in
+ const ChatLineModel::Word& lastWord = wrapList.at(start); // the last word we were able to squeeze in
// both cases should be cought preliminary
- Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
- Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
+ Q_ASSERT(lastWord.endX <= targetWidth); // ensure that "start" really fits in
+ Q_ASSERT(end < wrapList.count()); // ensure that start isn't the last word
choppedTrailing += lastWord.trailing - (targetWidth - lastWord.endX);
return wrapList.at(wordidx).start;
return -1;
}
-
/*************************************************************************************************/
#ifndef CHATITEM_H_
#define CHATITEM_H_
+#include <utility>
+
#include <QAction>
#include <QObject>
+#include <QTextLayout>
#include "chatlinemodel.h"
#include "chatscene.h"
#include "clickable.h"
-#include "uistyle.h"
#include "qtui.h"
-
-#include <QTextLayout>
-#include <utility>
+#include "uistyle.h"
class ChatLine;
class ChatView;
{
protected:
// boundingRect is relative to the parent ChatLine
- ChatItem(const QRectF &boundingRect, ChatLine *parent);
+ ChatItem(const QRectF& boundingRect, ChatLine* parent);
virtual ~ChatItem();
public:
- const QAbstractItemModel *model() const;
- ChatLine *chatLine() const;
- ChatScene *chatScene() const;
- ChatView *chatView() const;
+ const QAbstractItemModel* model() const;
+ ChatLine* chatLine() const;
+ ChatScene* chatScene() const;
+ ChatView* chatView() const;
int row() const;
virtual ChatLineModel::ColumnType column() const = 0;
inline qreal x() const;
inline qreal y() const;
- QPointF mapToLine(const QPointF &) const;
- QPointF mapFromLine(const QPointF &) const;
- QPointF mapToScene(const QPointF &) const;
- QPointF mapFromScene(const QPointF &) const;
+ QPointF mapToLine(const QPointF&) const;
+ QPointF mapFromLine(const QPointF&) const;
+ QPointF mapToScene(const QPointF&) const;
+ QPointF mapFromScene(const QPointF&) const;
- virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr);
+ virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr);
virtual inline int type() const { return ChatScene::ChatItemType; }
QVariant data(int role) const;
QString selection() const;
void clearSelection();
void setFullSelection();
- void continueSelecting(const QPointF &pos);
+ void continueSelecting(const QPointF& pos);
bool hasSelection() const;
- bool isPosOverSelection(const QPointF &pos) const;
+ bool isPosOverSelection(const QPointF& pos) const;
- QList<QRectF> findWords(const QString &searchWord, Qt::CaseSensitivity caseSensitive);
+ QList<QRectF> findWords(const QString& searchWord, Qt::CaseSensitivity caseSensitive);
- virtual void addActionsToMenu(QMenu *menu, const QPointF &itemPos);
- virtual void handleClick(const QPointF &pos, ChatScene::ClickMode);
+ virtual void addActionsToMenu(QMenu* menu, const QPointF& itemPos);
+ virtual void handleClick(const QPointF& pos, ChatScene::ClickMode);
- void initLayoutHelper(QTextLayout *layout, QTextOption::WrapMode, Qt::Alignment = Qt::AlignLeft) const;
+ void initLayoutHelper(QTextLayout* layout, QTextOption::WrapMode, Qt::Alignment = Qt::AlignLeft) const;
//! Remove internally cached data
/** This removes e.g. the cached QTextLayout to avoid wasting space for nonvisible ChatLines
virtual void clearCache();
protected:
- enum SelectionMode {
+ enum SelectionMode
+ {
NoSelection,
PartialSelection,
FullSelection
};
- virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
- virtual void mousePressEvent(QGraphicsSceneMouseEvent *event);
- virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
- virtual void hoverEnterEvent(QGraphicsSceneHoverEvent *) {}
- virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent *) {}
- virtual void hoverMoveEvent(QGraphicsSceneHoverEvent *) {}
+ virtual void mouseMoveEvent(QGraphicsSceneMouseEvent* event);
+ virtual void mousePressEvent(QGraphicsSceneMouseEvent* event);
+ virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent* event);
+ virtual void hoverEnterEvent(QGraphicsSceneHoverEvent*) {}
+ virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent*) {}
+ virtual void hoverMoveEvent(QGraphicsSceneHoverEvent*) {}
- QTextLayout *layout() const;
+ QTextLayout* layout() const;
- virtual void initLayout(QTextLayout *layout) const;
- virtual void doLayout(QTextLayout *) const;
+ virtual void initLayout(QTextLayout* layout) const;
+ virtual void doLayout(QTextLayout*) const;
virtual UiStyle::FormatList formatList() const;
- void paintBackground(QPainter *);
+ void paintBackground(QPainter*);
virtual QVector<QTextLayout::FormatRange> additionalFormats() const;
- void overlayFormat(UiStyle::FormatList &fmtList, quint16 start, quint16 end, UiStyle::FormatType overlayFmt) const;
+ void overlayFormat(UiStyle::FormatList& fmtList, quint16 start, quint16 end, UiStyle::FormatType overlayFmt) const;
inline qint16 selectionStart() const { return _selectionStart; }
inline void setSelectionStart(qint16 start) { _selectionStart = start; }
virtual bool hasActiveClickable() const;
virtual std::pair<quint16, quint16> activeClickableRange() const;
- qint16 posToCursor(const QPointF &pos) const;
+ qint16 posToCursor(const QPointF& pos) const;
- inline void setGeometry(qreal width, qreal height) { clearCache(); _boundingRect.setSize(QSizeF(width, height)); }
- inline void setHeight(const qreal &height) { clearCache(); _boundingRect.setHeight(height); }
- inline void setWidth(const qreal &width) { clearCache(); _boundingRect.setWidth(width); }
- inline void setPos(const QPointF &pos) { _boundingRect.moveTopLeft(pos); }
+ inline void setGeometry(qreal width, qreal height)
+ {
+ clearCache();
+ _boundingRect.setSize(QSizeF(width, height));
+ }
+ inline void setHeight(const qreal& height)
+ {
+ clearCache();
+ _boundingRect.setHeight(height);
+ }
+ inline void setWidth(const qreal& width)
+ {
+ clearCache();
+ _boundingRect.setWidth(width);
+ }
+ inline void setPos(const QPointF& pos) { _boundingRect.moveTopLeft(pos); }
private:
- ChatLine *_parent;
+ ChatLine* _parent;
QRectF _boundingRect;
SelectionMode _selectionMode;
qint16 _selectionStart, _selectionEnd;
- mutable QTextLayout *_cachedLayout;
+ mutable QTextLayout* _cachedLayout;
// internal selection stuff
void setSelection(int start, int length);
friend class ChatLine;
};
-
// ************************************************************
// TimestampChatItem
// ************************************************************
class TimestampChatItem : public ChatItem
{
public:
- TimestampChatItem(const QRectF &boundingRect, ChatLine *parent) : ChatItem(boundingRect, parent) {}
+ TimestampChatItem(const QRectF& boundingRect, ChatLine* parent)
+ : ChatItem(boundingRect, parent)
+ {}
inline int type() const override { return ChatScene::TimestampChatItemType; }
inline ChatLineModel::ColumnType column() const override { return ChatLineModel::TimestampColumn; }
};
-
// ************************************************************
// SenderChatItem
// ************************************************************
class SenderChatItem : public ChatItem
{
public:
- SenderChatItem(const QRectF &boundingRect, ChatLine *parent) : ChatItem(boundingRect, parent) {}
+ SenderChatItem(const QRectF& boundingRect, ChatLine* parent)
+ : ChatItem(boundingRect, parent)
+ {}
inline ChatLineModel::ColumnType column() const override { return ChatLineModel::SenderColumn; }
- void handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) override;
+ void handleClick(const QPointF& pos, ChatScene::ClickMode clickMode) override;
protected:
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override;
+ void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override;
inline int type() const override { return ChatScene::SenderChatItemType; }
- void initLayout(QTextLayout *layout) const override;
+ void initLayout(QTextLayout* layout) const override;
};
-
// ************************************************************
// ContentsChatItem
// ************************************************************
Q_DECLARE_TR_FUNCTIONS(ContentsChatItem)
public:
- ContentsChatItem(const QPointF &pos, const qreal &width, ChatLine *parent);
+ ContentsChatItem(const QPointF& pos, const qreal& width, ChatLine* parent);
~ContentsChatItem() override;
inline int type() const override { return ChatScene::ContentsChatItemType; }
inline ChatLineModel::ColumnType column() const override { return ChatLineModel::ContentsColumn; }
- QFontMetricsF *fontMetrics() const;
+ QFontMetricsF* fontMetrics() const;
void clearCache() override;
protected:
- void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
- void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override;
- void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override;
- void handleClick(const QPointF &pos, ChatScene::ClickMode clickMode) override;
+ void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override;
+ void hoverLeaveEvent(QGraphicsSceneHoverEvent* event) override;
+ void hoverMoveEvent(QGraphicsSceneHoverEvent* event) override;
+ void handleClick(const QPointF& pos, ChatScene::ClickMode clickMode) override;
bool hasActiveClickable() const override;
std::pair<quint16, quint16> activeClickableRange() const override;
- void addActionsToMenu(QMenu *menu, const QPointF &itemPos) override;
+ void addActionsToMenu(QMenu* menu, const QPointF& itemPos) override;
virtual void copyLinkToClipboard();
- void initLayout(QTextLayout *layout) const override;
- void doLayout(QTextLayout *layout) const override;
+ void initLayout(QTextLayout* layout) const override;
+ void doLayout(QTextLayout* layout) const override;
UiStyle::FormatList formatList() const override;
private:
class ActionProxy;
class WrapColumnFinder;
- mutable ContentsChatItemPrivate *_data;
- ContentsChatItemPrivate *privateData() const;
+ mutable ContentsChatItemPrivate* _data;
+ ContentsChatItemPrivate* privateData() const;
- Clickable clickableAt(const QPointF &pos) const;
+ Clickable clickableAt(const QPointF& pos) const;
void endHoverMode();
- void showWebPreview(const Clickable &click);
+ void showWebPreview(const Clickable& click);
void clearWebPreview();
qreal setGeometryByWidth(qreal w);
- QFontMetricsF *_fontMetrics;
+ QFontMetricsF* _fontMetrics;
// we need a receiver for Action signals
static ActionProxy _actionProxy;
friend struct ContentsChatItemPrivate;
};
-
-struct ContentsChatItemPrivate {
- ContentsChatItem *contentsItem;
+struct ContentsChatItemPrivate
+{
+ ContentsChatItem* contentsItem;
ClickableList clickables;
Clickable currentClickable;
Clickable activeClickable;
- ContentsChatItemPrivate(ClickableList c, ContentsChatItem *parent) : contentsItem(parent), clickables(std::move(c)) {}
+ ContentsChatItemPrivate(ClickableList c, ContentsChatItem* parent)
+ : contentsItem(parent)
+ , clickables(std::move(c))
+ {}
};
class ContentsChatItem::WrapColumnFinder
{
public:
- WrapColumnFinder(const ChatItem *parent);
+ WrapColumnFinder(const ChatItem* parent);
qint16 nextWrapColumn(qreal width);
private:
- const ChatItem *item;
+ const ChatItem* item;
QTextLayout layout;
QTextLine line;
ChatLineModel::WrapList wrapList;
qreal choppedTrailing;
};
-
//! Acts as a proxy for Action signals targetted at a ContentsChatItem
/** Since a ChatItem is not a QObject, hence cannot receive signals, we use a static ActionProxy
* as a receiver instead. This avoids having to handle ChatItem actions (e.g. context menu entries)
* in the Action correctly.
* @return The ChatItem from which the sending Action originated
*/
- inline ContentsChatItem *item() const
+ inline ContentsChatItem* item() const
{
- return static_cast<ContentsChatItem *>(qobject_cast<QAction *>(sender())->data().value<void *>());
+ return static_cast<ContentsChatItem*>(qobject_cast<QAction*>(sender())->data().value<void*>());
}
};
-
/*************************************************************************************************/
// Inlines
-QRectF ChatItem::boundingRect() const { return _boundingRect; }
-qreal ChatItem::width() const { return _boundingRect.width(); }
-qreal ChatItem::height() const { return _boundingRect.height(); }
-QPointF ChatItem::pos() const { return _boundingRect.topLeft(); }
-qreal ChatItem::x() const { return pos().x(); }
-qreal ChatItem::y() const { return pos().y(); }
+QRectF ChatItem::boundingRect() const
+{
+ return _boundingRect;
+}
+qreal ChatItem::width() const
+{
+ return _boundingRect.width();
+}
+qreal ChatItem::height() const
+{
+ return _boundingRect.height();
+}
+QPointF ChatItem::pos() const
+{
+ return _boundingRect.topLeft();
+}
+qreal ChatItem::x() const
+{
+ return pos().x();
+}
+qreal ChatItem::y() const
+{
+ return pos().y();
+}
#endif
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "chatline.h"
+
#include <QDateTime>
#include <QGraphicsSceneMouseEvent>
#include <QString>
#include "bufferinfo.h"
#include "buffersyncer.h"
-#include "client.h"
#include "chatitem.h"
-#include "chatline.h"
#include "chatview.h"
+#include "client.h"
#include "columnhandleitem.h"
#include "messagemodel.h"
#include "networkmodel.h"
#include "qtuisettings.h"
#include "qtuistyle.h"
-ChatLine::ChatLine(int row, QAbstractItemModel *model,
- const qreal &width,
- const qreal ×tampWidth, const qreal &senderWidth, const qreal &contentsWidth,
- const QPointF &senderPos, const QPointF &contentsPos,
- QGraphicsItem *parent)
- : QGraphicsItem(parent),
- _row(row), // needs to be set before the items
- _model(model),
- _contentsItem(contentsPos, contentsWidth, this),
- _senderItem(QRectF(senderPos, QSizeF(senderWidth, _contentsItem.height())), this),
- _timestampItem(QRectF(0, 0, timestampWidth, _contentsItem.height()), this),
- _width(width),
- _height(_contentsItem.height()),
- _selection(0),
- _mouseGrabberItem(nullptr),
- _hoverItem(nullptr)
+ChatLine::ChatLine(int row,
+ QAbstractItemModel* model,
+ const qreal& width,
+ const qreal& timestampWidth,
+ const qreal& senderWidth,
+ const qreal& contentsWidth,
+ const QPointF& senderPos,
+ const QPointF& contentsPos,
+ QGraphicsItem* parent)
+ : QGraphicsItem(parent)
+ , _row(row)
+ , // needs to be set before the items
+ _model(model)
+ , _contentsItem(contentsPos, contentsWidth, this)
+ , _senderItem(QRectF(senderPos, QSizeF(senderWidth, _contentsItem.height())), this)
+ , _timestampItem(QRectF(0, 0, timestampWidth, _contentsItem.height()), this)
+ , _width(width)
+ , _height(_contentsItem.height())
+ , _selection(0)
+ , _mouseGrabberItem(nullptr)
+ , _hoverItem(nullptr)
{
Q_ASSERT(model);
QModelIndex index = model->index(row, ChatLineModel::ContentsColumn);
setHighlighted(index.data(MessageModel::FlagsRole).toInt() & Message::Highlight);
}
-
ChatLine::~ChatLine()
{
if (chatView())
chatView()->setHasCache(this, false);
}
-
-ChatItem *ChatLine::item(ChatLineModel::ColumnType column)
+ChatItem* ChatLine::item(ChatLineModel::ColumnType column)
{
switch (column) {
case ChatLineModel::TimestampColumn:
}
}
-
-ChatItem *ChatLine::itemAt(const QPointF &pos)
+ChatItem* ChatLine::itemAt(const QPointF& pos)
{
if (_contentsItem.boundingRect().contains(pos))
return &_contentsItem;
return nullptr;
}
-
void ChatLine::clearCache()
{
_timestampItem.clearCache();
_contentsItem.clearCache();
}
-
-void ChatLine::setMouseGrabberItem(ChatItem *item)
+void ChatLine::setMouseGrabberItem(ChatItem* item)
{
_mouseGrabberItem = item;
}
-
-bool ChatLine::sceneEvent(QEvent *event)
+bool ChatLine::sceneEvent(QEvent* event)
{
if (event->type() == QEvent::GrabMouse) {
// get mouse cursor pos relative to us
- ChatView *view = chatScene()->chatView();
+ ChatView* view = chatScene()->chatView();
QPointF linePos = mapFromScene(view->mapToScene(view->mapFromGlobal(QCursor::pos())));
setMouseGrabberItem(itemAt(linePos));
}
return QGraphicsItem::sceneEvent(event);
}
-
-void ChatLine::setFirstColumn(const qreal ×tampWidth, const qreal &senderWidth, const QPointF &senderPos)
+void ChatLine::setFirstColumn(const qreal& timestampWidth, const qreal& senderWidth, const QPointF& senderPos)
{
_timestampItem.setGeometry(timestampWidth, _height);
_senderItem.setGeometry(senderWidth, _height);
_senderItem.setPos(senderPos);
}
-
-void ChatLine::setSecondColumn(const qreal &senderWidth, const qreal &contentsWidth, const QPointF &contentsPos, qreal &linePos)
+void ChatLine::setSecondColumn(const qreal& senderWidth, const qreal& contentsWidth, const QPointF& contentsPos, qreal& linePos)
{
// linepos is the *bottom* position for the line
qreal height = _contentsItem.setGeometryByWidth(contentsWidth);
setPos(0, linePos);
}
-
-void ChatLine::setGeometryByWidth(const qreal &width, const qreal &contentsWidth, qreal &linePos)
+void ChatLine::setGeometryByWidth(const qreal& width, const qreal& contentsWidth, qreal& linePos)
{
// linepos is the *bottom* position for the line
qreal height = _contentsItem.setGeometryByWidth(contentsWidth);
_width = width;
}
- setPos(0, linePos); // set pos is _very_ cheap if nothing changes.
+ setPos(0, linePos); // set pos is _very_ cheap if nothing changes.
}
-
void ChatLine::setSelected(bool selected, ChatLineModel::ColumnType minColumn)
{
if (selected) {
}
}
-
void ChatLine::setHighlighted(bool highlighted)
{
- if (highlighted) _selection |= Highlighted;
- else _selection &= ~Highlighted;
+ if (highlighted)
+ _selection |= Highlighted;
+ else
+ _selection &= ~Highlighted;
update();
}
-
-void ChatLine::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
+void ChatLine::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
- const QAbstractItemModel *model_ = model();
+ const QAbstractItemModel* model_ = model();
QModelIndex myIdx = model_->index(row(), 0);
Message::Type type = (Message::Type)myIdx.data(MessageModel::TypeRole).toInt();
auto label = myIdx.data(ChatLineModel::MsgLabelRole).value<UiStyle::MessageLabel>();
contentsItem()->paint(painter, option, widget);
}
-
// We need to dispatch all mouse-related events to the appropriate (mouse grabbing) ChatItem
-ChatItem *ChatLine::mouseEventTargetItem(const QPointF &pos)
+ChatItem* ChatLine::mouseEventTargetItem(const QPointF& pos)
{
if (mouseGrabberItem())
return mouseGrabberItem();
return itemAt(pos);
}
-
-void ChatLine::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
+void ChatLine::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
- ChatItem *item = mouseEventTargetItem(event->pos());
+ ChatItem* item = mouseEventTargetItem(event->pos());
if (item)
item->mouseMoveEvent(event);
}
-
-void ChatLine::mousePressEvent(QGraphicsSceneMouseEvent *event)
+void ChatLine::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
- ChatItem *item = mouseEventTargetItem(event->pos());
+ ChatItem* item = mouseEventTargetItem(event->pos());
if (item)
item->mousePressEvent(event);
}
-
-void ChatLine::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
+void ChatLine::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
- ChatItem *item = mouseEventTargetItem(event->pos());
+ ChatItem* item = mouseEventTargetItem(event->pos());
if (item)
item->mouseReleaseEvent(event);
}
-
-void ChatLine::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
+void ChatLine::hoverEnterEvent(QGraphicsSceneHoverEvent* event)
{
- ChatItem *item = mouseEventTargetItem(event->pos());
+ ChatItem* item = mouseEventTargetItem(event->pos());
if (item && !_hoverItem) {
_hoverItem = item;
item->hoverEnterEvent(event);
}
}
-
-void ChatLine::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
+void ChatLine::hoverLeaveEvent(QGraphicsSceneHoverEvent* event)
{
if (_hoverItem) {
_hoverItem->hoverLeaveEvent(event);
}
}
-
-void ChatLine::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
+void ChatLine::hoverMoveEvent(QGraphicsSceneHoverEvent* event)
{
- ChatItem *item = mouseEventTargetItem(event->pos());
+ ChatItem* item = mouseEventTargetItem(event->pos());
if (item)
item->hoverMoveEvent(event);
}
#include <QGraphicsItem>
-#include "chatlinemodel.h"
#include "chatitem.h"
+#include "chatlinemodel.h"
#include "chatscene.h"
class ChatLine : public QGraphicsItem
{
public:
- ChatLine(int row, QAbstractItemModel *model,
- const qreal &width,
- const qreal ×tampWidth, const qreal &senderWidth, const qreal &contentsWidth,
- const QPointF &senderPos, const QPointF &contentsPos,
- QGraphicsItem *parent = nullptr);
+ ChatLine(int row,
+ QAbstractItemModel* model,
+ const qreal& width,
+ const qreal& timestampWidth,
+ const qreal& senderWidth,
+ const qreal& contentsWidth,
+ const QPointF& senderPos,
+ const QPointF& contentsPos,
+ QGraphicsItem* parent = nullptr);
~ChatLine() override;
inline int row() const { return _row; }
inline void setRow(int row) { _row = row; }
- inline const QAbstractItemModel *model() const { return _model; }
- inline ChatScene *chatScene() const { return qobject_cast<ChatScene *>(scene()); }
- inline ChatView *chatView() const { return chatScene() ? chatScene()->chatView() : nullptr; }
+ inline const QAbstractItemModel* model() const { return _model; }
+ inline ChatScene* chatScene() const { return qobject_cast<ChatScene*>(scene()); }
+ inline ChatView* chatView() const { return chatScene() ? chatScene()->chatView() : nullptr; }
inline qreal width() const { return _width; }
inline qreal height() const { return _height; }
- ChatItem *item(ChatLineModel::ColumnType);
- ChatItem *itemAt(const QPointF &pos);
- inline ChatItem *timestampItem() { return &_timestampItem; }
- inline ChatItem *senderItem() { return &_senderItem; }
- inline ContentsChatItem *contentsItem() { return &_contentsItem; }
-
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override;
- enum { Type = ChatScene::ChatLineType };
+ ChatItem* item(ChatLineModel::ColumnType);
+ ChatItem* itemAt(const QPointF& pos);
+ inline ChatItem* timestampItem() { return &_timestampItem; }
+ inline ChatItem* senderItem() { return &_senderItem; }
+ inline ContentsChatItem* contentsItem() { return &_contentsItem; }
+
+ void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override;
+ enum
+ {
+ Type = ChatScene::ChatLineType
+ };
inline int type() const override { return Type; }
// pos is relative to the parent ChatLine
- void setFirstColumn(const qreal ×tampWidth, const qreal &senderWidth, const QPointF &senderPos);
+ void setFirstColumn(const qreal& timestampWidth, const qreal& senderWidth, const QPointF& senderPos);
// setSecondColumn and setGeometryByWidth both also relocate the chatline.
// the _bottom_ position is passed via linePos. linePos is updated to the top of the chatLine.
- void setSecondColumn(const qreal &senderWidth, const qreal &contentsWidth, const QPointF &contentsPos, qreal &linePos);
- void setGeometryByWidth(const qreal &width, const qreal &contentsWidth, qreal &linePos);
+ void setSecondColumn(const qreal& senderWidth, const qreal& contentsWidth, const QPointF& contentsPos, qreal& linePos);
+ void setGeometryByWidth(const qreal& width, const qreal& contentsWidth, qreal& linePos);
void setSelected(bool selected, ChatLineModel::ColumnType minColumn = ChatLineModel::ContentsColumn);
void setHighlighted(bool highlighted);
void clearCache();
protected:
- bool sceneEvent(QEvent *event) override;
+ bool sceneEvent(QEvent* event) override;
// These need to be relayed to the appropriate ChatItem
- void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
- void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
- void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
- void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override;
- void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override;
- void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override;
+ void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override;
+ void mousePressEvent(QGraphicsSceneMouseEvent* event) override;
+ void mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override;
+ void hoverEnterEvent(QGraphicsSceneHoverEvent* event) override;
+ void hoverLeaveEvent(QGraphicsSceneHoverEvent* event) override;
+ void hoverMoveEvent(QGraphicsSceneHoverEvent* event) override;
- ChatItem *mouseEventTargetItem(const QPointF &pos);
+ ChatItem* mouseEventTargetItem(const QPointF& pos);
- inline ChatItem *mouseGrabberItem() const { return _mouseGrabberItem; }
- void setMouseGrabberItem(ChatItem *item);
+ inline ChatItem* mouseGrabberItem() const { return _mouseGrabberItem; }
+ void setMouseGrabberItem(ChatItem* item);
private:
int _row;
- QAbstractItemModel *_model;
+ QAbstractItemModel* _model;
ContentsChatItem _contentsItem;
SenderChatItem _senderItem;
TimestampChatItem _timestampItem;
qreal _width, _height;
- enum { ItemMask = 0x3f,
- Selected = 0x40,
- Highlighted = 0x80 };
+ enum
+ {
+ ItemMask = 0x3f,
+ Selected = 0x40,
+ Highlighted = 0x80
+ };
// _selection[1..0] ... Min Selected Column (See MessageModel::ColumnType)
// _selection[5..2] ... reserved for new column types
// _selection[6] ...... Selected
// _selection[7] ...... Highlighted
- quint8 _selection; // save space, so we put both the col and the flags into one byte
+ quint8 _selection; // save space, so we put both the col and the flags into one byte
- ChatItem *_mouseGrabberItem;
- ChatItem *_hoverItem;
+ ChatItem* _mouseGrabberItem;
+ ChatItem* _hoverItem;
};
-
#endif
***************************************************************************/
#include "chatlinemodel.h"
+
#include "qtui.h"
#include "qtuistyle.h"
-ChatLineModel::ChatLineModel(QObject *parent)
+ChatLineModel::ChatLineModel(QObject* parent)
: MessageModel(parent)
{
qRegisterMetaType<WrapList>("ChatLineModel::WrapList");
connect(QtUi::style(), &UiStyle::changed, this, &ChatLineModel::styleChanged);
}
-
// MessageModelItem *ChatLineModel::createMessageModelItem(const Message &msg) {
// return new ChatLineModelItem(msg);
// }
-void ChatLineModel::insertMessages__(int pos, const QList<Message> &messages)
+void ChatLineModel::insertMessages__(int pos, const QList<Message>& messages)
{
for (int i = 0; i < messages.count(); i++) {
_messageList.insert(pos, ChatLineModelItem(messages[i]));
}
}
-
Message ChatLineModel::takeMessageAt(int i)
{
Message msg = _messageList[i].message();
return msg;
}
-
void ChatLineModel::styleChanged()
{
- foreach(ChatLineModelItem item, _messageList) {
+ foreach (ChatLineModelItem item, _messageList) {
item.invalidateWrapList();
}
- emit dataChanged(index(0, 0), index(rowCount()-1, columnCount()-1));
+ emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1));
}
-
-QDataStream &operator<<(QDataStream &out, const ChatLineModel::WrapList wplist)
+QDataStream& operator<<(QDataStream& out, const ChatLineModel::WrapList wplist)
{
out << wplist.count();
ChatLineModel::WrapList::const_iterator it = wplist.begin();
return out;
}
-
-QDataStream &operator>>(QDataStream &in, ChatLineModel::WrapList &wplist)
+QDataStream& operator>>(QDataStream& in, ChatLineModel::WrapList& wplist)
{
quint16 cnt;
in >> cnt;
#ifndef CHATLINEMODEL_H_
#define CHATLINEMODEL_H_
-#include "messagemodel.h"
-
#include <QList>
+
#include "chatlinemodelitem.h"
+#include "messagemodel.h"
class ChatLineModel : public MessageModel
{
Q_OBJECT
public:
- enum ChatLineRole {
+ enum ChatLineRole
+ {
WrapListRole = MessageModel::UserRole,
MsgLabelRole,
SelectedBackgroundRole
};
- ChatLineModel(QObject *parent = nullptr);
+ ChatLineModel(QObject* parent = nullptr);
using Word = ChatLineModelItem::Word;
using WrapList = ChatLineModelItem::WrapList;
- inline const MessageModelItem *messageItemAt(int i) const override { return &_messageList[i]; }
+ inline const MessageModelItem* messageItemAt(int i) const override { return &_messageList[i]; }
+
protected:
-// virtual MessageModelItem *createMessageModelItem(const Message &);
+ // virtual MessageModelItem *createMessageModelItem(const Message &);
inline int messageCount() const override { return _messageList.count(); }
inline bool messagesIsEmpty() const override { return _messageList.isEmpty(); }
- inline MessageModelItem *messageItemAt(int i) override { return &_messageList[i]; }
- inline const MessageModelItem *firstMessageItem() const override { return &_messageList.first(); }
- inline MessageModelItem *firstMessageItem() override { return &_messageList.first(); }
- inline const MessageModelItem *lastMessageItem() const override { return &_messageList.last(); }
- inline MessageModelItem *lastMessageItem() override { return &_messageList.last(); }
- inline void insertMessage__(int pos, const Message &msg) override { _messageList.insert(pos, ChatLineModelItem(msg)); }
- void insertMessages__(int pos, const QList<Message> &) override;
+ inline MessageModelItem* messageItemAt(int i) override { return &_messageList[i]; }
+ inline const MessageModelItem* firstMessageItem() const override { return &_messageList.first(); }
+ inline MessageModelItem* firstMessageItem() override { return &_messageList.first(); }
+ inline const MessageModelItem* lastMessageItem() const override { return &_messageList.last(); }
+ inline MessageModelItem* lastMessageItem() override { return &_messageList.last(); }
+ inline void insertMessage__(int pos, const Message& msg) override { _messageList.insert(pos, ChatLineModelItem(msg)); }
+ void insertMessages__(int pos, const QList<Message>&) override;
inline void removeMessageAt(int i) override { _messageList.removeAt(i); }
inline void removeAllMessages() override { _messageList.clear(); }
Message takeMessageAt(int i) override;
QList<ChatLineModelItem> _messageList;
};
-
-QDataStream &operator<<(QDataStream &out, const ChatLineModel::WrapList);
-QDataStream &operator>>(QDataStream &in, ChatLineModel::WrapList &);
+QDataStream& operator<<(QDataStream& out, const ChatLineModel::WrapList);
+QDataStream& operator>>(QDataStream& in, ChatLineModel::WrapList&);
Q_DECLARE_METATYPE(ChatLineModel::WrapList)
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "chatlinemodelitem.h"
+
#include <QFontMetrics>
#include <QTextBoundaryFinder>
-#include "chatlinemodelitem.h"
#include "chatlinemodel.h"
#include "qtui.h"
#include "qtuistyle.h"
// This Struct is taken from Harfbuzz. We use it only to calc it's size.
// we use a shared memory region so we do not have to malloc a buffer area for every line
-using HB_CharAttributes_Dummy = struct {
- /*HB_LineBreakType*/ unsigned lineBreakType : 2;
- /*HB_Bool*/ unsigned whiteSpace : 1; /* A unicode whitespace character, except NBSP, ZWNBSP */
- /*HB_Bool*/ unsigned charStop : 1; /* Valid cursor position (for left/right arrow) */
- /*HB_Bool*/ unsigned wordBoundary : 1;
- /*HB_Bool*/ unsigned sentenceBoundary : 1;
- unsigned unused : 2;
+using HB_CharAttributes_Dummy = struct
+{
+ /*HB_LineBreakType*/ unsigned lineBreakType : 2;
+ /*HB_Bool*/ unsigned whiteSpace : 1; /* A unicode whitespace character, except NBSP, ZWNBSP */
+ /*HB_Bool*/ unsigned charStop : 1; /* Valid cursor position (for left/right arrow) */
+ /*HB_Bool*/ unsigned wordBoundary : 1;
+ /*HB_Bool*/ unsigned sentenceBoundary : 1;
+ unsigned unused : 2;
};
-unsigned char *ChatLineModelItem::TextBoundaryFinderBuffer = (unsigned char *)malloc(512 * sizeof(HB_CharAttributes_Dummy));
+unsigned char* ChatLineModelItem::TextBoundaryFinderBuffer = (unsigned char*)malloc(512 * sizeof(HB_CharAttributes_Dummy));
int ChatLineModelItem::TextBoundaryFinderBufferSize = 512 * (sizeof(HB_CharAttributes_Dummy) / sizeof(unsigned char));
// ****************************************
// the actual ChatLineModelItem
// ****************************************
-ChatLineModelItem::ChatLineModelItem(const Message &msg)
- : MessageModelItem(),
- _styledMsg(msg)
+ChatLineModelItem::ChatLineModelItem(const Message& msg)
+ : MessageModelItem()
+ , _styledMsg(msg)
{
if (!msg.sender().contains('!'))
_styledMsg.setFlags(msg.flags() |= Message::ServerMsg);
// Unfortunately, the missing Self flag for other message types can't easily be worked around.
}
-
-bool ChatLineModelItem::setData(int column, const QVariant &value, int role)
+bool ChatLineModelItem::setData(int column, const QVariant& value, int role)
{
switch (role) {
case MessageModel::FlagsRole:
}
}
-
QVariant ChatLineModelItem::data(int column, int role) const
{
if (role == ChatLineModel::MsgLabelRole)
return variant;
}
-
QVariant ChatLineModelItem::timestampData(int role) const
{
switch (role) {
case ChatLineModel::SelectedBackgroundRole:
return backgroundBrush(UiStyle::FormatType::Timestamp, true);
case ChatLineModel::FormatRole:
- return QVariant::fromValue<UiStyle::FormatList>({std::make_pair(quint16{0}, UiStyle::Format{UiStyle::formatType(_styledMsg.type()) | UiStyle::FormatType::Timestamp, {}, {}})});
+ return QVariant::fromValue<UiStyle::FormatList>(
+ {std::make_pair(quint16{0}, UiStyle::Format{UiStyle::formatType(_styledMsg.type()) | UiStyle::FormatType::Timestamp, {}, {}})});
}
return QVariant();
}
-
QVariant ChatLineModelItem::senderData(int role) const
{
switch (role) {
case ChatLineModel::SelectedBackgroundRole:
return backgroundBrush(UiStyle::FormatType::Sender, true);
case ChatLineModel::FormatRole:
- return QVariant::fromValue<UiStyle::FormatList>({std::make_pair(quint16{0}, UiStyle::Format{UiStyle::formatType(_styledMsg.type()) | UiStyle::FormatType::Sender, {}, {}})});
+ return QVariant::fromValue<UiStyle::FormatList>(
+ {std::make_pair(quint16{0}, UiStyle::Format{UiStyle::formatType(_styledMsg.type()) | UiStyle::FormatType::Sender, {}, {}})});
}
return QVariant();
}
-
QVariant ChatLineModelItem::contentsData(int role) const
{
switch (role) {
return QVariant();
}
-
UiStyle::MessageLabel ChatLineModelItem::messageLabel() const
{
using MessageLabel = UiStyle::MessageLabel;
return label;
}
-
QVariant ChatLineModelItem::backgroundBrush(UiStyle::FormatType subelement, bool selected) const
{
QTextCharFormat fmt = QtUi::style()->format({UiStyle::formatType(_styledMsg.type()) | subelement, {}, {}},
return QVariant();
}
-
void ChatLineModelItem::computeWrapList() const
{
QString text = _styledMsg.plainContents();
if (!length)
return;
- QList<ChatLineModel::Word> wplist; // use a temp list which we'll later copy into a QVector for efficiency
- QTextBoundaryFinder finder(QTextBoundaryFinder::Line, _styledMsg.plainContents().unicode(), length,
- TextBoundaryFinderBuffer, TextBoundaryFinderBufferSize);
+ QList<ChatLineModel::Word> wplist; // use a temp list which we'll later copy into a QVector for efficiency
+ QTextBoundaryFinder finder(QTextBoundaryFinder::Line,
+ _styledMsg.plainContents().unicode(),
+ length,
+ TextBoundaryFinderBuffer,
+ TextBoundaryFinderBufferSize);
int idx;
int oldidx = 0;
word.start = oldidx;
int wordend = idx;
for (; wordend > word.start; wordend--) {
- if (!text.at(wordend-1).isSpace())
+ if (!text.at(wordend - 1).isSpace())
break;
}
#pragma once
#include "messagemodel.h"
-
#include "uistyle.h"
class ChatLineModelItem : public MessageModelItem
{
public:
- ChatLineModelItem(const Message &);
+ ChatLineModelItem(const Message&);
QVariant data(int column, int role) const override;
- bool setData(int column, const QVariant &value, int role) override;
+ bool setData(int column, const QVariant& value, int role) override;
- inline const Message &message() const override { return _styledMsg; }
- inline const QDateTime ×tamp() const override { return _styledMsg.timestamp(); }
- inline const MsgId &msgId() const override { return _styledMsg.msgId(); }
- inline const BufferId &bufferId() const override { return _styledMsg.bufferId(); }
+ inline const Message& message() const override { return _styledMsg; }
+ inline const QDateTime& timestamp() const override { return _styledMsg.timestamp(); }
+ inline const MsgId& msgId() const override { return _styledMsg.msgId(); }
+ inline const BufferId& bufferId() const override { return _styledMsg.bufferId(); }
inline void setBufferId(BufferId bufferId) override { _styledMsg.setBufferId(bufferId); }
inline Message::Type msgType() const override { return _styledMsg.type(); }
inline Message::Flags msgFlags() const override { return _styledMsg.flags(); }
virtual inline void invalidateWrapList() { _wrapList.clear(); }
/// Used to store information about words to be used for wrapping
- struct Word {
+ struct Word
+ {
quint16 start;
qreal endX;
qreal width;
mutable WrapList _wrapList;
UiStyle::StyledMessage _styledMsg;
- static unsigned char *TextBoundaryFinderBuffer;
+ static unsigned char* TextBoundaryFinderBuffer;
static int TextBoundaryFinderBufferSize;
};
#include "chatmonitorfilter.h"
-#include "client.h"
#include "chatlinemodel.h"
-#include "networkmodel.h"
#include "chatviewsettings.h"
+#include "client.h"
#include "clientignorelistmanager.h"
+#include "networkmodel.h"
-ChatMonitorFilter::ChatMonitorFilter(MessageModel *model, QObject *parent)
+ChatMonitorFilter::ChatMonitorFilter(MessageModel* model, QObject* parent)
: MessageFilter(model, parent)
{
// Global configuration
_showHighlights = viewSettings.value(showHighlightsSettingsId, false).toBool();
_operationMode = viewSettings.value(operationModeSettingsId, ChatViewSettings::InvalidMode).toInt();
// read configured list of buffers to monitor/ignore
- foreach(QVariant v, viewSettings.value(buffersSettingsId, QVariant()).toList())
+ foreach (QVariant v, viewSettings.value(buffersSettingsId, QVariant()).toList())
_bufferIds << v.value<BufferId>();
_showBacklog = viewSettings.value(showBacklogSettingsId, true).toBool();
_includeRead = viewSettings.value(includeReadSettingsId, false).toBool();
viewSettings.notify(alwaysOwnSettingsId, this, &ChatMonitorFilter::alwaysOwnSettingChanged);
}
-
-bool ChatMonitorFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
+bool ChatMonitorFilter::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const
{
Q_UNUSED(sourceParent)
if (!_showBacklog)
return false;
- if (!_includeRead && Client::networkModel()->lastSeenMsgId(bufferId) >= sourceModel()->data(source_index, MessageModel::MsgIdRole).value<MsgId>())
+ if (!_includeRead
+ && Client::networkModel()->lastSeenMsgId(bufferId) >= sourceModel()->data(source_index, MessageModel::MsgIdRole).value<MsgId>())
return false;
}
// ChatMonitorSettingsPage
if (_showHighlights && flags & Message::Highlight)
- ; // pass
+ ; // pass
else if (_alwaysOwn && flags & Message::Self)
- ; // pass
+ ; // pass
else if (_operationMode == ChatViewSettings::OptOut && _bufferIds.contains(bufferId))
return false;
else if (_operationMode == ChatViewSettings::OptIn && !_bufferIds.contains(bufferId))
// ignorelist handling
// only match if message is not flagged as server msg
if (!(flags & Message::ServerMsg) && Client::ignoreListManager()
- && Client::ignoreListManager()->match(source_index.data(MessageModel::MessageRole).value<Message>(), Client::networkModel()->networkName(bufferId)))
+ && Client::ignoreListManager()->match(source_index.data(MessageModel::MessageRole).value<Message>(),
+ Client::networkModel()->networkName(bufferId)))
return false;
return true;
}
-
// override this to inject display of network and channel
-QVariant ChatMonitorFilter::data(const QModelIndex &index, int role) const
+QVariant ChatMonitorFilter::data(const QModelIndex& index, int role) const
{
if (index.column() != ChatLineModel::SenderColumn || role != ChatLineModel::DisplayRole)
return MessageFilter::data(index, role);
return QString("%1").arg(fields.join(":"));
}
-
void ChatMonitorFilter::addShowField(int field)
{
if (_showFields & field)
ChatViewSettings(idString()).setValue("ShowFields", _showFields | field);
}
-
void ChatMonitorFilter::removeShowField(int field)
{
if (!(_showFields & field))
ChatViewSettings(idString()).setValue("ShowFields", _showFields ^ field);
}
-
void ChatMonitorFilter::setShowOwnMessages(bool show)
{
if (_showOwnMessages == show)
ChatViewSettings(idString()).setValue("ShowOwnMsgs", show);
}
-
-void ChatMonitorFilter::showFieldsSettingChanged(const QVariant &newValue)
+void ChatMonitorFilter::showFieldsSettingChanged(const QVariant& newValue)
{
int newFields = newValue.toInt();
if (_showFields == newFields)
emit dataChanged(index(0, ChatLineModel::SenderColumn), index(rows - 1, ChatLineModel::SenderColumn));
}
-
-void ChatMonitorFilter::showOwnMessagesSettingChanged(const QVariant &newValue)
+void ChatMonitorFilter::showOwnMessagesSettingChanged(const QVariant& newValue)
{
_showOwnMessages = newValue.toBool();
}
-void ChatMonitorFilter::alwaysOwnSettingChanged(const QVariant &newValue) {
+void ChatMonitorFilter::alwaysOwnSettingChanged(const QVariant& newValue)
+{
_alwaysOwn = newValue.toBool();
}
-void ChatMonitorFilter::showHighlightsSettingChanged(const QVariant &newValue)
+void ChatMonitorFilter::showHighlightsSettingChanged(const QVariant& newValue)
{
_showHighlights = newValue.toBool();
}
-
-void ChatMonitorFilter::operationModeSettingChanged(const QVariant &newValue)
+void ChatMonitorFilter::operationModeSettingChanged(const QVariant& newValue)
{
_operationMode = newValue.toInt();
}
-
-void ChatMonitorFilter::buffersSettingChanged(const QVariant &newValue)
+void ChatMonitorFilter::buffersSettingChanged(const QVariant& newValue)
{
_bufferIds.clear();
- foreach(QVariant v, newValue.toList()) {
+ foreach (QVariant v, newValue.toList()) {
_bufferIds << v.value<BufferId>();
}
invalidateFilter();
}
-void ChatMonitorFilter::showBacklogSettingChanged(const QVariant &newValue) {
+void ChatMonitorFilter::showBacklogSettingChanged(const QVariant& newValue)
+{
_showBacklog = newValue.toBool();
}
-void ChatMonitorFilter::includeReadSettingChanged(const QVariant &newValue) {
+void ChatMonitorFilter::includeReadSettingChanged(const QVariant& newValue)
+{
_includeRead = newValue.toBool();
}
-void ChatMonitorFilter::showSenderBracketsSettingChanged(const QVariant &newValue)
+void ChatMonitorFilter::showSenderBracketsSettingChanged(const QVariant& newValue)
{
_showSenderBrackets = newValue.toBool();
}
Q_OBJECT
public:
- enum SenderFields {
+ enum SenderFields
+ {
NoField = 0x00,
NetworkField = 0x01,
BufferField = 0x02,
AllFields = 0xff
};
- ChatMonitorFilter(MessageModel *model, QObject *parent = nullptr);
+ ChatMonitorFilter(MessageModel* model, QObject* parent = nullptr);
- bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override;
+ bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override;
QString idString() const override { return "ChatMonitor"; }
- QVariant data(const QModelIndex &index, int role) const override;
+ QVariant data(const QModelIndex& index, int role) const override;
int showFields() const { return _showFields; }
bool showOwnMessages() const { return _showOwnMessages; }
void setShowOwnMessages(bool show);
private slots:
- void showFieldsSettingChanged(const QVariant &newValue);
- void showOwnMessagesSettingChanged(const QVariant &newValue);
- void alwaysOwnSettingChanged(const QVariant &newValue);
- void showHighlightsSettingChanged(const QVariant &newValue);
- void operationModeSettingChanged(const QVariant &newValue);
- void buffersSettingChanged(const QVariant &newValue);
- void showBacklogSettingChanged(const QVariant &newValue);
- void includeReadSettingChanged(const QVariant &newValue);
+ void showFieldsSettingChanged(const QVariant& newValue);
+ void showOwnMessagesSettingChanged(const QVariant& newValue);
+ void alwaysOwnSettingChanged(const QVariant& newValue);
+ void showHighlightsSettingChanged(const QVariant& newValue);
+ void operationModeSettingChanged(const QVariant& newValue);
+ void buffersSettingChanged(const QVariant& newValue);
+ void showBacklogSettingChanged(const QVariant& newValue);
+ void includeReadSettingChanged(const QVariant& newValue);
/**
* Updates the local setting cache of whether or not to show sender brackets
*
* @param[in] newValue If true, sender brackets are enabled, otherwise false.
*/
- void showSenderBracketsSettingChanged(const QVariant &newValue);
+ void showSenderBracketsSettingChanged(const QVariant& newValue);
private:
int _showFields;
int _operationMode;
bool _showBacklog;
bool _includeRead;
- bool _showSenderBrackets; /// If true, show brackets around sender names
+ bool _showSenderBrackets; /// If true, show brackets around sender names
};
#include "chatmonitorview.h"
#include <QAction>
-#include <QMenu>
#include <QContextMenuEvent>
+#include <QMenu>
#include "action.h"
#include "buffermodel.h"
-#include "chatmonitorfilter.h"
-#include "chatlinemodel.h"
#include "chatitem.h"
+#include "chatlinemodel.h"
+#include "chatmonitorfilter.h"
#include "chatscene.h"
#include "client.h"
#include "clientignorelistmanager.h"
#include "icon.h"
-#include "networkmodel.h"
#include "messagemodel.h"
+#include "networkmodel.h"
#include "qtuisettings.h"
#include "settingspagedlg.h"
+
#include "settingspages/chatmonitorsettingspage.h"
-ChatMonitorView::ChatMonitorView(ChatMonitorFilter *filter, QWidget *parent)
- : ChatView(filter, parent),
- _filter(filter)
+ChatMonitorView::ChatMonitorView(ChatMonitorFilter* filter, QWidget* parent)
+ : ChatView(filter, parent)
+ , _filter(filter)
{
scene()->setSenderCutoffMode(ChatScene::CutoffLeft);
// The normal message prefixes get replaced by the network and buffer name. Re-add brackets for
connect(Client::instance(), &Client::coreConnectionStateChanged, this, &ChatMonitorView::coreConnectionStateChanged);
}
-
-void ChatMonitorView::addActionsToMenu(QMenu *menu, const QPointF &pos)
+void ChatMonitorView::addActionsToMenu(QMenu* menu, const QPointF& pos)
{
ChatView::addActionsToMenu(menu, pos);
menu->addSeparator();
menu->addAction(new Action(icon::get("configure"), tr("Configure..."), menu, this, &ChatMonitorView::showSettingsPage));
}
-
-void ChatMonitorView::mouseDoubleClickEvent(QMouseEvent *event)
+void ChatMonitorView::mouseDoubleClickEvent(QMouseEvent* event)
{
if (scene()->columnByScenePos(event->pos()) != ChatLineModel::SenderColumn) {
ChatView::mouseDoubleClickEvent(event);
return;
}
- ChatItem *chatItem = scene()->chatItemAt(mapToScene(event->pos()));
+ ChatItem* chatItem = scene()->chatItemAt(mapToScene(event->pos()));
if (!chatItem) {
event->ignore();
return;
Client::bufferModel()->switchToBuffer(bufferId);
}
-
void ChatMonitorView::showFieldsChanged(bool checked)
{
- auto *showAction = qobject_cast<QAction *>(sender());
+ auto* showAction = qobject_cast<QAction*>(sender());
if (!showAction)
return;
_filter->removeShowField(showAction->data().toInt());
}
-
void ChatMonitorView::showSettingsPage()
{
SettingsPageDlg dlg(new ChatMonitorSettingsPage(), this);
dlg.exec();
}
-
// connect only after client is synced to core since ChatMonitorView is created before
// the ignoreListManager
void ChatMonitorView::coreConnectionStateChanged(bool connected)
Q_OBJECT
public:
- ChatMonitorView(ChatMonitorFilter *filter, QWidget *parent);
+ ChatMonitorView(ChatMonitorFilter* filter, QWidget* parent);
void showFieldsChanged(bool checked);
protected:
- void addActionsToMenu(QMenu *menu, const QPointF &pos) override;
- void mouseDoubleClickEvent(QMouseEvent *event) override;
+ void addActionsToMenu(QMenu* menu, const QPointF& pos) override;
+ void mouseDoubleClickEvent(QMouseEvent* event) override;
private slots:
void showSettingsPage();
virtual void coreConnectionStateChanged(bool connected);
protected:
- inline ChatMonitorFilter *filter() const { return _filter; }
+ inline ChatMonitorFilter* filter() const { return _filter; }
private:
- ChatMonitorFilter *_filter;
+ ChatMonitorFilter* _filter;
};
-
-#endif //CHATMONITORVIEW_H
+#endif // CHATMONITORVIEW_H
#include <QUrl>
#ifdef HAVE_WEBENGINE
-# include <QWebEngineView>
+# include <QWebEngineView>
#elif defined HAVE_WEBKIT
-# include <QWebView>
+# include <QWebView>
#endif
#include "chatitem.h"
const qreal minContentsWidth = 200;
-ChatScene::ChatScene(QAbstractItemModel *model, QString idString, qreal width, ChatView *parent)
- : QGraphicsScene(0, 0, width, 0, (QObject *)parent),
- _chatView(parent),
- _idString(std::move(idString)),
- _model(model),
- _singleBufferId(BufferId()),
- _sceneRect(0, 0, width, 0),
- _firstLineRow(-1),
- _viewportHeight(0),
- _markerLine(new MarkerLineItem(width)),
- _markerLineVisible(false),
- _markerLineValid(false),
- _markerLineJumpPending(false),
- _cutoffMode(CutoffRight),
- _alwaysBracketSender(false),
- _selectingItem(nullptr),
- _selectionStart(-1),
- _isSelecting(false),
- _clickMode(NoClick),
- _clickHandled(true),
- _leftButtonPressed(false)
+ChatScene::ChatScene(QAbstractItemModel* model, QString idString, qreal width, ChatView* parent)
+ : QGraphicsScene(0, 0, width, 0, (QObject*)parent)
+ , _chatView(parent)
+ , _idString(std::move(idString))
+ , _model(model)
+ , _singleBufferId(BufferId())
+ , _sceneRect(0, 0, width, 0)
+ , _firstLineRow(-1)
+ , _viewportHeight(0)
+ , _markerLine(new MarkerLineItem(width))
+ , _markerLineVisible(false)
+ , _markerLineValid(false)
+ , _markerLineJumpPending(false)
+ , _cutoffMode(CutoffRight)
+ , _alwaysBracketSender(false)
+ , _selectingItem(nullptr)
+ , _selectionStart(-1)
+ , _isSelecting(false)
+ , _clickMode(NoClick)
+ , _clickHandled(true)
+ , _leftButtonPressed(false)
{
- auto *filter = qobject_cast<MessageFilter *>(model);
+ auto* filter = qobject_cast<MessageFilter*>(model);
if (filter && filter->isSingleBufferFilter()) {
_singleBufferId = filter->singleBufferId();
}
if (model->rowCount() > 0)
rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
- connect(model, &QAbstractItemModel::rowsInserted,
- this, &ChatScene::rowsInserted);
- connect(model, &QAbstractItemModel::rowsAboutToBeRemoved,
- this, &ChatScene::rowsAboutToBeRemoved);
- connect(model, &QAbstractItemModel::rowsRemoved,
- this, &ChatScene::rowsRemoved);
+ connect(model, &QAbstractItemModel::rowsInserted, this, &ChatScene::rowsInserted);
+ connect(model, &QAbstractItemModel::rowsAboutToBeRemoved, this, &ChatScene::rowsAboutToBeRemoved);
+ connect(model, &QAbstractItemModel::rowsRemoved, this, &ChatScene::rowsRemoved);
connect(model, &QAbstractItemModel::dataChanged, this, &ChatScene::dataChanged);
#if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
setItemIndexMethod(QGraphicsScene::NoIndex);
}
-
-ChatView *ChatScene::chatView() const
+ChatView* ChatScene::chatView() const
{
return _chatView;
}
-
-ColumnHandleItem *ChatScene::firstColumnHandle() const
+ColumnHandleItem* ChatScene::firstColumnHandle() const
{
return _firstColHandle;
}
-
-ColumnHandleItem *ChatScene::secondColumnHandle() const
+ColumnHandleItem* ChatScene::secondColumnHandle() const
{
return _secondColHandle;
}
void ChatScene::resetColumnWidths()
{
- //make sure first column is at least 80 px wide, second 120 px
- int firstColHandlePos = qMax(_defaultFirstColHandlePos,
- 80);
- int secondColHandlePos = qMax(_defaultSecondColHandlePos,
- firstColHandlePos + 120);
+ // make sure first column is at least 80 px wide, second 120 px
+ int firstColHandlePos = qMax(_defaultFirstColHandlePos, 80);
+ int secondColHandlePos = qMax(_defaultSecondColHandlePos, firstColHandlePos + 120);
_firstColHandle->setXPos(firstColHandlePos);
_secondColHandle->setXPos(secondColHandlePos);
}
-ChatLine *ChatScene::chatLine(MsgId msgId, bool matchExact, bool ignoreDayChange) const
+ChatLine* ChatScene::chatLine(MsgId msgId, bool matchExact, bool ignoreDayChange) const
{
if (!_lines.count())
return nullptr;
- QList<ChatLine *>::ConstIterator start = _lines.begin();
- QList<ChatLine *>::ConstIterator end = _lines.end();
- QList<ChatLine *>::ConstIterator middle;
+ QList<ChatLine*>::ConstIterator start = _lines.begin();
+ QList<ChatLine*>::ConstIterator end = _lines.end();
+ QList<ChatLine*>::ConstIterator middle;
auto n = int(end - start);
int half;
if (matchExact)
return nullptr;
- if (start == _lines.begin()) // not (yet?) in our scene
+ if (start == _lines.begin()) // not (yet?) in our scene
return nullptr;
// if we didn't find the exact msgId, take the next-lower one (this makes sense for lastSeen)
- if (start == end) { // higher than last element
+ if (start == end) { // higher than last element
if (!ignoreDayChange)
return _lines.last();
- for (int i = _lines.count() -1; i >= 0; i--) {
+ for (int i = _lines.count() - 1; i >= 0; i--) {
if (_lines.at(i)->msgType() != Message::DayChange)
return _lines.at(i);
}
do {
if ((*(--start))->msgType() != Message::DayChange)
return *start;
- }
- while (start != _lines.begin());
+ } while (start != _lines.begin());
return nullptr;
}
-
-ChatItem *ChatScene::chatItemAt(const QPointF &scenePos) const
+ChatItem* ChatScene::chatItemAt(const QPointF& scenePos) const
{
- foreach(QGraphicsItem *item, items(scenePos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder)) {
- auto *line = qgraphicsitem_cast<ChatLine *>(item);
+ foreach (QGraphicsItem* item, items(scenePos, Qt::IntersectsItemBoundingRect, Qt::AscendingOrder)) {
+ auto* line = qgraphicsitem_cast<ChatLine*>(item);
if (line)
return line->itemAt(line->mapFromScene(scenePos));
}
return nullptr;
}
-
-bool ChatScene::containsBuffer(const BufferId &id) const
+bool ChatScene::containsBuffer(const BufferId& id) const
{
- auto *filter = qobject_cast<MessageFilter *>(model());
+ auto* filter = qobject_cast<MessageFilter*>(model());
if (filter)
return filter->containsBuffer(id);
else
return false;
}
-
void ChatScene::setMarkerLineVisible(bool visible)
{
_markerLineVisible = visible;
markerLine()->setVisible(false);
}
-
void ChatScene::setMarkerLine(MsgId msgId)
{
if (!isSingleBufferScene())
msgId = Client::markerLine(singleBufferId());
if (msgId.isValid()) {
- ChatLine *line = chatLine(msgId, false, true);
+ ChatLine* line = chatLine(msgId, false, true);
if (line) {
markerLine()->setChatLine(line);
// if this was the last line, we won't see it because it's outside the sceneRect
markerLine()->setVisible(false);
}
-
void ChatScene::jumpToMarkerLine(bool requestBacklog)
{
if (!isSingleBufferScene())
}
}
-
-void ChatScene::rowsInserted(const QModelIndex &index, int start, int end)
+void ChatScene::rowsInserted(const QModelIndex& index, int start, int end)
{
Q_UNUSED(index);
-// QModelIndex sidx = model()->index(start, 2);
-// QModelIndex eidx = model()->index(end, 2);
-// qDebug() << "rowsInserted:";
-// if(start > 0) {
-// QModelIndex ssidx = model()->index(start - 1, 2);
-// qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
-// << ssidx.data(Qt::DisplayRole).toString();
-// }
-// qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
-// << sidx.data(Qt::DisplayRole).toString();
-// qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
-// << eidx.data(Qt::DisplayRole).toString();
-// if(end + 1 < model()->rowCount()) {
-// QModelIndex eeidx = model()->index(end + 1, 2);
-// qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
-// << eeidx.data(Qt::DisplayRole).toString();
-// }
+ // QModelIndex sidx = model()->index(start, 2);
+ // QModelIndex eidx = model()->index(end, 2);
+ // qDebug() << "rowsInserted:";
+ // if(start > 0) {
+ // QModelIndex ssidx = model()->index(start - 1, 2);
+ // qDebug() << "Start--:" << start - 1 << ssidx.data(MessageModel::MsgIdRole).value<MsgId>()
+ // << ssidx.data(Qt::DisplayRole).toString();
+ // }
+ // qDebug() << "Start:" << start << sidx.data(MessageModel::MsgIdRole).value<MsgId>()
+ // << sidx.data(Qt::DisplayRole).toString();
+ // qDebug() << "End:" << end << eidx.data(MessageModel::MsgIdRole).value<MsgId>()
+ // << eidx.data(Qt::DisplayRole).toString();
+ // if(end + 1 < model()->rowCount()) {
+ // QModelIndex eeidx = model()->index(end + 1, 2);
+ // qDebug() << "End++:" << end + 1 << eeidx.data(MessageModel::MsgIdRole).value<MsgId>()
+ // << eeidx.data(Qt::DisplayRole).toString();
+ // }
qreal h = 0;
qreal y = 0;
if (atTop) {
for (int i = end; i >= start; i--) {
- auto *line = new ChatLine(i, model(),
- width,
- timestampWidth, senderWidth, contentsWidth,
- senderPos, contentsPos);
+ auto* line = new ChatLine(i, model(), width, timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
h += line->height();
- line->setPos(0, y-h);
+ line->setPos(0, y - h);
_lines.insert(start, line);
addItem(line);
}
}
else {
for (int i = start; i <= end; i++) {
- auto *line = new ChatLine(i, model(),
- width,
- timestampWidth, senderWidth, contentsWidth,
- senderPos, contentsPos);
- line->setPos(0, y+h);
+ auto* line = new ChatLine(i, model(), width, timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
+ line->setPos(0, y + h);
h += line->height();
_lines.insert(i, line);
addItem(line);
}
// update existing items
- for (int i = end+1; i < _lines.count(); i++) {
+ for (int i = end + 1; i < _lines.count(); i++) {
_lines[i]->setRow(i);
}
// neither pre- or append means we have to do dirty work: move items...
if (!(atTop || atBottom)) {
- ChatLine *line = nullptr;
+ ChatLine* line = nullptr;
for (int i = 0; i <= end; i++) {
line = _lines.at(i);
line->setPos(0, line->pos().y() - h);
// check if all went right
Q_ASSERT(start == 0 || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
-// if(start != 0) {
-// if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
-// qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
-// qDebug() << "line[start - 1]:" << _lines.at(start - 1)->pos().y() << "+" << _lines.at(start - 1)->height() << "=" << _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height();
-// qDebug() << "line[start]" << _lines.at(start)->pos().y();
-// qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
-// Q_ASSERT(false)
-// }
-// }
+ // if(start != 0) {
+ // if(_lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() != _lines.at(start)->pos().y()) {
+ // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
+ // qDebug() << "line[start - 1]:" << _lines.at(start - 1)->pos().y() << "+" << _lines.at(start - 1)->height() << "=" <<
+ // _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height(); qDebug() << "line[start]" << _lines.at(start)->pos().y(); qDebug()
+ // << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset; Q_ASSERT(false)
+ // }
+ // }
Q_ASSERT(end + 1 == _lines.count() || _lines.at(end)->pos().y() + _lines.at(end)->height() == _lines.at(end + 1)->pos().y());
-// if(end + 1 < _lines.count()) {
-// if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
-// qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
-// qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() + _lines.at(end)->height();
-// qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y();
-// qDebug() << "needed moving:" << !(atTop || atBottom) << moveTop << moveStart << moveEnd << offset;
-// Q_ASSERT(false);
-// }
-// }
+ // if(end + 1 < _lines.count()) {
+ // if(_lines.at(end)->pos().y() + _lines.at(end)->height() != _lines.at(end + 1)->pos().y()) {
+ // qDebug() << "lines:" << _lines.count() << "start:" << start << "end:" << end;
+ // qDebug() << "line[end]:" << _lines.at(end)->pos().y() << "+" << _lines.at(end)->height() << "=" << _lines.at(end)->pos().y() +
+ // _lines.at(end)->height(); qDebug() << "line[end+1]" << _lines.at(end + 1)->pos().y(); qDebug() << "needed moving:" << !(atTop
+ // || atBottom) << moveTop << moveStart << moveEnd << offset; Q_ASSERT(false);
+ // }
+ // }
if (!atBottom) {
if (start < _firstLineRow) {
setMarkerLine();
}
-
-void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
+void ChatScene::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
Q_UNUSED(parent);
- qreal h = 0; // total height of removed items;
+ qreal h = 0; // total height of removed items;
bool atTop = (start == 0);
bool atBottom = (end == _lines.count() - 1);
}
// remove items from scene
- QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
+ QList<ChatLine*>::iterator lineIter = _lines.begin() + start;
int lineCount = start;
while (lineIter != _lines.end() && lineCount <= end) {
if ((*lineIter) == markerLine()->chatLine())
moveStart = start;
offset = -offset;
}
- ChatLine *line = nullptr;
+ ChatLine* line = nullptr;
for (int i = moveStart; i <= moveEnd; i++) {
line = _lines.at(i);
line->setPos(0, line->pos().y() + offset);
}
}
- Q_ASSERT(start == 0 || start >= _lines.count() || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
+ Q_ASSERT(start == 0 || start >= _lines.count()
+ || _lines.at(start - 1)->pos().y() + _lines.at(start - 1)->height() == _lines.at(start)->pos().y());
// update sceneRect
// when searching for the first non-date-line we have to take into account that our
needOffset = true;
}
firstLineIdx = model()->index(_firstLineRow, 0);
- }
- while ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
+ } while ((Message::Type)(model()->data(firstLineIdx, MessageModel::TypeRole).toInt()) == Message::DayChange && _firstLineRow < numRows);
if (needOffset)
_firstLineRow -= end - start + 1;
updateSceneRect();
}
-
void ChatScene::rowsRemoved()
{
// move the marker line if necessary
setMarkerLine();
}
-
-void ChatScene::dataChanged(const QModelIndex &tl, const QModelIndex &br)
+void ChatScene::dataChanged(const QModelIndex& tl, const QModelIndex& br)
{
layout(tl.row(), br.row(), _sceneRect.width());
}
-
void ChatScene::updateForViewport(qreal width, qreal height)
{
_viewportHeight = height;
setWidth(width);
}
-
void ChatScene::setWidth(qreal width)
{
if (width == _sceneRect.width())
return;
- layout(0, _lines.count()-1, width);
+ layout(0, _lines.count() - 1, width);
}
-
void ChatScene::layout(int start, int end, qreal width)
{
// clock_t startT = clock();
// disabling the index while doing this complex updates is about
// 2 to 10 times faster!
- //setItemIndexMethod(QGraphicsScene::NoIndex);
+ // setItemIndexMethod(QGraphicsScene::NoIndex);
if (end >= 0) {
int row = end;
if (row >= 0) {
// remaining items don't need geometry changes, but maybe repositioning?
- ChatLine *line = _lines.at(row);
+ ChatLine* line = _lines.at(row);
qreal offset = linePos - (line->scenePos().y() + line->height());
if (offset != 0) {
while (row >= 0) {
}
}
- //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
+ // setItemIndexMethod(QGraphicsScene::BspTreeIndex);
updateSceneRect(width);
setHandleXLimits();
setMarkerLine();
emit layoutChanged();
-// clock_t endT = clock();
-// qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
+ // clock_t endT = clock();
+ // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
}
-
void ChatScene::firstHandlePositionChanged(qreal xpos)
{
if (_firstColHandlePos == xpos)
// disabling the index while doing this complex updates is about
// 2 to 10 times faster!
- //setItemIndexMethod(QGraphicsScene::NoIndex);
+ // setItemIndexMethod(QGraphicsScene::NoIndex);
- QList<ChatLine *>::iterator lineIter = _lines.end();
- QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
+ QList<ChatLine*>::iterator lineIter = _lines.end();
+ QList<ChatLine*>::iterator lineIterBegin = _lines.begin();
qreal timestampWidth = firstColumnHandle()->sceneLeft();
qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
--lineIter;
(*lineIter)->setFirstColumn(timestampWidth, senderWidth, senderPos);
}
- //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
+ // setItemIndexMethod(QGraphicsScene::BspTreeIndex);
setHandleXLimits();
-// clock_t endT = clock();
-// qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
+ // clock_t endT = clock();
+ // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
}
-
void ChatScene::secondHandlePositionChanged(qreal xpos)
{
if (_secondColHandlePos == xpos)
// disabling the index while doing this complex updates is about
// 2 to 10 times faster!
- //setItemIndexMethod(QGraphicsScene::NoIndex);
+ // setItemIndexMethod(QGraphicsScene::NoIndex);
- QList<ChatLine *>::iterator lineIter = _lines.end();
- QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
+ QList<ChatLine*>::iterator lineIter = _lines.end();
+ QList<ChatLine*>::iterator lineIterBegin = _lines.begin();
qreal linePos = _sceneRect.y() + _sceneRect.height();
qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
qreal contentsWidth = _sceneRect.width() - secondColumnHandle()->sceneRight();
--lineIter;
(*lineIter)->setSecondColumn(senderWidth, contentsWidth, contentsPos, linePos);
}
- //setItemIndexMethod(QGraphicsScene::BspTreeIndex);
+ // setItemIndexMethod(QGraphicsScene::BspTreeIndex);
updateSceneRect();
setHandleXLimits();
emit layoutChanged();
-// clock_t endT = clock();
-// qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
+ // clock_t endT = clock();
+ // qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
}
-
void ChatScene::setHandleXLimits()
{
_firstColHandle->setXLimits(0, _secondColHandle->sceneLeft());
update();
}
-
-void ChatScene::setSelectingItem(ChatItem *item)
+void ChatScene::setSelectingItem(ChatItem* item)
{
- if (_selectingItem) _selectingItem->clearSelection();
+ if (_selectingItem)
+ _selectingItem->clearSelection();
_selectingItem = item;
}
-
-void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos)
+void ChatScene::startGlobalSelection(ChatItem* item, const QPointF& itemPos)
{
_selectionStart = _selectionEnd = _firstSelectionRow = item->row();
_selectionStartCol = _selectionMinCol = item->column();
updateSelection(item->mapToScene(itemPos));
}
-
-void ChatScene::updateSelection(const QPointF &pos)
+void ChatScene::updateSelection(const QPointF& pos)
{
int curRow = rowByScenePos(pos);
- if (curRow < 0) return;
+ if (curRow < 0)
+ return;
auto curColumn = (int)columnByScenePos(pos);
auto minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
if (minColumn != _selectionMinCol) {
_lines[l]->setSelected(false);
}
if (newend > _selectionEnd) {
- for (int l = _selectionEnd+1; l <= newend; l++)
+ for (int l = _selectionEnd + 1; l <= newend; l++)
_lines[l]->setSelected(true, minColumn);
}
if (newend < _selectionEnd) {
- for (int l = newend+1; l <= _selectionEnd; l++)
+ for (int l = newend + 1; l <= _selectionEnd; l++)
_lines[l]->setSelected(false);
}
}
}
-
-bool ChatScene::isPosOverSelection(const QPointF &pos) const
+bool ChatScene::isPosOverSelection(const QPointF& pos) const
{
- ChatItem *chatItem = chatItemAt(pos);
+ ChatItem* chatItem = chatItemAt(pos);
if (!chatItem)
return false;
if (hasGlobalSelection()) {
return false;
}
-
bool ChatScene::isScrollingAllowed() const
{
if (_isSelecting)
return true;
}
-
/******** MOUSE HANDLING **************************************************************************/
-void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
+void ChatScene::contextMenuEvent(QGraphicsSceneContextMenuEvent* event)
{
QPointF pos = event->scenePos();
QMenu menu;
menu.addSeparator();
// item-specific options (select link etc)
- ChatItem *item = chatItemAt(pos);
+ ChatItem* item = chatItemAt(pos);
if (item)
item->addActionsToMenu(&menu, item->mapFromScene(pos));
else
// If we have text selected, insert the Copy Selection as first item
if (isPosOverSelection(pos)) {
- QAction *sep = menu.insertSeparator(menu.actions().first());
- QAction *act = new Action(icon::get("edit-copy"), tr("Copy Selection"), &menu, this, [this]() { selectionToClipboard(); }, QKeySequence::Copy);
+ QAction* sep = menu.insertSeparator(menu.actions().first());
+ QAction* act = new Action(icon::get("edit-copy"),
+ tr("Copy Selection"),
+ &menu,
+ this,
+ [this]() { selectionToClipboard(); },
+ QKeySequence::Copy);
menu.insertAction(sep, act);
QString searchSelectionText = selection();
searchSelectionText = searchSelectionText.left(_webSearchSelectionTextMaxVisible).append(QString::fromUtf8("…"));
searchSelectionText = tr("Search '%1'").arg(searchSelectionText);
- QAction *webSearchAction = new Action(icon::get("edit-find"), searchSelectionText, &menu, this, &ChatScene::webSearchOnSelection);
+ QAction* webSearchAction = new Action(icon::get("edit-find"), searchSelectionText, &menu, this, &ChatScene::webSearchOnSelection);
menu.insertAction(sep, webSearchAction);
}
menu.addAction(QtUi::actionCollection("General")->action("ToggleMenuBar"));
// show column reset action if columns have been resized in this session or there is at least one very narrow column
- if ((_firstColHandlePos != _defaultFirstColHandlePos) || (_secondColHandlePos != _defaultSecondColHandlePos) ||
- (_firstColHandlePos <= 10) || (_secondColHandlePos - _firstColHandlePos <= 10))
+ if ((_firstColHandlePos != _defaultFirstColHandlePos) || (_secondColHandlePos != _defaultSecondColHandlePos)
+ || (_firstColHandlePos <= 10) || (_secondColHandlePos - _firstColHandlePos <= 10))
menu.addAction(new Action(tr("Reset Column Widths"), &menu, this, &ChatScene::resetColumnWidths));
menu.exec(event->screenPos());
}
-
-void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
+void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
if (event->buttons() == Qt::LeftButton) {
if (!_clickHandled && (event->scenePos() - _clickPos).toPoint().manhattanLength() >= QApplication::startDragDistance()) {
QGraphicsScene::mouseMoveEvent(event);
}
-
-void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
+void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
if (event->buttons() == Qt::LeftButton) {
_leftButtonPressed = true;
if (_clickMode != NoClick && _clickTimer.isActive()) {
switch (_clickMode) {
case NoClick:
- _clickMode = SingleClick; break;
+ _clickMode = SingleClick;
+ break;
case SingleClick:
- _clickMode = DoubleClick; break;
+ _clickMode = DoubleClick;
+ break;
case DoubleClick:
- _clickMode = TripleClick; break;
+ _clickMode = TripleClick;
+ break;
case TripleClick:
- _clickMode = DoubleClick; break;
+ _clickMode = DoubleClick;
+ break;
case DragStartClick:
break;
}
QGraphicsScene::mousePressEvent(event);
}
-
-void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
+void ChatScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event)
{
// we check for doubleclick ourselves, so just call press handler
mousePressEvent(event);
}
-
-void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
+void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
if (event->button() == Qt::LeftButton && _leftButtonPressed) {
_leftButtonPressed = false;
QGraphicsScene::mouseReleaseEvent(event);
}
-
void ChatScene::clickTimeout()
{
if (!_leftButtonPressed && _clickMode == SingleClick)
handleClick(Qt::LeftButton, _clickPos);
}
-
-void ChatScene::handleClick(Qt::MouseButton button, const QPointF &scenePos)
+void ChatScene::handleClick(Qt::MouseButton button, const QPointF& scenePos)
{
if (button == Qt::LeftButton) {
clearSelection();
// Now send click down to items
- ChatItem *chatItem = chatItemAt(scenePos);
+ ChatItem* chatItem = chatItemAt(scenePos);
if (chatItem) {
chatItem->handleClick(chatItem->mapFromScene(scenePos), _clickMode);
}
}
}
-
-void ChatScene::initiateDrag(QWidget *source)
+void ChatScene::initiateDrag(QWidget* source)
{
- auto *drag = new QDrag(source);
- auto *mimeData = new QMimeData;
+ auto* drag = new QDrag(source);
+ auto* mimeData = new QMimeData;
mimeData->setText(selection());
drag->setMimeData(mimeData);
drag->exec(Qt::CopyAction);
}
-
/******** SELECTIONS ******************************************************************************/
void ChatScene::selectionToClipboard(QClipboard::Mode mode)
stringToClipboard(selection(), mode);
}
-
-void ChatScene::stringToClipboard(const QString &str_, QClipboard::Mode mode)
+void ChatScene::stringToClipboard(const QString& str_, QClipboard::Mode mode)
{
QString str = str_;
// remove trailing linefeeds
};
}
-
//!\brief Convert current selection to human-readable string.
QString ChatScene::selection() const
{
- //TODO Make selection format configurable!
+ // TODO Make selection format configurable!
if (hasGlobalSelection()) {
int start = qMin(_selectionStart, _selectionEnd);
int end = qMax(_selectionStart, _selectionEnd);
for (int l = start; l <= end; l++) {
if (_selectionMinCol == ChatLineModel::TimestampColumn) {
- ChatItem *item = _lines[l]->item(ChatLineModel::TimestampColumn);
+ ChatItem* item = _lines[l]->item(ChatLineModel::TimestampColumn);
if (!_showSenderBrackets && !_timestampHasBrackets) {
// Only re-add brackets if the current timestamp format does not include them
// -and- sender brackets are disabled. Don't filter on Message::Plain as
// timestamp brackets affect all types of messages.
// Remove any spaces before and after, otherwise it may look weird.
- result += QString("[%1] ").arg(item->data(MessageModel::DisplayRole)
- .toString().trimmed());
- } else {
+ result += QString("[%1] ").arg(item->data(MessageModel::DisplayRole).toString().trimmed());
+ }
+ else {
result += item->data(MessageModel::DisplayRole).toString() + " ";
}
}
if (_selectionMinCol <= ChatLineModel::SenderColumn) {
- ChatItem *item = _lines[l]->item(ChatLineModel::SenderColumn);
- if (!_showSenderBrackets && (_alwaysBracketSender
- || item->chatLine()->msgType() == Message::Plain)) {
+ ChatItem* item = _lines[l]->item(ChatLineModel::SenderColumn);
+ if (!_showSenderBrackets && (_alwaysBracketSender || item->chatLine()->msgType() == Message::Plain)) {
// Copying to plain-text. Re-add the sender brackets if they're normally hidden
// for...
// * Plain messages
// * All messages in the Chat Monitor
//
// The Chat Monitor sets alwaysBracketSender() to true.
- result += QString("<%1> ").arg(item->data(MessageModel::DisplayRole)
- .toString());
- } else {
+ result += QString("<%1> ").arg(item->data(MessageModel::DisplayRole).toString());
+ }
+ else {
result += item->data(MessageModel::DisplayRole).toString() + " ";
}
}
- result += _lines[l]->item(ChatLineModel::ContentsColumn)
- ->data(MessageModel::DisplayRole).toString() + "\n";
+ result += _lines[l]->item(ChatLineModel::ContentsColumn)->data(MessageModel::DisplayRole).toString() + "\n";
}
return result;
}
return QString();
}
-
bool ChatScene::hasSelection() const
{
return hasGlobalSelection() || (selectingItem() && selectingItem()->hasSelection());
}
-
bool ChatScene::hasGlobalSelection() const
{
return _selectionStart >= 0;
}
-
bool ChatScene::isGloballySelecting() const
{
return _isSelecting;
}
-
void ChatScene::clearGlobalSelection()
{
if (hasGlobalSelection()) {
}
}
-
void ChatScene::clearSelection()
{
clearGlobalSelection();
selectingItem()->clearSelection();
}
-
/******** *************************************************************************************/
void ChatScene::webSearchOnSelection()
QDesktopServices::openUrl(url);
}
-
/******** *************************************************************************************/
void ChatScene::requestBacklog()
{
- auto *filter = qobject_cast<MessageFilter *>(model());
+ auto* filter = qobject_cast<MessageFilter*>(model());
if (filter)
return filter->requestBacklog();
return;
}
-
ChatLineModel::ColumnType ChatScene::columnByScenePos(qreal x) const
{
if (x < _firstColHandle->x())
return ChatLineModel::ContentsColumn;
}
-
int ChatScene::rowByScenePos(qreal y) const
{
- QList<QGraphicsItem *> itemList = items(QPointF(0, y));
+ QList<QGraphicsItem*> itemList = items(QPointF(0, y));
// ChatLine should be at the bottom of the list
- for (int i = itemList.count()-1; i >= 0; i--) {
- auto *line = qgraphicsitem_cast<ChatLine *>(itemList.at(i));
+ for (int i = itemList.count() - 1; i >= 0; i--) {
+ auto* line = qgraphicsitem_cast<ChatLine*>(itemList.at(i));
if (line)
return line->row();
}
return -1;
}
-
void ChatScene::updateSceneRect(qreal width)
{
if (_lines.isEmpty()) {
// the following call should be safe. If it crashes something went wrong during insert/remove
if (_firstLineRow < _lines.count()) {
- ChatLine *firstLine = _lines.at(_firstLineRow);
- ChatLine *lastLine = _lines.last();
+ ChatLine* firstLine = _lines.at(_firstLineRow);
+ ChatLine* lastLine = _lines.last();
updateSceneRect(QRectF(0, firstLine->pos().y(), width, lastLine->pos().y() + lastLine->height() - firstLine->pos().y()));
}
else {
}
}
-
-void ChatScene::updateSceneRect(const QRectF &rect)
+void ChatScene::updateSceneRect(const QRectF& rect)
{
_sceneRect = rect;
setSceneRect(rect);
update();
}
-
// ========================================
// Webkit/WebEngine Only stuff
// ========================================
#if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
-void ChatScene::loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect)
+void ChatScene::loadWebPreview(ChatItem* parentItem, const QUrl& url, const QRectF& urlRect)
{
if (!_showWebPreview)
return;
// qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
}
-
void ChatScene::webPreviewNextStep()
{
// qDebug() << Q_FUNC_INFO << webPreview.previewState;
// qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
}
-
-void ChatScene::clearWebPreview(ChatItem *parentItem)
+void ChatScene::clearWebPreview(ChatItem* parentItem)
{
// qDebug() << Q_FUNC_INFO << webPreview.previewState;
switch (webPreview.previewState) {
case WebPreview::NewPreview:
- webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
+ webPreview.previewState = WebPreview::NoPreview; // we haven't loaded anything yet
break;
case WebPreview::ShowPreview:
if (parentItem == nullptr || webPreview.parentItem == parentItem) {
// qDebug() << " new State:" << webPreview.previewState << webPreview.timer.isActive();
}
-
#endif
// ========================================
// The default timestamp format string does not have brackets, no need to check.
// If UiStyle::updateSystemTimestampFormat() has brackets added, change this, too.
_timestampHasBrackets = false;
- } else {
+ }
+ else {
// Does the timestamp format contain brackets? For example:
// Classic: "[hh:mm:ss]"
// Modern: " hh:mm:ss"
Q_OBJECT
public:
- enum CutoffMode {
+ enum CutoffMode
+ {
CutoffLeft,
CutoffRight
};
- enum ItemType {
+ enum ItemType
+ {
ChatLineType = QGraphicsItem::UserType + 1,
ChatItemType,
TimestampChatItemType,
MarkerLineType
};
- enum ClickMode {
+ enum ClickMode
+ {
NoClick,
DragStartClick,
SingleClick,
TripleClick
};
- ChatScene(QAbstractItemModel *model, QString idString, qreal width, ChatView *parent);
+ ChatScene(QAbstractItemModel* model, QString idString, qreal width, ChatView* parent);
- inline QAbstractItemModel *model() const { return _model; }
- inline MessageFilter *filter() const { return qobject_cast<MessageFilter *>(_model); }
+ inline QAbstractItemModel* model() const { return _model; }
+ inline MessageFilter* filter() const { return qobject_cast<MessageFilter*>(_model); }
inline QString idString() const { return _idString; }
int rowByScenePos(qreal y) const;
- inline int rowByScenePos(const QPointF &pos) const { return rowByScenePos(pos.y()); }
+ inline int rowByScenePos(const QPointF& pos) const { return rowByScenePos(pos.y()); }
ChatLineModel::ColumnType columnByScenePos(qreal x) const;
- inline ChatLineModel::ColumnType columnByScenePos(const QPointF &pos) const { return columnByScenePos(pos.x()); }
+ inline ChatLineModel::ColumnType columnByScenePos(const QPointF& pos) const { return columnByScenePos(pos.x()); }
- ChatView *chatView() const;
- ChatItem *chatItemAt(const QPointF &pos) const;
- inline ChatLine *chatLine(int row) const { return (row < _lines.count()) ? _lines.value(row) : 0; }
- inline ChatLine *chatLine(const QModelIndex &index) const { return _lines.value(index.row()); }
+ ChatView* chatView() const;
+ ChatItem* chatItemAt(const QPointF& pos) const;
+ inline ChatLine* chatLine(int row) const { return (row < _lines.count()) ? _lines.value(row) : 0; }
+ inline ChatLine* chatLine(const QModelIndex& index) const { return _lines.value(index.row()); }
//! Find the ChatLine belonging to a MsgId
/** Searches for the ChatLine belonging to a MsgId. If there are more than one ChatLine with the same msgId,
* \param ignoreDayChange Whether we ignore day change messages
* \return The ChatLine corresponding to the given MsgId
*/
- ChatLine *chatLine(MsgId msgId, bool matchExact = true, bool ignoreDayChange = true) const;
+ ChatLine* chatLine(MsgId msgId, bool matchExact = true, bool ignoreDayChange = true) const;
- inline ChatLine *lastLine() const { return _lines.count() ? _lines.last() : 0; }
+ inline ChatLine* lastLine() const { return _lines.count() ? _lines.last() : 0; }
- inline MarkerLineItem *markerLine() const { return _markerLine; }
+ inline MarkerLineItem* markerLine() const { return _markerLine; }
inline bool isSingleBufferScene() const { return _singleBufferId.isValid(); }
inline BufferId singleBufferId() const { return _singleBufferId; }
- bool containsBuffer(const BufferId &id) const;
+ bool containsBuffer(const BufferId& id) const;
- ColumnHandleItem *firstColumnHandle() const;
- ColumnHandleItem *secondColumnHandle() const;
+ ColumnHandleItem* firstColumnHandle() const;
+ ColumnHandleItem* secondColumnHandle() const;
inline CutoffMode senderCutoffMode() const { return _cutoffMode; }
inline void setSenderCutoffMode(CutoffMode mode) { _cutoffMode = mode; }
QString selection() const;
bool hasSelection() const;
bool hasGlobalSelection() const;
- bool isPosOverSelection(const QPointF &) const;
+ bool isPosOverSelection(const QPointF&) const;
bool isGloballySelecting() const;
- void initiateDrag(QWidget *source);
+ void initiateDrag(QWidget* source);
bool isScrollingAllowed() const;
void jumpToMarkerLine(bool requestBacklog);
// these are used by the chatitems to notify the scene and manage selections
- void setSelectingItem(ChatItem *item);
- ChatItem *selectingItem() const { return _selectingItem; }
- void startGlobalSelection(ChatItem *item, const QPointF &itemPos);
+ void setSelectingItem(ChatItem* item);
+ ChatItem* selectingItem() const { return _selectingItem; }
+ void startGlobalSelection(ChatItem* item, const QPointF& itemPos);
void clearGlobalSelection();
void clearSelection();
void selectionToClipboard(QClipboard::Mode = QClipboard::Clipboard);
- void stringToClipboard(const QString &str, QClipboard::Mode = QClipboard::Clipboard);
+ void stringToClipboard(const QString& str, QClipboard::Mode = QClipboard::Clipboard);
void webSearchOnSelection();
void requestBacklog();
#if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
- void loadWebPreview(ChatItem *parentItem, const QUrl &url, const QRectF &urlRect);
- void clearWebPreview(ChatItem *parentItem = nullptr);
+ void loadWebPreview(ChatItem* parentItem, const QUrl& url, const QRectF& urlRect);
+ void clearWebPreview(ChatItem* parentItem = nullptr);
#endif
signals:
- void lastLineChanged(QGraphicsItem *item, qreal offset);
- void layoutChanged(); // indicates changes to the scenerect due to resizing of the contentsitems
- void mouseMoveWhileSelecting(const QPointF &scenePos);
+ void lastLineChanged(QGraphicsItem* item, qreal offset);
+ void layoutChanged(); // indicates changes to the scenerect due to resizing of the contentsitems
+ void mouseMoveWhileSelecting(const QPointF& scenePos);
protected:
- void contextMenuEvent(QGraphicsSceneContextMenuEvent *contextMenuEvent) override;
- void mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent) override;
- void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) override;
- void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent) override;
- void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *mouseEvent) override;
- virtual void handleClick(Qt::MouseButton button, const QPointF &scenePos);
+ void contextMenuEvent(QGraphicsSceneContextMenuEvent* contextMenuEvent) override;
+ void mouseMoveEvent(QGraphicsSceneMouseEvent* mouseEvent) override;
+ void mousePressEvent(QGraphicsSceneMouseEvent* mouseEvent) override;
+ void mouseReleaseEvent(QGraphicsSceneMouseEvent* mouseEvent) override;
+ void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* mouseEvent) override;
+ virtual void handleClick(Qt::MouseButton button, const QPointF& scenePos);
protected slots:
- void rowsInserted(const QModelIndex &, int, int);
- void rowsAboutToBeRemoved(const QModelIndex &, int, int);
- void dataChanged(const QModelIndex &, const QModelIndex &);
+ void rowsInserted(const QModelIndex&, int, int);
+ void rowsAboutToBeRemoved(const QModelIndex&, int, int);
+ void dataChanged(const QModelIndex&, const QModelIndex&);
private slots:
void firstHandlePositionChanged(qreal xpos);
private:
void setHandleXLimits();
- void updateSelection(const QPointF &pos);
+ void updateSelection(const QPointF& pos);
- ChatView *_chatView;
+ ChatView* _chatView;
QString _idString;
- QAbstractItemModel *_model;
- QList<ChatLine *> _lines;
+ QAbstractItemModel* _model;
+ QList<ChatLine*> _lines;
BufferId _singleBufferId;
// calls to QChatScene::sceneRect() are very expensive. As we manage the scenerect ourselves
// we store the size in a member variable.
QRectF _sceneRect;
- int _firstLineRow; // the first row to display (aka: not a daychange msg)
+ int _firstLineRow; // the first row to display (aka: not a daychange msg)
void updateSceneRect(qreal width);
inline void updateSceneRect() { updateSceneRect(_sceneRect.width()); }
- void updateSceneRect(const QRectF &rect);
+ void updateSceneRect(const QRectF& rect);
qreal _viewportHeight;
- MarkerLineItem *_markerLine;
+ MarkerLineItem* _markerLine;
bool _markerLineVisible, _markerLineValid, _markerLineJumpPending;
ColumnHandleItem *_firstColHandle, *_secondColHandle;
/// Whether to re-add hidden brackets around sender for all message types
bool _alwaysBracketSender;
- ChatItem *_selectingItem;
+ ChatItem* _selectingItem;
int _selectionStartCol, _selectionMinCol;
int _selectionStart;
int _selectionEnd;
bool _showSenderBrackets; /// If true, show brackets around sender names
- bool _useCustomTimestampFormat; /// If true, use the custom timestamp format
- QString _timestampFormatString; /// Format of the timestamp string
- bool _timestampHasBrackets; /// If true, timestamp format has [brackets] of some sort
+ bool _useCustomTimestampFormat; /// If true, use the custom timestamp format
+ QString _timestampFormatString; /// Format of the timestamp string
+ bool _timestampHasBrackets; /// If true, timestamp format has [brackets] of some sort
static const int _webSearchSelectionTextMaxVisible = 24;
#if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
- struct WebPreview {
- enum PreviewState {
+ struct WebPreview
+ {
+ enum PreviewState
+ {
NoPreview,
NewPreview,
DelayPreview,
ShowPreview,
HidePreview
};
- ChatItem *parentItem{nullptr};
- QGraphicsItem *previewItem{nullptr};
+ ChatItem* parentItem{nullptr};
+ QGraphicsItem* previewItem{nullptr};
QUrl url;
QRectF urlRect;
PreviewState previewState{NoPreview};
QTimer timer;
};
WebPreview webPreview;
-#endif // HAVE_WEBKIT || HAVE_WEBENGINE
+#endif // HAVE_WEBKIT || HAVE_WEBENGINE
};
-
#endif
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "chatview.h"
+
#include <QGraphicsTextItem>
#include <QKeyEvent>
#include <QMenu>
#include <QScrollBar>
#include "bufferwidget.h"
+#include "chatline.h"
#include "chatscene.h"
-#include "chatview.h"
#include "client.h"
+#include "clientignorelistmanager.h"
#include "messagefilter.h"
#include "qtui.h"
#include "qtuistyle.h"
-#include "clientignorelistmanager.h"
-
-#include "chatline.h"
-ChatView::ChatView(BufferId bufferId, QWidget *parent)
- : QGraphicsView(parent),
- AbstractChatView()
+ChatView::ChatView(BufferId bufferId, QWidget* parent)
+ : QGraphicsView(parent)
+ , AbstractChatView()
{
QList<BufferId> filterList;
filterList.append(bufferId);
- auto *filter = new MessageFilter(Client::messageModel(), filterList, this);
+ auto* filter = new MessageFilter(Client::messageModel(), filterList, this);
init(filter);
}
-
-ChatView::ChatView(MessageFilter *filter, QWidget *parent)
- : QGraphicsView(parent),
- AbstractChatView()
+ChatView::ChatView(MessageFilter* filter, QWidget* parent)
+ : QGraphicsView(parent)
+ , AbstractChatView()
{
init(filter);
}
-
-void ChatView::init(MessageFilter *filter)
+void ChatView::init(MessageFilter* filter)
{
_bufferContainer = nullptr;
_currentScaleFactor = 1;
setAttribute(Qt::WA_AcceptTouchEvents);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
- setAlignment(Qt::AlignLeft|Qt::AlignBottom);
+ setAlignment(Qt::AlignLeft | Qt::AlignBottom);
setInteractive(true);
- //setOptimizationFlags(QGraphicsView::DontClipPainter | QGraphicsView::DontAdjustForAntialiasing);
+ // setOptimizationFlags(QGraphicsView::DontClipPainter | QGraphicsView::DontAdjustForAntialiasing);
// setOptimizationFlags(QGraphicsView::DontAdjustForAntialiasing);
setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
// setTransformationAnchor(QGraphicsView::NoAnchor);
connect(Client::ignoreListManager(), &ClientIgnoreListManager::ignoreListChanged, this, &ChatView::invalidateFilter);
}
-
-bool ChatView::event(QEvent *event)
+bool ChatView::event(QEvent* event)
{
if (event->type() == QEvent::KeyPress) {
- auto *keyEvent = static_cast<QKeyEvent *>(event);
+ auto* keyEvent = static_cast<QKeyEvent*>(event);
switch (keyEvent->key()) {
case Qt::Key_Up:
case Qt::Key_Down:
setInteractive(false);
// if scrollbar is not visible we need to request backlog below else we need to accept
// the event now (return true) so that we will receive TouchUpdate and TouchEnd/TouchCancel
- if (verticalScrollBar()->isVisible()) return true;
+ if (verticalScrollBar()->isVisible())
+ return true;
}
if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
}
// Applying the movement happens automatically by the drag-mode
}
- if (event->type() == QEvent::Wheel || (event->type() == QEvent::TouchBegin && ((QTouchEvent*)event)->device()->type() == QTouchDevice::TouchScreen) || event->type() == QEvent::TouchUpdate) {
+ if (event->type() == QEvent::Wheel
+ || (event->type() == QEvent::TouchBegin && ((QTouchEvent*)event)->device()->type() == QTouchDevice::TouchScreen)
+ || event->type() == QEvent::TouchUpdate) {
if (!verticalScrollBar()->isVisible()) {
scene()->requestBacklog();
return true;
return QGraphicsView::event(event);
}
-
-void ChatView::resizeEvent(QResizeEvent *event)
+void ChatView::resizeEvent(QResizeEvent* event)
{
// if view is currently scrolled to bottom, we want it that way after resizing
bool atBottom = (_lastScrollbarPos == verticalScrollBar()->maximum());
QGraphicsView::resizeEvent(event);
// if scrolling to bottom, do it immediately.
- if(atBottom)
- {
+ if (atBottom) {
// we can reduce viewport updates if we scroll to the bottom allready at the beginning
verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}
scene()->updateForViewport(viewport()->width(), viewport()->height());
adjustSceneRect();
- if(atBottom)
- {
+ if (atBottom) {
_lastScrollbarPos = verticalScrollBar()->maximum();
verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}
checkChatLineCaches();
}
-
void ChatView::adjustSceneRect()
{
// Workaround for QTBUG-6322
setSceneRect(scene()->sceneRect().adjusted(0, 0, -25, 0));
}
-
-void ChatView::mouseMoveWhileSelecting(const QPointF &scenePos)
+void ChatView::mouseMoveWhileSelecting(const QPointF& scenePos)
{
int y = (int)mapFromScene(scenePos).y();
_scrollOffset = 0;
_scrollTimer.start();
}
-
void ChatView::scrollTimerTimeout()
{
// scroll view
- QAbstractSlider *vbar = verticalScrollBar();
+ QAbstractSlider* vbar = verticalScrollBar();
if (_scrollOffset < 0 && vbar->value() > 0)
vbar->setValue(qMax(vbar->value() + _scrollOffset, 0));
else if (_scrollOffset > 0 && vbar->value() < vbar->maximum())
vbar->setValue(qMin(vbar->value() + _scrollOffset, vbar->maximum()));
}
-
-void ChatView::lastLineChanged(QGraphicsItem *chatLine, qreal offset)
+void ChatView::lastLineChanged(QGraphicsItem* chatLine, qreal offset)
{
Q_UNUSED(chatLine)
// disabled until further testing/discussion
- //if(!scene()->isScrollingAllowed())
+ // if(!scene()->isScrollingAllowed())
// return;
- QAbstractSlider *vbar = verticalScrollBar();
+ QAbstractSlider* vbar = verticalScrollBar();
Q_ASSERT(vbar);
- if (vbar->maximum() - vbar->value() <= (offset + 5) * _currentScaleFactor) { // 5px grace area
+ if (vbar->maximum() - vbar->value() <= (offset + 5) * _currentScaleFactor) { // 5px grace area
vbar->setValue(vbar->maximum());
}
}
-
void ChatView::verticalScrollbarChanged(int newPos)
{
- QAbstractSlider *vbar = verticalScrollBar();
+ QAbstractSlider* vbar = verticalScrollBar();
Q_ASSERT(vbar);
// check for backlog request
vbar->setValue(vbar->maximum());
}
-
MsgId ChatView::lastMsgId() const
{
if (!scene())
return {};
- QAbstractItemModel *model = scene()->model();
+ QAbstractItemModel* model = scene()->model();
if (!model || model->rowCount() == 0)
return {};
return model->index(model->rowCount() - 1, 0).data(MessageModel::MsgIdRole).value<MsgId>();
}
-
MsgId ChatView::lastVisibleMsgId() const
{
- ChatLine *line = lastVisibleChatLine();
+ ChatLine* line = lastVisibleChatLine();
if (line)
return line->msgId();
return {};
}
-
-bool chatLinePtrLessThan(ChatLine *one, ChatLine *other)
+bool chatLinePtrLessThan(ChatLine* one, ChatLine* other)
{
return one->row() < other->row();
}
-
// TODO: figure out if it's cheaper to use a cached list (that we'd need to keep updated)
-QSet<ChatLine *> ChatView::visibleChatLines(Qt::ItemSelectionMode mode) const
+QSet<ChatLine*> ChatView::visibleChatLines(Qt::ItemSelectionMode mode) const
{
- QSet<ChatLine *> result;
- foreach(QGraphicsItem *item, items(viewport()->rect().adjusted(-1, -1, 1, 1), mode)) {
- auto *line = qgraphicsitem_cast<ChatLine *>(item);
+ QSet<ChatLine*> result;
+ foreach (QGraphicsItem* item, items(viewport()->rect().adjusted(-1, -1, 1, 1), mode)) {
+ auto* line = qgraphicsitem_cast<ChatLine*>(item);
if (line)
result.insert(line);
}
return result;
}
-
-QList<ChatLine *> ChatView::visibleChatLinesSorted(Qt::ItemSelectionMode mode) const
+QList<ChatLine*> ChatView::visibleChatLinesSorted(Qt::ItemSelectionMode mode) const
{
- QList<ChatLine *> result = visibleChatLines(mode).toList();
+ QList<ChatLine*> result = visibleChatLines(mode).toList();
qSort(result.begin(), result.end(), chatLinePtrLessThan);
return result;
}
-
-ChatLine *ChatView::lastVisibleChatLine(bool ignoreDayChange) const
+ChatLine* ChatView::lastVisibleChatLine(bool ignoreDayChange) const
{
if (!scene())
return nullptr;
- QAbstractItemModel *model = scene()->model();
+ QAbstractItemModel* model = scene()->model();
if (!model || model->rowCount() == 0)
return nullptr;
int row = -1;
- QSet<ChatLine *> visibleLines = visibleChatLines(Qt::ContainsItemBoundingRect);
- foreach(ChatLine *line, visibleLines) {
+ QSet<ChatLine*> visibleLines = visibleChatLines(Qt::ContainsItemBoundingRect);
+ foreach (ChatLine* line, visibleLines) {
if (line->row() > row && (ignoreDayChange ? line->msgType() != Message::DayChange : true))
row = line->row();
}
return nullptr;
}
-
void ChatView::setMarkerLineVisible(bool visible)
{
scene()->setMarkerLineVisible(visible);
}
-
void ChatView::setMarkerLine(MsgId msgId)
{
if (!scene()->isSingleBufferScene())
Client::setMarkerLine(bufId, msgId);
}
-
void ChatView::markerLineSet(BufferId buffer, MsgId msgId)
{
if (!scene()->isSingleBufferScene() || scene()->singleBufferId() != buffer)
scene()->setMarkerLineVisible(true);
}
-
void ChatView::jumpToMarkerLine(bool requestBacklog)
{
scene()->jumpToMarkerLine(requestBacklog);
}
-
-void ChatView::addActionsToMenu(QMenu *menu, const QPointF &pos)
+void ChatView::addActionsToMenu(QMenu* menu, const QPointF& pos)
{
// zoom actions
- auto *bw = qobject_cast<BufferWidget *>(bufferContainer());
+ auto* bw = qobject_cast<BufferWidget*>(bufferContainer());
if (bw) {
bw->addActionsToMenu(menu, pos);
menu->addSeparator();
}
}
-
void ChatView::zoomIn()
{
_currentScaleFactor *= 1.2;
scene()->setWidth(viewport()->width() / _currentScaleFactor - 2);
}
-
void ChatView::zoomOut()
{
_currentScaleFactor /= 1.2;
scene()->setWidth(viewport()->width() / _currentScaleFactor - 2);
}
-
void ChatView::zoomOriginal()
{
- scale(1/_currentScaleFactor, 1/_currentScaleFactor);
+ scale(1 / _currentScaleFactor, 1 / _currentScaleFactor);
_currentScaleFactor = 1;
scene()->setWidth(viewport()->width() - 2);
}
-
void ChatView::invalidateFilter()
{
// if this is the currently selected chatview
}
}
-
void ChatView::scrollContentsBy(int dx, int dy)
{
QGraphicsView::scrollContentsBy(dx, dy);
checkChatLineCaches();
}
-
-void ChatView::setHasCache(ChatLine *line, bool hasCache)
+void ChatView::setHasCache(ChatLine* line, bool hasCache)
{
if (hasCache)
_linesWithCache.insert(line);
_linesWithCache.remove(line);
}
-
void ChatView::checkChatLineCaches()
{
- qreal top = mapToScene(viewport()->rect().topLeft()).y() - 10; // some grace area to avoid premature cleaning
+ qreal top = mapToScene(viewport()->rect().topLeft()).y() - 10; // some grace area to avoid premature cleaning
qreal bottom = mapToScene(viewport()->rect().bottomRight()).y() + 10;
- QSet<ChatLine *>::iterator iter = _linesWithCache.begin();
+ QSet<ChatLine*>::iterator iter = _linesWithCache.begin();
while (iter != _linesWithCache.end()) {
- ChatLine *line = *iter;
+ ChatLine* line = *iter;
if (line->pos().y() + line->height() < top || line->pos().y() > bottom) {
line->clearCache();
iter = _linesWithCache.erase(iter);
Q_OBJECT
public:
- ChatView(MessageFilter *, QWidget *parent = nullptr);
- ChatView(BufferId bufferId, QWidget *parent = nullptr);
+ ChatView(MessageFilter*, QWidget* parent = nullptr);
+ ChatView(BufferId bufferId, QWidget* parent = nullptr);
MsgId lastMsgId() const override;
virtual MsgId lastVisibleMsgId() const;
- inline AbstractBufferContainer *bufferContainer() const { return _bufferContainer; }
- inline void setBufferContainer(AbstractBufferContainer *c) { _bufferContainer = c; }
+ inline AbstractBufferContainer* bufferContainer() const { return _bufferContainer; }
+ inline void setBufferContainer(AbstractBufferContainer* c) { _bufferContainer = c; }
- inline ChatScene *scene() const { return _scene; }
+ inline ChatScene* scene() const { return _scene; }
//! Return a set of ChatLines currently visible in the view
/** \param mode How partially visible ChatLines are handled
* \return A set of visible ChatLines
*/
- QSet<ChatLine *> visibleChatLines(Qt::ItemSelectionMode mode = Qt::ContainsItemBoundingRect) const;
+ QSet<ChatLine*> visibleChatLines(Qt::ItemSelectionMode mode = Qt::ContainsItemBoundingRect) const;
//! Return a sorted list of ChatLines currently visible in the view
/** \param mode How partially visible ChatLines are handled
* \return A list of visible ChatLines sorted by row
* \note If the order of ChatLines does not matter, use visibleChatLines() instead
*/
- QList<ChatLine *> visibleChatLinesSorted(Qt::ItemSelectionMode mode = Qt::ContainsItemBoundingRect) const;
+ QList<ChatLine*> visibleChatLinesSorted(Qt::ItemSelectionMode mode = Qt::ContainsItemBoundingRect) const;
//! Return the last fully visible ChatLine in this view
/** Using this method more efficient than calling visibleChatLinesSorted() and taking its last element.
* \return The last fully visible ChatLine in the view
*/
- ChatLine *lastVisibleChatLine(bool ignoreDayChange = false) const;
+ ChatLine* lastVisibleChatLine(bool ignoreDayChange = false) const;
- virtual void addActionsToMenu(QMenu *, const QPointF &pos);
+ virtual void addActionsToMenu(QMenu*, const QPointF& pos);
//! Tell the view that this ChatLine has cached data
/** ChatLines cache some layout data that should be cleared as soon as it's no
* appropriate.
* \param line The ChatLine having cached data
*/
- void setHasCache(ChatLine *line, bool hasCache = true);
+ void setHasCache(ChatLine* line, bool hasCache = true);
public slots:
inline virtual void clear() {}
void jumpToMarkerLine(bool requestBacklog);
protected:
- bool event(QEvent *event) override;
- void resizeEvent(QResizeEvent *event) override;
+ bool event(QEvent* event) override;
+ void resizeEvent(QResizeEvent* event) override;
void scrollContentsBy(int dx, int dy) override;
protected slots:
virtual void verticalScrollbarChanged(int);
private slots:
- void lastLineChanged(QGraphicsItem *chatLine, qreal offset);
+ void lastLineChanged(QGraphicsItem* chatLine, qreal offset);
void adjustSceneRect();
void checkChatLineCaches();
- void mouseMoveWhileSelecting(const QPointF &scenePos);
+ void mouseMoveWhileSelecting(const QPointF& scenePos);
void scrollTimerTimeout();
void invalidateFilter();
void markerLineSet(BufferId buffer, MsgId msg);
private:
- void init(MessageFilter *filter);
+ void init(MessageFilter* filter);
- AbstractBufferContainer *_bufferContainer;
- ChatScene *_scene;
+ AbstractBufferContainer* _bufferContainer;
+ ChatScene* _scene;
int _lastScrollbarPos;
qreal _currentScaleFactor;
QTimer _scrollTimer;
int _scrollOffset;
bool _invalidateFilter;
- QSet<ChatLine *> _linesWithCache;
+ QSet<ChatLine*> _linesWithCache;
bool _firstTouchUpdateHappened = false;
};
-
#endif
#include "icon.h"
#include "qtui.h"
-ChatViewSearchBar::ChatViewSearchBar(QWidget *parent)
+ChatViewSearchBar::ChatViewSearchBar(QWidget* parent)
: QWidget(parent)
{
ui.setupUi(this);
hide();
- ActionCollection *coll = QtUi::actionCollection("General");
+ ActionCollection* coll = QtUi::actionCollection("General");
- QAction *toggleSearchBar = coll->action("ToggleSearchBar");
+ QAction* toggleSearchBar = coll->action("ToggleSearchBar");
connect(toggleSearchBar, &QAction::toggled, this, &QWidget::setVisible);
- auto *hideSearchBar = new Action{{}, this, toggleSearchBar, &QAction::setChecked};
+ auto* hideSearchBar = new Action{{}, this, toggleSearchBar, &QAction::setChecked};
hideSearchBar->setShortcut(Qt::Key_Escape);
hideSearchBar->setShortcutConfigurable(false);
coll->addAction("HideSearchBar", hideSearchBar);
connect(&_searchDelayTimer, &QTimer::timeout, this, &ChatViewSearchBar::search);
}
-
void ChatViewSearchBar::setVisible(bool visible)
{
// clearing the search field also removes the highlight items from the scene
emit hidden();
}
-
void ChatViewSearchBar::delaySearch()
{
_searchDelayTimer.start(300);
}
-
void ChatViewSearchBar::search()
{
emit searchChanged(ui.searchEditLine->text());
#ifndef CHATVIEWSEARCHBAR_H
#define CHATVIEWSEARCHBAR_H
-#include "ui_chatviewsearchbar.h"
-
-#include <QWidget>
#include <QTimer>
+#include <QWidget>
+
+#include "ui_chatviewsearchbar.h"
class QAction;
Q_OBJECT
public:
- ChatViewSearchBar(QWidget *parent = nullptr);
+ ChatViewSearchBar(QWidget* parent = nullptr);
- inline QLineEdit *searchEditLine() const { return ui.searchEditLine; }
- inline QCheckBox *caseSensitiveBox() const { return ui.caseSensitiveBox; }
- inline QCheckBox *searchSendersBox() const { return ui.searchSendersBox; }
- inline QCheckBox *searchMsgsBox() const { return ui.searchMsgsBox; }
- inline QCheckBox *searchOnlyRegularMsgsBox() const { return ui.searchOnlyRegularMsgsBox; }
- inline QToolButton *searchUpButton() const { return ui.searchUpButton; }
- inline QToolButton *searchDownButton() const { return ui.searchDownButton; }
+ inline QLineEdit* searchEditLine() const { return ui.searchEditLine; }
+ inline QCheckBox* caseSensitiveBox() const { return ui.caseSensitiveBox; }
+ inline QCheckBox* searchSendersBox() const { return ui.searchSendersBox; }
+ inline QCheckBox* searchMsgsBox() const { return ui.searchMsgsBox; }
+ inline QCheckBox* searchOnlyRegularMsgsBox() const { return ui.searchOnlyRegularMsgsBox; }
+ inline QToolButton* searchUpButton() const { return ui.searchUpButton; }
+ inline QToolButton* searchDownButton() const { return ui.searchDownButton; }
public slots:
void setVisible(bool) override;
signals:
- void searchChanged(const QString &);
+ void searchChanged(const QString&);
void hidden();
private slots:
QTimer _searchDelayTimer;
};
-
-#endif //CHATVIEWSEARCHBAR_H
+#endif // CHATVIEWSEARCHBAR_H
#include "chatscene.h"
#include "messagemodel.h"
-ChatViewSearchController::ChatViewSearchController(QObject *parent)
+ChatViewSearchController::ChatViewSearchController(QObject* parent)
: QObject(parent)
-{
-}
-
+{}
-void ChatViewSearchController::setSearchString(const QString &searchString)
+void ChatViewSearchController::setSearchString(const QString& searchString)
{
QString oldSearchString = _searchString;
_searchString = searchString;
}
}
-
-void ChatViewSearchController::setScene(ChatScene *scene)
+void ChatViewSearchController::setScene(ChatScene* scene)
{
Q_ASSERT(scene);
if (scene == _scene)
updateHighlights();
}
-
void ChatViewSearchController::highlightNext()
{
if (_highlightItems.isEmpty())
emit newCurrentHighlight(_highlightItems.at(_currentHighlight));
}
-
void ChatViewSearchController::highlightPrev()
{
if (_highlightItems.isEmpty())
emit newCurrentHighlight(_highlightItems.at(_currentHighlight));
}
-
void ChatViewSearchController::updateHighlights(bool reuse)
{
if (!_scene)
return;
if (reuse) {
- QSet<ChatLine *> chatLines;
- foreach(SearchHighlightItem *highlightItem, _highlightItems) {
- auto *line = qgraphicsitem_cast<ChatLine *>(highlightItem->parentItem());
+ QSet<ChatLine*> chatLines;
+ foreach (SearchHighlightItem* highlightItem, _highlightItems) {
+ auto* line = qgraphicsitem_cast<ChatLine*>(highlightItem->parentItem());
if (line)
chatLines << line;
}
- foreach(ChatLine *line, QList<ChatLine *>(chatLines.toList())) {
+ foreach (ChatLine* line, QList<ChatLine*>(chatLines.toList())) {
updateHighlights(line);
}
}
if (!_highlightItems.isEmpty()) {
if (!oldHighlightPos.isNull()) {
- int start = 0; int end = _highlightItems.count() - 1;
+ int start = 0;
+ int end = _highlightItems.count() - 1;
QPointF startPos;
QPointF endPos;
while (true) {
}
}
-
void ChatViewSearchController::checkMessagesForHighlight(int start, int end)
{
- QAbstractItemModel *model = _scene->model();
+ QAbstractItemModel* model = _scene->model();
Q_ASSERT(model);
if (end == -1) {
}
}
-
-void ChatViewSearchController::updateHighlights(ChatLine *line)
+void ChatViewSearchController::updateHighlights(ChatLine* line)
{
- QList<ChatItem *> checkItems;
+ QList<ChatItem*> checkItems;
if (_searchSenders)
checkItems << line->item(MessageModel::SenderColumn);
if (_searchMsgs)
checkItems << line->item(MessageModel::ContentsColumn);
- QHash<quint64, QHash<quint64, QRectF> > wordRects;
- foreach(ChatItem *item, checkItems) {
- foreach(QRectF wordRect, item->findWords(searchString(), caseSensitive())) {
+ QHash<quint64, QHash<quint64, QRectF>> wordRects;
+ foreach (ChatItem* item, checkItems) {
+ foreach (QRectF wordRect, item->findWords(searchString(), caseSensitive())) {
wordRects[(quint64)(wordRect.x() + item->x())][(quint64)(wordRect.y())] = wordRect;
}
}
bool deleteAll = false;
- QAbstractItemModel *model = _scene->model();
+ QAbstractItemModel* model = _scene->model();
Q_ASSERT(model);
if (_searchOnlyRegularMsgs) {
QModelIndex index = model->index(line->row(), 0);
deleteAll = true;
}
- foreach(QGraphicsItem *child, line->childItems()) {
- auto *highlightItem = qgraphicsitem_cast<SearchHighlightItem *>(child);
+ foreach (QGraphicsItem* child, line->childItems()) {
+ auto* highlightItem = qgraphicsitem_cast<SearchHighlightItem*>(child);
if (!highlightItem)
continue;
- if (!deleteAll && wordRects.contains((quint64)(highlightItem->pos().x())) && wordRects[(quint64)(highlightItem->pos().x())].contains((quint64)(highlightItem->pos().y()))) {
- QRectF &wordRect = wordRects[(quint64)(highlightItem->pos().x())][(quint64)(highlightItem->pos().y())];
+ if (!deleteAll && wordRects.contains((quint64)(highlightItem->pos().x()))
+ && wordRects[(quint64)(highlightItem->pos().x())].contains((quint64)(highlightItem->pos().y()))) {
+ QRectF& wordRect = wordRects[(quint64)(highlightItem->pos().x())][(quint64)(highlightItem->pos().y())];
highlightItem->updateGeometry(wordRect.width(), wordRect.height());
}
else {
}
}
-
-void ChatViewSearchController::highlightLine(ChatLine *line)
+void ChatViewSearchController::highlightLine(ChatLine* line)
{
- QList<ChatItem *> checkItems;
+ QList<ChatItem*> checkItems;
if (_searchSenders)
checkItems << line->item(MessageModel::SenderColumn);
if (_searchMsgs)
checkItems << line->item(MessageModel::ContentsColumn);
- foreach(ChatItem *item, checkItems) {
- foreach(QRectF wordRect, item->findWords(searchString(), caseSensitive())) {
+ foreach (ChatItem* item, checkItems) {
+ foreach (QRectF wordRect, item->findWords(searchString(), caseSensitive())) {
_highlightItems << new SearchHighlightItem(wordRect.adjusted(item->x(), 0, item->x(), 0), line);
}
}
}
-
void ChatViewSearchController::repositionHighlights()
{
- QSet<ChatLine *> chatLines;
- foreach(SearchHighlightItem *item, _highlightItems) {
- auto *line = qgraphicsitem_cast<ChatLine *>(item->parentItem());
+ QSet<ChatLine*> chatLines;
+ foreach (SearchHighlightItem* item, _highlightItems) {
+ auto* line = qgraphicsitem_cast<ChatLine*>(item->parentItem());
if (line)
chatLines << line;
}
- QList<ChatLine *> chatLineList(chatLines.toList());
- foreach(ChatLine *line, chatLineList) {
+ QList<ChatLine*> chatLineList(chatLines.toList());
+ foreach (ChatLine* line, chatLineList) {
repositionHighlights(line);
}
}
-
-void ChatViewSearchController::repositionHighlights(ChatLine *line)
+void ChatViewSearchController::repositionHighlights(ChatLine* line)
{
- QList<SearchHighlightItem *> searchHighlights;
- foreach(QGraphicsItem *child, line->childItems()) {
- auto *highlightItem = qgraphicsitem_cast<SearchHighlightItem *>(child);
+ QList<SearchHighlightItem*> searchHighlights;
+ foreach (QGraphicsItem* child, line->childItems()) {
+ auto* highlightItem = qgraphicsitem_cast<SearchHighlightItem*>(child);
if (highlightItem)
searchHighlights << highlightItem;
}
QList<QPointF> wordPos;
if (_searchSenders) {
- foreach(QRectF wordRect, line->senderItem()->findWords(searchString(), caseSensitive())) {
+ foreach (QRectF wordRect, line->senderItem()->findWords(searchString(), caseSensitive())) {
wordPos << QPointF(wordRect.x() + line->senderItem()->x(), wordRect.y());
}
}
if (_searchMsgs) {
- foreach(QRectF wordRect, line->contentsItem()->findWords(searchString(), caseSensitive())) {
+ foreach (QRectF wordRect, line->contentsItem()->findWords(searchString(), caseSensitive())) {
wordPos << QPointF(wordRect.x() + line->contentsItem()->x(), wordRect.y());
}
}
}
}
-
void ChatViewSearchController::sceneDestroyed()
{
// WARNING: don't call any methods on scene!
_highlightItems.clear();
}
-
void ChatViewSearchController::setCaseSensitive(bool caseSensitive)
{
if (_caseSensitive == caseSensitive)
updateHighlights(caseSensitive);
}
-
void ChatViewSearchController::setSearchSenders(bool searchSenders)
{
if (_searchSenders == searchSenders)
updateHighlights(!searchSenders);
}
-
void ChatViewSearchController::setSearchMsgs(bool searchMsgs)
{
if (_searchMsgs == searchMsgs)
updateHighlights(!searchMsgs);
}
-
void ChatViewSearchController::setSearchOnlyRegularMsgs(bool searchOnlyRegularMsgs)
{
if (_searchOnlyRegularMsgs == searchOnlyRegularMsgs)
updateHighlights(searchOnlyRegularMsgs);
}
-
// ==================================================
// SearchHighlightItem
// ==================================================
-SearchHighlightItem::SearchHighlightItem(QRectF wordRect, QGraphicsItem *parent)
- : QObject(),
- QGraphicsItem(parent),
- _highlighted(false),
- _alpha(70),
- _timeLine(150)
+SearchHighlightItem::SearchHighlightItem(QRectF wordRect, QGraphicsItem* parent)
+ : QObject()
+ , QGraphicsItem(parent)
+ , _highlighted(false)
+ , _alpha(70)
+ , _timeLine(150)
{
setPos(wordRect.x(), wordRect.y());
updateGeometry(wordRect.width(), wordRect.height());
connect(&_timeLine, &QTimeLine::valueChanged, this, &SearchHighlightItem::updateHighlight);
}
-
void SearchHighlightItem::setHighlighted(bool highlighted)
{
_highlighted = highlighted;
update();
}
-
void SearchHighlightItem::updateHighlight(qreal value)
{
_alpha = 70 + (int)(80 * value);
update();
}
-
-void SearchHighlightItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
+void SearchHighlightItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->drawRoundedRect(boundingRect(), radius, radius);
}
-
void SearchHighlightItem::updateGeometry(qreal width, qreal height)
{
prepareGeometryChange();
update();
}
-
-bool SearchHighlightItem::firstInLine(QGraphicsItem *item1, QGraphicsItem *item2)
+bool SearchHighlightItem::firstInLine(QGraphicsItem* item1, QGraphicsItem* item2)
{
if (item1->pos().y() != item2->pos().y())
return item1->pos().y() < item2->pos().y();
Q_OBJECT
public:
- ChatViewSearchController(QObject *parent = nullptr);
+ ChatViewSearchController(QObject* parent = nullptr);
- inline const QString &searchString() const { return _searchString; }
+ inline const QString& searchString() const { return _searchString; }
- void setScene(ChatScene *scene);
+ void setScene(ChatScene* scene);
public slots:
- void setSearchString(const QString &searchString);
+ void setSearchString(const QString& searchString);
void setCaseSensitive(bool caseSensitive);
void setSearchSenders(bool searchSenders);
void setSearchMsgs(bool searchMsgs);
void updateHighlights(bool reuse = false);
void repositionHighlights();
- void repositionHighlights(ChatLine *line);
+ void repositionHighlights(ChatLine* line);
signals:
- void newCurrentHighlight(QGraphicsItem *highlightItem);
+ void newCurrentHighlight(QGraphicsItem* highlightItem);
private:
QString _searchString;
- ChatScene *_scene{nullptr};
- QList<SearchHighlightItem *> _highlightItems;
+ ChatScene* _scene{nullptr};
+ QList<SearchHighlightItem*> _highlightItems;
int _currentHighlight{0};
bool _caseSensitive{false};
inline bool checkType(Message::Type type) const { return type & (Message::Plain | Message::Notice | Message::Action); }
void checkMessagesForHighlight(int start = 0, int end = -1);
- void highlightLine(ChatLine *line);
- void updateHighlights(ChatLine *line);
+ void highlightLine(ChatLine* line);
+ void updateHighlights(ChatLine* line);
};
-
// Highlight Items
class SearchHighlightItem : public QObject, public QGraphicsItem
{
Q_INTERFACES(QGraphicsItem)
public:
- SearchHighlightItem(QRectF wordRect, QGraphicsItem *parent = nullptr);
+ SearchHighlightItem(QRectF wordRect, QGraphicsItem* parent = nullptr);
inline QRectF boundingRect() const override { return _boundingRect; }
void updateGeometry(qreal width, qreal height);
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override;
- enum { Type = ChatScene::SearchHighlightType };
+ void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override;
+ enum
+ {
+ Type = ChatScene::SearchHighlightType
+ };
inline int type() const override { return Type; }
void setHighlighted(bool highlighted);
- static bool firstInLine(QGraphicsItem *item1, QGraphicsItem *item2);
+ static bool firstInLine(QGraphicsItem* item1, QGraphicsItem* item2);
private slots:
void updateHighlight(qreal value);
QTimeLine _timeLine;
};
-
-#endif //CHATVIEWSEARCHCONTROLLER_H
+#endif // CHATVIEWSEARCHCONTROLLER_H
#include "chatscene.h"
#include "chatview.h"
-ChatViewSettings::ChatViewSettings(const QString &id)
+ChatViewSettings::ChatViewSettings(const QString& id)
: QtUiSettings(QString("ChatView/%1").arg(id))
-{
-}
-
+{}
-ChatViewSettings::ChatViewSettings(ChatScene *scene)
+ChatViewSettings::ChatViewSettings(ChatScene* scene)
: QtUiSettings(QString("ChatView/%1").arg(scene->idString()))
-{
-}
+{}
-
-ChatViewSettings::ChatViewSettings(ChatView *view)
+ChatViewSettings::ChatViewSettings(ChatView* view)
: QtUiSettings(QString("ChatView/%1").arg(view->scene()->idString()))
-{
-}
-
+{}
bool ChatViewSettings::showWebPreview() const
{
return localValue("ShowWebPreview", false).toBool();
}
-
void ChatViewSettings::enableWebPreview(bool enabled)
{
setLocalValue("ShowWebPreview", enabled);
}
-
bool ChatViewSettings::useCustomTimestampFormat() const
{
return localValue("UseCustomTimestampFormat", false).toBool();
}
-
void ChatViewSettings::setUseCustomTimestampFormat(bool enabled)
{
setLocalValue("UseCustomTimestampFormat", enabled);
}
-
QString ChatViewSettings::timestampFormatString() const
{
// Include a space in the default TimestampFormat to give the timestamp a small bit of padding
return localValue("TimestampFormat", " hh:mm:ss").toString();
}
-
-void ChatViewSettings::setTimestampFormatString(const QString &format)
+void ChatViewSettings::setTimestampFormatString(const QString& format)
{
setLocalValue("TimestampFormat", format);
}
-
UiStyle::SenderPrefixMode ChatViewSettings::senderPrefixDisplay() const
{
return static_cast<UiStyle::SenderPrefixMode>(
- localValue("SenderPrefixMode",
- QVariant::fromValue<UiStyle::SenderPrefixMode>(
- UiStyle::SenderPrefixMode::HighestMode)).toInt());
+ localValue("SenderPrefixMode", QVariant::fromValue<UiStyle::SenderPrefixMode>(UiStyle::SenderPrefixMode::HighestMode)).toInt());
// Cast the QVariant to an integer, then cast that to the enum class.
// .canConvert<UiStyle::SenderPrefixMode>() returned true, but
// .value<UiStyle::SenderPrefixMode>(); always gave the default value 0.
// There's probably a cleaner way of doing this. I couldn't find it within 4 hours, so...
}
-
bool ChatViewSettings::showSenderBrackets() const
{
return localValue("ShowSenderBrackets", false).toBool();
}
-
void ChatViewSettings::enableSenderBrackets(bool enabled)
{
setLocalValue("ShowSenderBrackets", enabled);
}
-
QString ChatViewSettings::webSearchUrlFormatString() const
{
return localValue("WebSearchUrlFormat", "https://www.google.com/search?q=%s").toString();
}
-
-void ChatViewSettings::setWebSearchUrlFormatString(const QString &format)
+void ChatViewSettings::setWebSearchUrlFormatString(const QString& format)
{
setLocalValue("WebSearchUrlFormat", format);
}
public:
Q_ENUMS(OperationMode)
public:
- enum OperationMode {
+ enum OperationMode
+ {
InvalidMode = 0,
OptIn = 1,
OptOut = 2
};
Q_DECLARE_FLAGS(OperationModes, OperationMode)
- ChatViewSettings(const QString &id = "__default__");
- ChatViewSettings(ChatScene *scene);
- ChatViewSettings(ChatView *view);
+ ChatViewSettings(const QString& id = "__default__");
+ ChatViewSettings(ChatScene* scene);
+ ChatViewSettings(ChatView* view);
bool showWebPreview() const;
void enableWebPreview(bool enabled);
*
* @param[in] format String representing timestamp format, e.g. "[hh:mm:ss]" or " hh:mm:ss"
*/
- void setTimestampFormatString(const QString &format);
+ void setTimestampFormatString(const QString& format);
/**
* Gets how prefix modes are shown before sender names
void enableSenderBrackets(bool enabled);
QString webSearchUrlFormatString() const;
- void setWebSearchUrlFormatString(const QString &format);
+ void setWebSearchUrlFormatString(const QString& format);
};
Q_DECLARE_METATYPE(ChatViewSettings::OperationMode)
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include "chatview.h"
#include "columnhandleitem.h"
#include <QApplication>
#include <QPainter>
#include <QPalette>
-ColumnHandleItem::ColumnHandleItem(qreal w, QGraphicsItem *parent)
- : QGraphicsObject(parent),
- _width(w),
- _boundingRect(-_width/2, 0, _width, 0),
- _moving(false),
- _offset(0),
- _minXPos(0),
- _maxXPos(0),
- _opacity(0),
- _animation(new QPropertyAnimation(this, "opacity", this))
+#include "chatview.h"
+
+ColumnHandleItem::ColumnHandleItem(qreal w, QGraphicsItem* parent)
+ : QGraphicsObject(parent)
+ , _width(w)
+ , _boundingRect(-_width / 2, 0, _width, 0)
+ , _moving(false)
+ , _offset(0)
+ , _minXPos(0)
+ , _maxXPos(0)
+ , _opacity(0)
+ , _animation(new QPropertyAnimation(this, "opacity", this))
{
setAcceptHoverEvents(true);
setZValue(10);
_animation->setEasingCurve(QEasingCurve::InOutSine);
}
-
void ColumnHandleItem::setXPos(qreal xpos)
{
setPos(xpos, 0);
emit positionChanged(xpos);
}
-
void ColumnHandleItem::setXLimits(qreal min, qreal max)
{
_minXPos = min;
_maxXPos = max;
- //if(x() < min) setPos(min, 0);
- //else if(x() > max) setPos(max - width(), 0);
+ // if(x() < min) setPos(min, 0);
+ // else if(x() > max) setPos(max - width(), 0);
}
-
-void ColumnHandleItem::sceneRectChanged(const QRectF &rect)
+void ColumnHandleItem::sceneRectChanged(const QRectF& rect)
{
prepareGeometryChange();
- _boundingRect = QRectF(-_width/2, rect.y(), _width, rect.height());
+ _boundingRect = QRectF(-_width / 2, rect.y(), _width, rect.height());
}
-
void ColumnHandleItem::setOpacity(qreal opacity)
{
_opacity = opacity;
update();
}
-
-void ColumnHandleItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
+void ColumnHandleItem::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
if (event->buttons() & Qt::LeftButton && _moving) {
qreal newx = event->scenePos().x() - _offset;
}
}
-
-void ColumnHandleItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
+void ColumnHandleItem::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
if (event->buttons() & Qt::LeftButton) {
QApplication::setOverrideCursor(Qt::ClosedHandCursor);
}
}
-
-void ColumnHandleItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
+void ColumnHandleItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
{
if (_moving) {
_moving = false;
}
}
-
-void ColumnHandleItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
+void ColumnHandleItem::hoverEnterEvent(QGraphicsSceneHoverEvent* event)
{
Q_UNUSED(event);
_animation->start();
}
-
-void ColumnHandleItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event)
+void ColumnHandleItem::hoverLeaveEvent(QGraphicsSceneHoverEvent* event)
{
Q_UNUSED(event);
_animation->start();
}
-
-void ColumnHandleItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
+void ColumnHandleItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
Q_OBJECT
Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity)
-public :
- ColumnHandleItem(qreal width, QGraphicsItem *parent = nullptr);
+public:
+ ColumnHandleItem(qreal width, QGraphicsItem* parent = nullptr);
inline int type() const override { return ChatScene::ColumnHandleType; }
inline qreal width() const { return _width; }
void setXPos(qreal xpos);
void setXLimits(qreal min, qreal max);
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override;
+ void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override;
public slots:
- void sceneRectChanged(const QRectF &);
+ void sceneRectChanged(const QRectF&);
void setOpacity(qreal opacity);
protected:
- void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override;
- void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override;
- void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
- void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
- void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
+ void hoverEnterEvent(QGraphicsSceneHoverEvent* event) override;
+ void hoverLeaveEvent(QGraphicsSceneHoverEvent* event) override;
+ void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override;
+ void mousePressEvent(QGraphicsSceneMouseEvent* event) override;
+ void mouseReleaseEvent(QGraphicsSceneMouseEvent* event) override;
signals:
void positionChanged(qreal x);
qreal _offset;
qreal _minXPos, _maxXPos;
qreal _opacity;
- QPropertyAnimation *_animation;
+ QPropertyAnimation* _animation;
};
-
#endif
#include "coreconfigwizard.h"
-#include <QDebug>
#include <QAbstractButton>
#include <QCoreApplication>
+#include <QDebug>
#include <QFormLayout>
#include <QSpinBox>
namespace {
-QGroupBox *createDescriptionBox(const QString &description)
+QGroupBox* createDescriptionBox(const QString& description)
{
auto box = new QGroupBox;
auto layout = new QVBoxLayout(box);
return box;
}
-
template<typename FieldInfo>
-QGroupBox *createFieldBox(const QString &title, const std::vector<FieldInfo> &fieldInfos)
+QGroupBox* createFieldBox(const QString& title, const std::vector<FieldInfo>& fieldInfos)
{
// Create a config UI based on the field types sent from the backend
// We make some assumptions here (like integer range and password field names) that may not
// provide specialized config widgets for those (which may be a good idea anyway, e.g. if we
// think about client-side translations...)
- auto *fieldBox = new QGroupBox;
+ auto* fieldBox = new QGroupBox;
fieldBox->setTitle(title);
- auto *formLayout = new QFormLayout;
+ auto* formLayout = new QFormLayout;
fieldBox->setLayout(formLayout);
- for (auto &&fieldInfo : fieldInfos) {
- QWidget *widget {nullptr};
+ for (auto&& fieldInfo : fieldInfos) {
+ QWidget* widget{nullptr};
switch (std::get<2>(fieldInfo).type()) {
- case QVariant::Int:
- widget = new QSpinBox(fieldBox);
- // Here we assume that int fields are always in 16 bit range, like ports
- static_cast<QSpinBox *>(widget)->setMinimum(0);
- static_cast<QSpinBox *>(widget)->setMaximum(65535);
- static_cast<QSpinBox *>(widget)->setValue(std::get<2>(fieldInfo).toInt());
- break;
- case QVariant::String:
- widget = new QLineEdit(std::get<2>(fieldInfo).toString(), fieldBox);
- // Here we assume that fields named something with "password" are actual password inputs
- if (std::get<0>(fieldInfo).toLower().contains("password"))
- static_cast<QLineEdit *>(widget)->setEchoMode(QLineEdit::Password);
- break;
- default:
- qWarning() << "Unsupported type for backend property" << std::get<0>(fieldInfo);
+ case QVariant::Int:
+ widget = new QSpinBox(fieldBox);
+ // Here we assume that int fields are always in 16 bit range, like ports
+ static_cast<QSpinBox*>(widget)->setMinimum(0);
+ static_cast<QSpinBox*>(widget)->setMaximum(65535);
+ static_cast<QSpinBox*>(widget)->setValue(std::get<2>(fieldInfo).toInt());
+ break;
+ case QVariant::String:
+ widget = new QLineEdit(std::get<2>(fieldInfo).toString(), fieldBox);
+ // Here we assume that fields named something with "password" are actual password inputs
+ if (std::get<0>(fieldInfo).toLower().contains("password"))
+ static_cast<QLineEdit*>(widget)->setEchoMode(QLineEdit::Password);
+ break;
+ default:
+ qWarning() << "Unsupported type for backend property" << std::get<0>(fieldInfo);
}
if (widget) {
widget->setObjectName(std::get<0>(fieldInfo));
return fieldBox;
}
-
template<typename FieldInfo>
-QVariantMap propertiesFromFieldWidgets(QGroupBox *fieldBox, const std::vector<FieldInfo> &fieldInfos)
+QVariantMap propertiesFromFieldWidgets(QGroupBox* fieldBox, const std::vector<FieldInfo>& fieldInfos)
{
QVariantMap properties;
if (!fieldBox)
return properties;
- for (auto &&fieldInfo : fieldInfos) {
+ for (auto&& fieldInfo : fieldInfos) {
QString key = std::get<0>(fieldInfo);
QVariant value;
switch (std::get<2>(fieldInfo).type()) {
- case QVariant::Int: {
- auto *spinBox = fieldBox->findChild<QSpinBox *>(key);
- if (spinBox)
- value = spinBox->value();
- else
- qWarning() << "Could not find child widget for field" << key;
- break;
- }
- case QVariant::String: {
- auto *lineEdit = fieldBox->findChild<QLineEdit *>(key);
- if (lineEdit)
- value = lineEdit->text();
- else
- qWarning() << "Could not find child widget for field" << key;
- break;
- }
- default:
- qWarning() << "Unsupported type for backend property" << key;
+ case QVariant::Int: {
+ auto* spinBox = fieldBox->findChild<QSpinBox*>(key);
+ if (spinBox)
+ value = spinBox->value();
+ else
+ qWarning() << "Could not find child widget for field" << key;
+ break;
+ }
+ case QVariant::String: {
+ auto* lineEdit = fieldBox->findChild<QLineEdit*>(key);
+ if (lineEdit)
+ value = lineEdit->text();
+ else
+ qWarning() << "Could not find child widget for field" << key;
+ break;
+ }
+ default:
+ qWarning() << "Unsupported type for backend property" << key;
}
properties[key] = std::move(value);
}
return properties;
}
-} // anon
-
+} // namespace
-CoreConfigWizard::CoreConfigWizard(CoreConnection *connection, const QVariantList &backendInfos, const QVariantList &authInfos, QWidget *parent)
- : QWizard(parent),
- _connection{connection}
+CoreConfigWizard::CoreConfigWizard(CoreConnection* connection, const QVariantList& backendInfos, const QVariantList& authInfos, QWidget* parent)
+ : QWizard(parent)
+ , _connection{connection}
{
setModal(true);
setAttribute(Qt::WA_DeleteOnClose);
setPage(AuthenticationSelectionPage, new CoreConfigWizardPages::AuthenticationSelectionPage(authInfos, this));
setPage(StorageSelectionPage, new CoreConfigWizardPages::StorageSelectionPage(backendInfos, this));
syncPage = new CoreConfigWizardPages::SyncPage(this);
- connect(syncPage, &CoreConfigWizardPages::SyncPage::setupCore,
- this, &CoreConfigWizard::prepareCoreSetup);
+ connect(syncPage, &CoreConfigWizardPages::SyncPage::setupCore, this, &CoreConfigWizard::prepareCoreSetup);
setPage(SyncPage, syncPage);
syncRelayPage = new CoreConfigWizardPages::SyncRelayPage(this);
connect(syncRelayPage, &CoreConfigWizardPages::SyncRelayPage::startOver, this, &CoreConfigWizard::startOver);
connect(connection, &CoreConnection::synchronized, this, &CoreConfigWizard::syncFinished);
connect(this, &QDialog::rejected, connection, selectOverload<>(&CoreConnection::disconnectFromCore));
-
// Resize all pages to the size hint of the largest one, so the wizard is large enough
QSize maxSize;
for (int id : pageIds()) {
}
}
-
-void CoreConfigWizard::prepareCoreSetup(const QString &backend, const QVariantMap &properties, const QString &authenticator, const QVariantMap &authProperties)
+void CoreConfigWizard::prepareCoreSetup(const QString& backend,
+ const QVariantMap& properties,
+ const QString& authenticator,
+ const QVariantMap& authProperties)
{
// Prevent the user from changing any settings he already specified...
- for (auto &&idx : visitedPages())
+ for (auto&& idx : visitedPages())
page(idx)->setEnabled(false);
// FIXME? We need to be able to set up older cores that don't have auth backend support.
// So if the core doesn't support that feature, don't pass those parameters.
if (!Client::isCoreFeatureEnabled(Quassel::Feature::Authenticators)) {
- coreConnection()->setupCore(Protocol::SetupData(field("adminUser.user").toString(), field("adminUser.password").toString(), backend, properties));
+ coreConnection()->setupCore(
+ Protocol::SetupData(field("adminUser.user").toString(), field("adminUser.password").toString(), backend, properties));
}
else {
- coreConnection()->setupCore(Protocol::SetupData(field("adminUser.user").toString(), field("adminUser.password").toString(), backend, properties, authenticator, authProperties));
+ coreConnection()->setupCore(Protocol::SetupData(field("adminUser.user").toString(),
+ field("adminUser.password").toString(),
+ backend,
+ properties,
+ authenticator,
+ authProperties));
}
}
-
void CoreConfigWizard::coreSetupSuccess()
{
syncPage->setStatus(tr("Your core has been successfully configured. Logging you in..."));
syncPage->setError(false);
syncRelayPage->setMode(CoreConfigWizardPages::SyncRelayPage::Success);
- coreConnection()->loginToCore(field("adminUser.user").toString(), field("adminUser.password").toString(), field("adminUser.rememberPasswd").toBool());
+ coreConnection()->loginToCore(field("adminUser.user").toString(),
+ field("adminUser.password").toString(),
+ field("adminUser.rememberPasswd").toBool());
}
-
-void CoreConfigWizard::coreSetupFailed(const QString &error)
+void CoreConfigWizard::coreSetupFailed(const QString& error)
{
syncPage->setStatus(tr("Core configuration failed:<br><b>%1</b><br>Press <em>Next</em> to start over.").arg(error));
syncPage->setError(true);
syncRelayPage->setMode(CoreConfigWizardPages::SyncRelayPage::Error);
- //foreach(int idx, visitedPages()) page(idx)->setEnabled(true);
- //setStartId(SyncPage);
- //restart();
+ // foreach(int idx, visitedPages()) page(idx)->setEnabled(true);
+ // setStartId(SyncPage);
+ // restart();
}
-
void CoreConfigWizard::startOver()
{
- foreach(int idx, visitedPages()) page(idx)->setEnabled(true);
+ foreach (int idx, visitedPages())
+ page(idx)->setEnabled(true);
setStartId(CoreConfigWizard::AdminUserPage);
restart();
}
-
void CoreConfigWizard::syncFinished()
{
accept();
}
-
namespace CoreConfigWizardPages {
/*** Intro Page ***/
-IntroPage::IntroPage(QWidget *parent) : QWizardPage(parent)
+IntroPage::IntroPage(QWidget* parent)
+ : QWizardPage(parent)
{
ui.setupUi(this);
setTitle(tr("Introduction"));
- //setSubTitle(tr("foobar"));
- //setPixmap(QWizard::WatermarkPixmap, QPixmap(":icons/quassel-icon.png"));
+ // setSubTitle(tr("foobar"));
+ // setPixmap(QWizard::WatermarkPixmap, QPixmap(":icons/quassel-icon.png"));
}
-
int IntroPage::nextId() const
{
return CoreConfigWizard::AdminUserPage;
}
-
/*** Admin User Page ***/
-AdminUserPage::AdminUserPage(QWidget *parent) : QWizardPage(parent)
+AdminUserPage::AdminUserPage(QWidget* parent)
+ : QWizardPage(parent)
{
ui.setupUi(this);
setTitle(tr("Create Admin User"));
registerField("adminUser.rememberPasswd", ui.rememberPasswd);
}
-
int AdminUserPage::nextId() const
{
// If the core doesn't support auth backends, skip that page!
}
}
-
bool AdminUserPage::isComplete() const
{
bool ok = !ui.user->text().isEmpty() && !ui.password->text().isEmpty() && ui.password->text() == ui.password2->text();
/*** Authentication Selection Page ***/
-AuthenticationSelectionPage::AuthenticationSelectionPage(const QVariantList &authInfos, QWidget *parent)
+AuthenticationSelectionPage::AuthenticationSelectionPage(const QVariantList& authInfos, QWidget* parent)
: QWizardPage(parent)
{
ui.setupUi(this);
registerField("authentication.backend", ui.backendList);
- for (auto &&authInfo : authInfos) {
+ for (auto&& authInfo : authInfos) {
auto props = authInfo.toMap();
// Extract field infos to avoid having to reparse the list
std::vector<FieldInfo> fields;
- const auto &list = props["SetupData"].toList();
+ const auto& list = props["SetupData"].toList();
for (int i = 0; i + 2 < list.size(); i += 3) {
- fields.emplace_back(std::make_tuple(list[i].toString(), list[i+1].toString(), list[i+2]));
+ fields.emplace_back(std::make_tuple(list[i].toString(), list[i + 1].toString(), list[i + 2]));
}
props.remove("SetupData");
ui.backendList->setCurrentIndex(0);
}
-
int AuthenticationSelectionPage::nextId() const
{
return CoreConfigWizard::StorageSelectionPage;
}
-
QString AuthenticationSelectionPage::displayName() const
{
return ui.backendList->currentText();
}
-
QString AuthenticationSelectionPage::authenticator() const
{
return ui.backendList->currentData().toString();
}
-
QVariantMap AuthenticationSelectionPage::authProperties() const
{
- return propertiesFromFieldWidgets(qobject_cast<QGroupBox *>(ui.authSettingsStack->currentWidget()),
+ return propertiesFromFieldWidgets(qobject_cast<QGroupBox*>(ui.authSettingsStack->currentWidget()),
_authFields[ui.backendList->currentIndex()]);
}
-
void AuthenticationSelectionPage::on_backendList_currentIndexChanged(int index)
{
ui.descriptionStack->setCurrentIndex(index);
/*** Storage Selection Page ***/
-StorageSelectionPage::StorageSelectionPage(const QVariantList &backendInfos, QWidget *parent)
+StorageSelectionPage::StorageSelectionPage(const QVariantList& backendInfos, QWidget* parent)
: QWizardPage(parent)
{
ui.setupUi(this);
registerField("storage.backend", ui.backendList);
- int defaultIndex {0}; // Legacy cores send backend infos in arbitrary order
+ int defaultIndex{0}; // Legacy cores send backend infos in arbitrary order
- for (auto &&backendInfo : backendInfos) {
+ for (auto&& backendInfo : backendInfos) {
auto props = backendInfo.toMap();
// Extract field infos to avoid having to reparse the list
std::vector<FieldInfo> fields;
// Legacy cores (prior to 0.13) didn't send SetupData for storage backends; deal with this
if (!props.contains("SetupData")) {
- const auto &defaultValues = props["SetupDefaults"].toMap();
- for (auto &&key : props["SetupKeys"].toStringList()) {
+ const auto& defaultValues = props["SetupDefaults"].toMap();
+ for (auto&& key : props["SetupKeys"].toStringList()) {
fields.emplace_back(std::make_tuple(key, key, defaultValues.value(key, QString{})));
}
if (props.value("IsDefault", false).toBool()) {
}
}
else {
- const auto &list = props["SetupData"].toList();
+ const auto& list = props["SetupData"].toList();
for (int i = 0; i + 2 < list.size(); i += 3) {
- fields.emplace_back(std::make_tuple(list[i].toString(), list[i+1].toString(), list[i+2]));
+ fields.emplace_back(std::make_tuple(list[i].toString(), list[i + 1].toString(), list[i + 2]));
}
props.remove("SetupData");
}
ui.backendList->setCurrentIndex(defaultIndex);
}
-
int StorageSelectionPage::nextId() const
{
return CoreConfigWizard::SyncPage;
}
-
QString StorageSelectionPage::displayName() const
{
return ui.backendList->currentText();
}
-
QString StorageSelectionPage::backend() const
{
return ui.backendList->currentData().toString();
}
-
QVariantMap StorageSelectionPage::backendProperties() const
{
- return propertiesFromFieldWidgets(qobject_cast<QGroupBox *>(ui.storageSettingsStack->currentWidget()),
+ return propertiesFromFieldWidgets(qobject_cast<QGroupBox*>(ui.storageSettingsStack->currentWidget()),
_backendFields[ui.backendList->currentIndex()]);
}
-
void StorageSelectionPage::on_backendList_currentIndexChanged(int index)
{
ui.descriptionStack->setCurrentIndex(index);
ui.storageSettingsStack->setVisible(!_backendFields[index].empty());
}
-
/*** Sync Page ***/
-SyncPage::SyncPage(QWidget *parent) : QWizardPage(parent)
+SyncPage::SyncPage(QWidget* parent)
+ : QWizardPage(parent)
{
ui.setupUi(this);
setTitle(tr("Storing Your Settings"));
setSubTitle(tr("Your settings are now being stored in the core, and you will be logged in automatically."));
}
-
void SyncPage::initializePage()
{
_complete = false;
emit completeChanged();
// Fill in sync info about the storage layer.
- auto *storagePage = qobject_cast<StorageSelectionPage *>(wizard()->page(CoreConfigWizard::StorageSelectionPage));
+ auto* storagePage = qobject_cast<StorageSelectionPage*>(wizard()->page(CoreConfigWizard::StorageSelectionPage));
QString backend = storagePage->backend();
QVariantMap backendProperties = storagePage->backendProperties();
ui.backend->setText(storagePage->displayName());
// Fill in sync info about the authentication layer.
- auto *authPage = qobject_cast<AuthenticationSelectionPage *>(wizard()->page(CoreConfigWizard::AuthenticationSelectionPage));
+ auto* authPage = qobject_cast<AuthenticationSelectionPage*>(wizard()->page(CoreConfigWizard::AuthenticationSelectionPage));
QString authenticator = authPage->authenticator();
QVariantMap authProperties = authPage->authProperties();
ui.authenticator->setText(authPage->displayName());
emit setupCore(backend, backendProperties, authenticator, authProperties);
}
-
int SyncPage::nextId() const
{
if (!_hasError)
return CoreConfigWizard::SyncRelayPage;
}
-
bool SyncPage::isComplete() const
{
return _complete || _hasError;
}
-
-void SyncPage::setStatus(const QString &status)
+void SyncPage::setStatus(const QString& status)
{
ui.status->setText(status);
}
-
void SyncPage::setError(bool e)
{
_hasError = e;
emit completeChanged();
}
-
void SyncPage::setComplete(bool c)
{
_complete = c;
completeChanged();
}
-
/*** Sync Relay Page ***/
-SyncRelayPage::SyncRelayPage(QWidget *parent) : QWizardPage(parent)
+SyncRelayPage::SyncRelayPage(QWidget* parent)
+ : QWizardPage(parent)
{
mode = Success;
}
-
void SyncRelayPage::setMode(Mode m)
{
mode = m;
emit startOver();
return 0;
}
-} /* namespace CoreConfigWizardPages */
+} /* namespace CoreConfigWizardPages */
#include <tuple>
#include <vector>
-#include <QWizard>
#include <QVariantMap>
+#include <QWizard>
-#include "ui_coreconfigwizardintropage.h"
#include "ui_coreconfigwizardadminuserpage.h"
#include "ui_coreconfigwizardauthenticationselectionpage.h"
+#include "ui_coreconfigwizardintropage.h"
#include "ui_coreconfigwizardstorageselectionpage.h"
#include "ui_coreconfigwizardsyncpage.h"
class SyncPage;
class SyncRelayPage;
-}
+} // namespace CoreConfigWizardPages
class CoreConfigWizard : public QWizard
{
Q_OBJECT
public:
- enum {
+ enum
+ {
IntroPage,
AdminUserPage,
AuthenticationSelectionPage,
ConclusionPage
};
- CoreConfigWizard(CoreConnection *connection, const QVariantList &backendInfos, const QVariantList &authInfos, QWidget *parent = nullptr);
+ CoreConfigWizard(CoreConnection* connection, const QVariantList& backendInfos, const QVariantList& authInfos, QWidget* parent = nullptr);
- inline CoreConnection *coreConnection() const { return _connection; }
+ inline CoreConnection* coreConnection() const { return _connection; }
signals:
- void setupCore(const QVariant &setupData);
- void loginToCore(const QString &user, const QString &password, bool rememberPassword);
+ void setupCore(const QVariant& setupData);
+ void loginToCore(const QString& user, const QString& password, bool rememberPassword);
public slots:
void syncFinished();
private slots:
- void prepareCoreSetup(const QString &backend, const QVariantMap &properties, const QString &authenticator, const QVariantMap &authProperties);
+ void prepareCoreSetup(const QString& backend,
+ const QVariantMap& properties,
+ const QString& authenticator,
+ const QVariantMap& authProperties);
void coreSetupSuccess();
- void coreSetupFailed(const QString &);
+ void coreSetupFailed(const QString&);
void startOver();
private:
- CoreConfigWizardPages::SyncPage *syncPage;
- CoreConfigWizardPages::SyncRelayPage *syncRelayPage;
+ CoreConfigWizardPages::SyncPage* syncPage;
+ CoreConfigWizardPages::SyncRelayPage* syncRelayPage;
- CoreConnection *_connection;
+ CoreConnection* _connection;
};
-
namespace CoreConfigWizardPages {
class IntroPage : public QWizardPage
Q_OBJECT
public:
- IntroPage(QWidget *parent = nullptr);
+ IntroPage(QWidget* parent = nullptr);
int nextId() const override;
+
private:
Ui::CoreConfigWizardIntroPage ui;
};
-
class AdminUserPage : public QWizardPage
{
Q_OBJECT
public:
- AdminUserPage(QWidget *parent = nullptr);
+ AdminUserPage(QWidget* parent = nullptr);
int nextId() const override;
bool isComplete() const override;
+
private:
Ui::CoreConfigWizardAdminUserPage ui;
};
-
class AuthenticationSelectionPage : public QWizardPage
{
Q_OBJECT
using FieldInfo = std::tuple<QString, QString, QVariant>;
public:
- AuthenticationSelectionPage(const QVariantList &authInfos, QWidget *parent = nullptr);
+ AuthenticationSelectionPage(const QVariantList& authInfos, QWidget* parent = nullptr);
int nextId() const override;
QString displayName() const;
QString authenticator() const;
std::vector<std::vector<FieldInfo>> _authFields;
};
-
class StorageSelectionPage : public QWizardPage
{
Q_OBJECT
using FieldInfo = std::tuple<QString, QString, QVariant>;
public:
- StorageSelectionPage(const QVariantList &backendInfos, QWidget *parent = nullptr);
+ StorageSelectionPage(const QVariantList& backendInfos, QWidget* parent = nullptr);
int nextId() const override;
QString displayName() const;
QString backend() const;
std::vector<std::vector<FieldInfo>> _backendFields;
};
-
class SyncPage : public QWizardPage
{
Q_OBJECT
public:
- SyncPage(QWidget *parent = nullptr);
+ SyncPage(QWidget* parent = nullptr);
void initializePage() override;
int nextId() const override;
bool isComplete() const override;
public slots:
- void setStatus(const QString &status);
+ void setStatus(const QString& status);
void setError(bool);
void setComplete(bool);
signals:
- void setupCore(const QString &backend, const QVariantMap &, const QString &authenticator, const QVariantMap &);
+ void setupCore(const QString& backend, const QVariantMap&, const QString& authenticator, const QVariantMap&);
private:
Ui::CoreConfigWizardSyncPage ui;
- bool _complete {false};
- bool _hasError {false};
+ bool _complete{false};
+ bool _hasError{false};
};
-
class SyncRelayPage : public QWizardPage
{
Q_OBJECT
public:
- SyncRelayPage(QWidget *parent = nullptr);
+ SyncRelayPage(QWidget* parent = nullptr);
int nextId() const override;
- enum Mode { Success, Error };
+ enum Mode
+ {
+ Success,
+ Error
+ };
public slots:
void setMode(Mode);
Mode mode;
};
-}
+} // namespace CoreConfigWizardPages
#include "coreaccountsettingspage.h"
#include "icon.h"
-CoreConnectDlg::CoreConnectDlg(QWidget *parent) : QDialog(parent)
+CoreConnectDlg::CoreConnectDlg(QWidget* parent)
+ : QDialog(parent)
{
_settingsPage = new CoreAccountSettingsPage(this);
_settingsPage->setStandAlone(true);
setWindowTitle(tr("Connect to Core"));
setWindowIcon(icon::get("network-disconnect"));
- auto *layout = new QVBoxLayout(this);
+ auto* layout = new QVBoxLayout(this);
layout->addWidget(_settingsPage);
- auto *buttonBox = new QDialogButtonBox(this);
- buttonBox->setStandardButtons(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
+ auto* buttonBox = new QDialogButtonBox(this);
+ buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
layout->addWidget(buttonBox);
connect(_settingsPage, &CoreAccountSettingsPage::connectToCore, this, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
-
AccountId CoreConnectDlg::selectedAccount() const
{
return _settingsPage->selectedAccount();
}
-
void CoreConnectDlg::accept()
{
_settingsPage->save();
QDialog::accept();
}
-
/******** CoreConnectAuthDlg ****************************************************************/
-CoreConnectAuthDlg::CoreConnectAuthDlg(CoreAccount *account, QWidget *parent)
- : QDialog(parent),
- _account(account)
+CoreConnectAuthDlg::CoreConnectAuthDlg(CoreAccount* account, QWidget* parent)
+ : QDialog(parent)
+ , _account(account)
{
ui.setupUi(this);
ui.password->setFocus();
}
-
void CoreConnectAuthDlg::accept()
{
_account->setUser(ui.user->text());
QDialog::accept();
}
-
void CoreConnectAuthDlg::setButtonStates()
{
bool valid = !(ui.user->text().isEmpty() || ui.password->text().isEmpty());
Q_OBJECT
public:
- CoreConnectDlg(QWidget *parent = nullptr);
+ CoreConnectDlg(QWidget* parent = nullptr);
AccountId selectedAccount() const;
void accept() override;
private:
- CoreAccountSettingsPage *_settingsPage;
+ CoreAccountSettingsPage* _settingsPage;
};
-
class CoreConnectAuthDlg : public QDialog
{
Q_OBJECT
public:
- CoreConnectAuthDlg(CoreAccount *account, QWidget *parent = nullptr);
+ CoreConnectAuthDlg(CoreAccount* account, QWidget* parent = nullptr);
void accept() override;
private:
Ui::CoreConnectAuthDlg ui;
- CoreAccount *_account;
+ CoreAccount* _account;
};
-
#endif
#include "icon.h"
#include "signalproxy.h"
-CoreConnectionStatusWidget::CoreConnectionStatusWidget(CoreConnection *connection, QWidget *parent)
- : QWidget(parent),
- _coreConnection(connection)
+CoreConnectionStatusWidget::CoreConnectionStatusWidget(CoreConnection* connection, QWidget* parent)
+ : QWidget(parent)
+ , _coreConnection(connection)
{
ui.setupUi(this);
ui.lagLabel->hide();
connect(coreConnection(), &CoreConnection::lagUpdated, this, &CoreConnectionStatusWidget::updateLag);
}
-
void CoreConnectionStatusWidget::update()
{
- CoreConnection *conn = coreConnection();
+ CoreConnection* conn = coreConnection();
if (conn->progressMaximum() >= 0) {
ui.progressBar->setMinimum(conn->progressMinimum());
ui.progressBar->setMaximum(conn->progressMaximum());
ui.messageLabel->setText(conn->progressText());
}
-
void CoreConnectionStatusWidget::updateLag(int msecs)
{
if (msecs >= 0) {
}
}
-
void CoreConnectionStatusWidget::connectionStateChanged(CoreConnection::ConnectionState state)
{
if (state >= CoreConnection::Connected) {
ui.sslLabel->hide();
}
-
void CoreConnectionStatusWidget::progressRangeChanged(int min, int max)
{
Q_UNUSED(min)
#include <QWidget>
-#include "ui_coreconnectionstatuswidget.h"
-
#include "coreconnection.h"
+#include "ui_coreconnectionstatuswidget.h"
+
class CoreConnectionStatusWidget : public QWidget
{
Q_OBJECT
public:
- CoreConnectionStatusWidget(CoreConnection *connection, QWidget *parent = nullptr);
+ CoreConnectionStatusWidget(CoreConnection* connection, QWidget* parent = nullptr);
- inline CoreConnection *coreConnection() const { return _coreConnection; }
+ inline CoreConnection* coreConnection() const { return _coreConnection; }
public slots:
void update();
private:
Ui::CoreConnectionStatusWidget ui;
- CoreConnection *_coreConnection;
+ CoreConnection* _coreConnection;
};
-
-#endif // CORECONNECTIONSTATUSWIDGET_H
+#endif // CORECONNECTIONSTATUSWIDGET_H
#include "icon.h"
#include "util.h"
-CoreInfoDlg::CoreInfoDlg(QWidget *parent) : QDialog(parent) {
+CoreInfoDlg::CoreInfoDlg(QWidget* parent)
+ : QDialog(parent)
+{
ui.setupUi(this);
// Listen for resynchronization events (pre-0.13 cores only)
- connect(Client::instance(), &Client::coreInfoResynchronized,
- this, &CoreInfoDlg::coreInfoResynchronized);
+ connect(Client::instance(), &Client::coreInfoResynchronized, this, &CoreInfoDlg::coreInfoResynchronized);
// Update legacy core info for Quassel cores earlier than 0.13. This does nothing on modern
// cores.
startTimer(1000);
}
-
-void CoreInfoDlg::refreshLegacyCoreInfo() {
+void CoreInfoDlg::refreshLegacyCoreInfo()
+{
if (!Client::isConnected() || Client::isCoreFeatureEnabled(Quassel::Feature::SyncedCoreInfo)) {
// If we're not connected, or the core supports SyncedCoreInfo (0.13+), bail out
return;
QTimer::singleShot(15 * 1000, this, &CoreInfoDlg::refreshLegacyCoreInfo);
}
-
-void CoreInfoDlg::coreInfoResynchronized() {
+void CoreInfoDlg::coreInfoResynchronized()
+{
// CoreInfo object has been recreated, or this is the first time the dialog's been shown
- CoreInfo *coreInfo = Client::coreInfo();
+ CoreInfo* coreInfo = Client::coreInfo();
// Listen for changes to core information
- connect(coreInfo, &CoreInfo::coreDataChanged,
- this, &CoreInfoDlg::coreInfoChanged);
+ connect(coreInfo, &CoreInfo::coreDataChanged, this, &CoreInfoDlg::coreInfoChanged);
// Update with any known core information set before connecting the signal. This is needed for
// both modern (0.13+) and legacy cores.
coreInfoChanged(coreInfo->coreData());
}
-
-void CoreInfoDlg::coreInfoChanged(const QVariantMap &coreInfo) {
- if(coreInfo.isEmpty()) {
+void CoreInfoDlg::coreInfoChanged(const QVariantMap& coreInfo)
+{
+ if (coreInfo.isEmpty()) {
// We're missing data for some reason
if (Client::isConnected()) {
// Core info is entirely empty despite being connected. Something's probably wrong.
ui.labelCoreVersion->setText(tr("Unknown"));
ui.labelCoreVersionDate->setText(tr("Unknown"));
- } else {
+ }
+ else {
// We're disconnected. Mark as such.
ui.labelCoreVersion->setText(tr("Disconnected from core"));
ui.labelCoreVersionDate->setText(tr("Not available"));
}
ui.labelClientCount->setNum(0);
// Don't return, allow the code below to remove any existing session widgets
- } else {
+ }
+ else {
ui.labelCoreVersion->setText(coreInfo["quasselVersion"].toString());
// "BuildDate" for compatibility
if (coreInfo["quasselBuildDate"].toString().isEmpty()) {
}
else {
ui.labelCoreVersionDate->setText(
- tryFormatUnixEpoch(coreInfo["quasselBuildDate"].toString(),
- Qt::DateFormat::DefaultLocaleShortDate));
+ tryFormatUnixEpoch(coreInfo["quasselBuildDate"].toString(), Qt::DateFormat::DefaultLocaleShortDate));
}
ui.labelClientCount->setNum(coreInfo["sessionConnectedClients"].toInt());
}
auto coreSessionSupported = false;
auto ids = _widgets.keys();
- for (const auto &peerData : coreInfo["sessionConnectedClientData"].toList()) {
+ for (const auto& peerData : coreInfo["sessionConnectedClientData"].toList()) {
coreSessionSupported = true;
auto peerMap = peerData.toMap();
ids.removeAll(peerId);
bool isNew = false;
- CoreSessionWidget *coreSessionWidget = _widgets[peerId];
+ CoreSessionWidget* coreSessionWidget = _widgets[peerId];
if (coreSessionWidget == nullptr) {
coreSessionWidget = new CoreSessionWidget(ui.coreSessionScrollContainer);
isNew = true;
_widgets[peerId] = coreSessionWidget;
// Add this to the end of the session list, but before the default layout stretch item.
// The layout stretch item should never be removed, so count should always be >= 1.
- ui.coreSessionContainer->insertWidget(ui.coreSessionContainer->count() - 1,
- coreSessionWidget, 0, Qt::AlignTop);
+ ui.coreSessionContainer->insertWidget(ui.coreSessionContainer->count() - 1, coreSessionWidget, 0, Qt::AlignTop);
connect(coreSessionWidget, &CoreSessionWidget::disconnectClicked, this, &CoreInfoDlg::disconnectClicked);
}
}
- for (const auto &key : ids) {
+ for (const auto& key : ids) {
delete _widgets[key];
_widgets.remove(key);
}
ui.coreSessionScrollArea->setVisible(coreSessionSupported);
// Hide the information bar when core sessions are supported or when disconnected
- ui.coreUnsupportedWidget->setVisible(
- !(coreSessionSupported || Client::isConnected() == false));
+ ui.coreUnsupportedWidget->setVisible(!(coreSessionSupported || Client::isConnected() == false));
// Update uptime for immediate display, don't wait for the timer
updateUptime();
}
-
-void CoreInfoDlg::updateUptime() {
- CoreInfo *coreInfo = Client::coreInfo();
+void CoreInfoDlg::updateUptime()
+{
+ CoreInfo* coreInfo = Client::coreInfo();
if (!Client::isConnected()) {
// Not connected, don't bother trying to calculate the uptime
ui.labelUptime->setText(tr("Not available"));
- } else if (coreInfo->coreData().isEmpty()) {
+ }
+ else if (coreInfo->coreData().isEmpty()) {
// Core info is entirely empty despite being connected. Something's probably wrong.
ui.labelUptime->setText(tr("Unknown"));
- } else {
+ }
+ else {
// Connected, format the uptime for display
QDateTime startTime = coreInfo->at("startTime").toDateTime();
int64_t upmins = uptime / 60;
uptime %= 60;
- QString uptimeText = tr("%n Day(s)", "", updays) +
- tr(" %1:%2:%3 (since %4)")
- .arg(uphours, 2, 10, QChar('0'))
- .arg(upmins, 2, 10, QChar('0'))
- .arg(uptime, 2, 10, QChar('0'))
- .arg(startTime.toLocalTime()
- .toString(Qt::DefaultLocaleShortDate));
+ QString uptimeText = tr("%n Day(s)", "", updays)
+ + tr(" %1:%2:%3 (since %4)")
+ .arg(uphours, 2, 10, QChar('0'))
+ .arg(upmins, 2, 10, QChar('0'))
+ .arg(uptime, 2, 10, QChar('0'))
+ .arg(startTime.toLocalTime().toString(Qt::DefaultLocaleShortDate));
ui.labelUptime->setText(uptimeText);
}
}
-void CoreInfoDlg::disconnectClicked(int peerId) {
+void CoreInfoDlg::disconnectClicked(int peerId)
+{
Client::kickClient(peerId);
}
{
QMessageBox::warning(this,
tr("Active sessions unsupported"),
- QString("<p><b>%1</b></p></br><p>%2</p>"
- ).arg(tr("Your Quassel core is too old to show active sessions"),
- tr("You need a Quassel core v0.13.0 or newer to view and "
- "disconnect other connected clients.")));
+ QString("<p><b>%1</b></p></br><p>%2</p>")
+ .arg(tr("Your Quassel core is too old to show active sessions"),
+ tr("You need a Quassel core v0.13.0 or newer to view and "
+ "disconnect other connected clients.")));
}
#include <QDialog>
-#include "ui_coreinfodlg.h"
#include "coreinfo.h"
#include "coresessionwidget.h"
-class CoreInfoDlg : public QDialog {
-Q_OBJECT
+#include "ui_coreinfodlg.h"
+
+class CoreInfoDlg : public QDialog
+{
+ Q_OBJECT
public:
- explicit CoreInfoDlg(QWidget *parent = nullptr);
+ explicit CoreInfoDlg(QWidget* parent = nullptr);
public slots:
- void coreInfoChanged(const QVariantMap &);
+ void coreInfoChanged(const QVariantMap&);
protected:
- void timerEvent(QTimerEvent *) override { updateUptime(); }
+ void timerEvent(QTimerEvent*) override { updateUptime(); }
private slots:
/**
void disconnectClicked(int peerId);
/**
- * Event handler for core unspported Details button
- */
+ * Event handler for core unspported Details button
+ */
void on_coreUnsupportedDetails_clicked();
private:
Ui::CoreInfoDlg ui;
- QMap<int, CoreSessionWidget *> _widgets;
+ QMap<int, CoreSessionWidget*> _widgets;
};
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "coresessionwidget.h"
+
#include <QDateTime>
#include "client.h"
-#include "coresessionwidget.h"
#include "util.h"
-
-CoreSessionWidget::CoreSessionWidget(QWidget *parent)
+CoreSessionWidget::CoreSessionWidget(QWidget* parent)
: QWidget(parent)
{
ui.setupUi(this);
ui.labelVersionDate->setText(QString("<i>%1</i>").arg(tr("Unknown date")));
}
else {
- ui.labelVersionDate->setText(tryFormatUnixEpoch(map["clientVersionDate"].toString(),
- Qt::DateFormat::DefaultLocaleShortDate));
+ ui.labelVersionDate->setText(tryFormatUnixEpoch(map["clientVersionDate"].toString(), Qt::DateFormat::DefaultLocaleShortDate));
}
- ui.labelUptime->setText(map["connectedSince"].toDateTime()
- .toLocalTime().toString(Qt::DateFormat::DefaultLocaleShortDate));
+ ui.labelUptime->setText(map["connectedSince"].toDateTime().toLocalTime().toString(Qt::DateFormat::DefaultLocaleShortDate));
if (map["location"].toString().isEmpty()) {
ui.labelLocation->hide();
ui.labelLocationTitle->hide();
// Both client and core support it, enable the button
ui.disconnectButton->setEnabled(true);
ui.disconnectButton->setToolTip(tr("End the client's session, disconnecting it"));
- } else {
+ }
+ else {
// For any active sessions to be displayed, the core must support this feature. We can
// assume the client doesn't support being remotely disconnected.
//
ui.disconnectButton->setEnabled(false);
// Assuming the client lacks support, set the tooltip accordingly
ui.disconnectButton->setToolTip(
- QString("<p>%1</p><p><b>%2</b></p>").arg(
- tr("End the client's session, disconnecting it"),
- tr("This client does not support being remotely disconnected")));
+ QString("<p>%1</p><p><b>%2</b></p>")
+ .arg(tr("End the client's session, disconnecting it"), tr("This client does not support being remotely disconnected")));
}
bool success = false;
_peerId = map["id"].toInt(&success);
- if (!success) _peerId = -1;
+ if (!success)
+ _peerId = -1;
}
void CoreSessionWidget::onDisconnectClicked()
#include "ui_coresessionwidget.h"
-class CoreSessionWidget: public QWidget
+class CoreSessionWidget : public QWidget
{
-Q_OBJECT
+ Q_OBJECT
public:
- explicit CoreSessionWidget(QWidget *);
+ explicit CoreSessionWidget(QWidget*);
void setData(QMap<QString, QVariant>);
#include "bufferviewoverlayfilter.h"
#include "client.h"
-DebugBufferViewOverlay::DebugBufferViewOverlay(QWidget *parent)
+DebugBufferViewOverlay::DebugBufferViewOverlay(QWidget* parent)
: QWidget(parent)
{
ui.setupUi(this);
- auto *filter = new BufferViewOverlayFilter(Client::bufferModel(), Client::bufferViewOverlay());
+ auto* filter = new BufferViewOverlayFilter(Client::bufferModel(), Client::bufferViewOverlay());
filter->setParent(ui.bufferView);
ui.bufferView->resize(610, 300);
ui.bufferView->show();
- auto *layout = new QFormLayout(ui.overlayProperties);
+ auto* layout = new QFormLayout(ui.overlayProperties);
layout->addRow(tr("BufferViews:"), _bufferViews = new QLineEdit(this));
layout->addRow(tr("All Networks:"), _allNetworks = new QLabel(this));
layout->addRow(tr("Networks:"), _networks = new QLineEdit(this));
connect(Client::bufferViewOverlay(), &BufferViewOverlay::hasChanged, this, &DebugBufferViewOverlay::update);
}
-
void DebugBufferViewOverlay::update()
{
- BufferViewOverlay *overlay = Client::bufferViewOverlay();
+ BufferViewOverlay* overlay = Client::bufferViewOverlay();
_allNetworks->setText(overlay->allNetworks() ? "yes" : "no");
QStringList ids;
- foreach(int bufferViewId, overlay->bufferViewIds()) {
+ foreach (int bufferViewId, overlay->bufferViewIds()) {
ids << QString::number(bufferViewId);
}
_bufferViews->setText(ids.join(", "));
ids.clear();
- foreach(NetworkId networkId, overlay->networkIds()) {
+ foreach (NetworkId networkId, overlay->networkIds()) {
ids << QString::number(networkId.toInt());
}
_networks->setText(ids.join(", "));
ids.clear();
- foreach(BufferId bufferId, overlay->bufferIds()) {
+ foreach (BufferId bufferId, overlay->bufferIds()) {
ids << QString::number(bufferId.toInt());
}
_bufferIds->setText(ids.join(", "));
ids.clear();
- foreach(BufferId bufferId, overlay->removedBufferIds()) {
+ foreach (BufferId bufferId, overlay->removedBufferIds()) {
ids << QString::number(bufferId.toInt());
}
_removedBufferIds->setText(ids.join(", "));
ids.clear();
- foreach(BufferId bufferId, overlay->tempRemovedBufferIds()) {
+ foreach (BufferId bufferId, overlay->tempRemovedBufferIds()) {
ids << QString::number(bufferId.toInt());
}
_tempRemovedBufferIds->setText(ids.join(", "));
Q_OBJECT
public:
- DebugBufferViewOverlay(QWidget *parent = nullptr);
+ DebugBufferViewOverlay(QWidget* parent = nullptr);
private slots:
void update();
private:
Ui::DebugBufferViewOverlay ui;
- QLineEdit *_bufferViews;
- QLabel *_allNetworks;
- QLineEdit *_networks;
- QTextEdit *_bufferIds;
- QTextEdit *_removedBufferIds;
- QTextEdit *_tempRemovedBufferIds;
- QLabel *_addBuffersAutomatically;
- QLabel *_hideInactiveBuffers;
- QLabel *_allowedBufferTypes;
- QLabel *_minimumActivity;
- QLabel *_isInitialized;
+ QLineEdit* _bufferViews;
+ QLabel* _allNetworks;
+ QLineEdit* _networks;
+ QTextEdit* _bufferIds;
+ QTextEdit* _removedBufferIds;
+ QTextEdit* _tempRemovedBufferIds;
+ QLabel* _addBuffersAutomatically;
+ QLabel* _hideInactiveBuffers;
+ QLabel* _allowedBufferTypes;
+ QLabel* _minimumActivity;
+ QLabel* _isInitialized;
};
-
-#endif //DEBUGBUFFERVIEWOVERLAY_H
+#endif // DEBUGBUFFERVIEWOVERLAY_H
***************************************************************************/
#include "debugconsole.h"
+
#include "client.h"
#include "signalproxy.h"
-DebugConsole::DebugConsole(QWidget *parent)
+DebugConsole::DebugConsole(QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
Client::signalProxy()->attachSlot(SIGNAL(scriptResult(QString)), this, SLOT(scriptResult(QString)));
}
-
void DebugConsole::on_evalButton_clicked()
{
if (ui.selectCore->isChecked()) {
}
}
-
void DebugConsole::scriptResult(QString result)
{
ui.resultLabel->setText(result);
Q_OBJECT
public:
- DebugConsole(QWidget *parent = nullptr);
+ DebugConsole(QWidget* parent = nullptr);
public slots:
void scriptResult(QString result);
Ui::DebugConsole ui;
};
-
#endif
#include "quassel.h"
-DebugLogDlg::DebugLogDlg(QWidget *parent)
+DebugLogDlg::DebugLogDlg(QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
connect(Quassel::instance()->logger(), &Logger::messageLogged, this, &DebugLogDlg::logUpdated);
QString content;
- for (auto &&message : Quassel::instance()->logger()->messages()) {
+ for (auto&& message : Quassel::instance()->logger()->messages()) {
content += toString(message);
}
ui.textEdit->setPlainText(content);
-
}
-
-QString DebugLogDlg::toString(const Logger::LogEntry &msg)
+QString DebugLogDlg::toString(const Logger::LogEntry& msg)
{
return msg.timeStamp.toString("yyyy-MM-dd hh:mm:ss ") + msg.message + "\n";
}
-
-void DebugLogDlg::logUpdated(const Logger::LogEntry &msg)
+void DebugLogDlg::logUpdated(const Logger::LogEntry& msg)
{
ui.textEdit->moveCursor(QTextCursor::End);
ui.textEdit->insertPlainText(toString(msg));
Q_OBJECT
public:
- DebugLogDlg(QWidget *parent = nullptr);
+ DebugLogDlg(QWidget* parent = nullptr);
private slots:
- void logUpdated(const Logger::LogEntry &msg);
+ void logUpdated(const Logger::LogEntry& msg);
private:
- QString toString(const Logger::LogEntry &msg);
+ QString toString(const Logger::LogEntry& msg);
private:
Ui::DebugLogDlg ui;
#include "messagemodel.h"
-DebugMessageModelFilter::DebugMessageModelFilter(QObject *parent)
+DebugMessageModelFilter::DebugMessageModelFilter(QObject* parent)
: QSortFilterProxyModel(parent)
-{
-}
-
+{}
QVariant DebugMessageModelFilter::headerData(int section, Qt::Orientation orientation, int role) const
{
}
}
-
-QVariant DebugMessageModelFilter::data(const QModelIndex &index, int role) const
+QVariant DebugMessageModelFilter::data(const QModelIndex& index, int role) const
{
if (index.column() != 0 || role != Qt::DisplayRole)
return QSortFilterProxyModel::data(index, role);
Q_OBJECT
public:
- DebugMessageModelFilter(QObject *parent = nullptr);
+ DebugMessageModelFilter(QObject* parent = nullptr);
QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
- QVariant data(const QModelIndex &index, int role) const override;
+ QVariant data(const QModelIndex& index, int role) const override;
};
-
-#endif //DEBUGMESSAGEMODELFILTER_H
+#endif // DEBUGMESSAGEMODELFILTER_H
#include "dockmanagernotificationbackend.h"
-#include <QHBoxLayout>
#include <QCheckBox>
#include <QDBusReply>
+#include <QHBoxLayout>
#include "client.h"
+#include "clientbacklogmanager.h"
#include "clientsettings.h"
#include "coreconnection.h"
-#include "clientbacklogmanager.h"
#include "util.h"
-DockManagerNotificationBackend::DockManagerNotificationBackend(QObject *parent)
- : AbstractNotificationBackend(parent), _bus(QDBusConnection::sessionBus())
+DockManagerNotificationBackend::DockManagerNotificationBackend(QObject* parent)
+ : AbstractNotificationBackend(parent)
+ , _bus(QDBusConnection::sessionBus())
{
NotificationSettings notificationSettings;
_enabled = notificationSettings.value("DockManager/Enabled", false).toBool();
_dock = new QDBusInterface("net.launchpad.DockManager", "/net/launchpad/DockManager", "net.launchpad.DockManager", _bus, this);
if (_dock->isValid()) {
- _bus.connect("net.launchpad.DockManager", "/net/launchpad/DockManager", "net.launchpad.DockManager", "ItemAdded", this, SLOT(itemAdded(QDBusObjectPath)));
- } else {
+ _bus.connect("net.launchpad.DockManager",
+ "/net/launchpad/DockManager",
+ "net.launchpad.DockManager",
+ "ItemAdded",
+ this,
+ SLOT(itemAdded(QDBusObjectPath)));
+ }
+ else {
// evil implementations (awn) use fd.o
_dock = new QDBusInterface("org.freedesktop.DockManager", "/org/freedesktop/DockManager", "org.freedesktop.DockManager", _bus, this);
if (_dock->isValid()) {
- _bus.connect("org.freedesktop.DockManager", "/org/freedesktop/DockManager", "org.freedesktop.DockManager", "ItemAdded", this, SLOT(itemAdded(QDBusObjectPath)));
- } else {
+ _bus.connect("org.freedesktop.DockManager",
+ "/org/freedesktop/DockManager",
+ "org.freedesktop.DockManager",
+ "ItemAdded",
+ this,
+ SLOT(itemAdded(QDBusObjectPath)));
+ }
+ else {
_available = _enabled = false;
return;
}
itemAdded(QDBusObjectPath());
- connect(Client::coreConnection(), &CoreConnection::progressValueChanged, this, selectOverload<int>(&DockManagerNotificationBackend::updateProgress));
+ connect(Client::coreConnection(),
+ &CoreConnection::progressValueChanged,
+ this,
+ selectOverload<int>(&DockManagerNotificationBackend::updateProgress));
connect(Client::coreConnection(), &CoreConnection::synchronized, this, &DockManagerNotificationBackend::synchronized);
}
-
void DockManagerNotificationBackend::itemAdded(QDBusObjectPath p)
{
Q_UNUSED(p);
return;
// stupid implementations (awn; kde?) use wrong casing of PID, but proper type
- QDBusReply<QList<QDBusObjectPath> > paths = _dock->call("GetItemsByPid", (int)QCoreApplication::applicationPid());
+ QDBusReply<QList<QDBusObjectPath>> paths = _dock->call("GetItemsByPid", (int)QCoreApplication::applicationPid());
if (!paths.isValid()) {
// stupid implementations (i.e. docky) use uint, but proper casing
paths = _dock->call("GetItemsByPID", (unsigned int)QCoreApplication::applicationPid());
return;
}
}
- if (paths.value().count() == 0) { // no icon for this instance
+ if (paths.value().count() == 0) { // no icon for this instance
return;
}
- QString path = paths.value()[0].path(); // no sense in using multiple icons for one instance
+ QString path = paths.value()[0].path(); // no sense in using multiple icons for one instance
_item = new QDBusInterface("org.freedesktop.DockManager", path, "org.freedesktop.DockItem", _bus, this);
}
-
void DockManagerNotificationBackend::updateProgress(int progress)
{
if (!_enabled || !_item)
return;
- CoreConnection *c = Client::instance()->coreConnection();
+ CoreConnection* c = Client::instance()->coreConnection();
int perc = 0;
if (c->progressMaximum() == c->progressMinimum())
perc = 0;
_item->call("UpdateDockItem", args);
}
-
void DockManagerNotificationBackend::updateProgress(int done, int total)
{
if (!_enabled || !_item)
if (done == total) {
disconnect(Client::backlogManager(), nullptr, this, nullptr);
perc = -1;
- } else
+ }
+ else
perc = (done * 100) / total;
QHash<QString, QVariant> args;
_item->call("UpdateDockItem", args);
}
-
void DockManagerNotificationBackend::synchronized()
{
- connect(Client::backlogManager(), &ClientBacklogManager::updateProgress, this, selectOverload<int, int>(&DockManagerNotificationBackend::updateProgress));
+ connect(Client::backlogManager(),
+ &ClientBacklogManager::updateProgress,
+ this,
+ selectOverload<int, int>(&DockManagerNotificationBackend::updateProgress));
}
-
-void DockManagerNotificationBackend::notify(const Notification ¬ification)
+void DockManagerNotificationBackend::notify(const Notification& notification)
{
if (!_enabled || !_item) {
return;
_item->call("UpdateDockItem", args);
}
-
void DockManagerNotificationBackend::close(uint notificationId)
{
Q_UNUSED(notificationId);
_item->call("UpdateDockItem", args);
}
-
-void DockManagerNotificationBackend::enabledChanged(const QVariant &v)
+void DockManagerNotificationBackend::enabledChanged(const QVariant& v)
{
_enabled = v.toBool();
}
}
-
-SettingsPage *DockManagerNotificationBackend::createConfigWidget() const
+SettingsPage* DockManagerNotificationBackend::createConfigWidget() const
{
return new ConfigWidget(_available);
}
-
/***************************************************************************/
-DockManagerNotificationBackend::ConfigWidget::ConfigWidget(bool enabled, QWidget *parent)
+DockManagerNotificationBackend::ConfigWidget::ConfigWidget(bool enabled, QWidget* parent)
: SettingsPage("Internal", "DockManagerNotification", parent)
{
- auto *layout = new QHBoxLayout(this);
+ auto* layout = new QHBoxLayout(this);
layout->addWidget(enabledBox = new QCheckBox(tr("Mark dockmanager entry"), this));
enabledBox->setVisible(enabled);
connect(enabledBox, &QAbstractButton::toggled, this, &ConfigWidget::widgetChanged);
}
-
void DockManagerNotificationBackend::ConfigWidget::widgetChanged()
{
bool changed = enabled != enabledBox->isChecked();
- if (changed != hasChanged()) setChangedState(changed);
+ if (changed != hasChanged())
+ setChangedState(changed);
}
-
bool DockManagerNotificationBackend::ConfigWidget::hasDefaults() const
{
return true;
}
-
void DockManagerNotificationBackend::ConfigWidget::defaults()
{
enabledBox->setChecked(false);
widgetChanged();
}
-
void DockManagerNotificationBackend::ConfigWidget::load()
{
NotificationSettings s;
setChangedState(false);
}
-
void DockManagerNotificationBackend::ConfigWidget::save()
{
NotificationSettings s;
Q_OBJECT
public:
- DockManagerNotificationBackend(QObject *parent = nullptr);
+ DockManagerNotificationBackend(QObject* parent = nullptr);
- void notify(const Notification &) override;
+ void notify(const Notification&) override;
void close(uint notificationId) override;
- SettingsPage *createConfigWidget() const override;
+ SettingsPage* createConfigWidget() const override;
private slots:
- void enabledChanged(const QVariant &);
+ void enabledChanged(const QVariant&);
void updateProgress(int progress);
void updateProgress(int done, int total);
void itemAdded(QDBusObjectPath);
bool _enabled;
bool _available;
QDBusConnection _bus;
- QDBusInterface *_dock{nullptr};
- QDBusInterface *_item{nullptr};
+ QDBusInterface* _dock{nullptr};
+ QDBusInterface* _item{nullptr};
int _count{0};
};
-
class DockManagerNotificationBackend::ConfigWidget : public SettingsPage
{
Q_OBJECT
public:
- ConfigWidget(bool enabled, QWidget *parent = nullptr);
+ ConfigWidget(bool enabled, QWidget* parent = nullptr);
void save() override;
void load() override;
void widgetChanged();
private:
- QCheckBox *enabledBox;
+ QCheckBox* enabledBox;
bool enabled;
};
-
#endif
const int leftMargin = 3;
-InputWidget::InputWidget(QWidget *parent)
- : AbstractItemView(parent),
- _networkId(0)
+InputWidget::InputWidget(QWidget* parent)
+ : AbstractItemView(parent)
+ , _networkId(0)
{
ui.setupUi(this);
connect(ui.ownNick, selectOverload<const QString&>(&QComboBox::activated), this, &InputWidget::changeNick);
_colorFillMenu = new QMenu();
QStringList names;
- names << tr("White") << tr("Black") << tr("Dark blue") << tr("Dark green") << tr("Red") << tr("Dark red") << tr("Dark magenta") << tr("Orange")
- << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray") << tr("Light gray");
+ names << tr("White") << tr("Black") << tr("Dark blue") << tr("Dark green") << tr("Red") << tr("Dark red") << tr("Dark magenta")
+ << tr("Orange") << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray")
+ << tr("Light gray");
QPixmap pix(16, 16);
for (int i = 0; i < inputLine()->mircColorMap().count(); i++) {
s.initAndNotify("EnableLineWrap", this, &InputWidget::setLineWrapEnabled, true);
s.initAndNotify("EnableMultiLine", this, &InputWidget::setMultiLineEnabled, true);
- ActionCollection *coll = QtUi::actionCollection();
- coll->addAction("FocusInputLine", new Action{tr("Focus Input Line"), coll, this, selectOverload<>(&QWidget::setFocus), QKeySequence(Qt::CTRL + Qt::Key_L)});
+ ActionCollection* coll = QtUi::actionCollection();
+ coll->addAction("FocusInputLine",
+ new Action{tr("Focus Input Line"), coll, this, selectOverload<>(&QWidget::setFocus), QKeySequence(Qt::CTRL + Qt::Key_L)});
- connect(inputLine(), &MultiLineEdit::textEntered, this, &InputWidget::onTextEntered, Qt::QueuedConnection); // make sure the line is already reset, bug #984
+ connect(inputLine(),
+ &MultiLineEdit::textEntered,
+ this,
+ &InputWidget::onTextEntered,
+ Qt::QueuedConnection); // make sure the line is already reset, bug #984
connect(inputLine(), &QTextEdit::currentCharFormatChanged, this, &InputWidget::currentCharFormatChanged);
}
-
-void InputWidget::setUseCustomFont(const QVariant &v)
+void InputWidget::setUseCustomFont(const QVariant& v)
{
if (v.toBool()) {
UiStyleSettings fs("Fonts");
setCustomFont(QFont());
}
-
-void InputWidget::setCustomFont(const QVariant &v)
+void InputWidget::setCustomFont(const QVariant& v)
{
QFont font = v.value<QFont>();
if (font.family().isEmpty())
ui.inputEdit->setCustomFont(font);
}
-
-void InputWidget::setEnableEmacsMode(const QVariant &v)
+void InputWidget::setEnableEmacsMode(const QVariant& v)
{
ui.inputEdit->setEmacsMode(v.toBool());
}
-
-void InputWidget::setShowNickSelector(const QVariant &v)
+void InputWidget::setShowNickSelector(const QVariant& v)
{
ui.ownNick->setVisible(v.toBool());
}
-
-void InputWidget::setShowStyleButtons(const QVariant &v)
+void InputWidget::setShowStyleButtons(const QVariant& v)
{
ui.showStyleButton->setVisible(v.toBool());
}
-
-void InputWidget::setEnablePerChatHistory(const QVariant &v)
+void InputWidget::setEnablePerChatHistory(const QVariant& v)
{
_perChatHistory = v.toBool();
}
-
-void InputWidget::setMaxLines(const QVariant &v)
+void InputWidget::setMaxLines(const QVariant& v)
{
ui.inputEdit->setMaxHeight(v.toInt());
}
-
-void InputWidget::setScrollBarsEnabled(const QVariant &v)
+void InputWidget::setScrollBarsEnabled(const QVariant& v)
{
ui.inputEdit->setScrollBarsEnabled(v.toBool());
}
-
-void InputWidget::setLineWrapEnabled(const QVariant &v)
+void InputWidget::setLineWrapEnabled(const QVariant& v)
{
ui.inputEdit->setLineWrapEnabled(v.toBool());
}
-
-void InputWidget::setMultiLineEnabled(const QVariant &v)
+void InputWidget::setMultiLineEnabled(const QVariant& v)
{
ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
}
-
-bool InputWidget::eventFilter(QObject *watched, QEvent *event)
+bool InputWidget::eventFilter(QObject* watched, QEvent* event)
{
if (event->type() != QEvent::KeyPress)
return false;
- auto *keyEvent = static_cast<QKeyEvent *>(event);
+ auto* keyEvent = static_cast<QKeyEvent*>(event);
// keys from BufferView should be sent to (and focus) the input line
- auto *view = qobject_cast<BufferView *>(watched);
+ auto* view = qobject_cast<BufferView*>(watched);
if (view) {
- if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
+ if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
QChar c = keyEvent->text().at(0);
if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
setFocus();
}
else if (watched == ui.inputEdit) {
if (keyEvent->matches(QKeySequence::Find)) {
- QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
+ QAction* act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
if (act) {
act->toggle();
return true;
return false;
}
-
-void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
+void InputWidget::currentChanged(const QModelIndex& current, const QModelIndex& previous)
{
BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
if (_perChatHistory) {
- //backup
+ // backup
historyMap[previousBufferId].history = inputLine()->history();
historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
historyMap[previousBufferId].idx = inputLine()->idx();
historyMap[previousBufferId].inputLine = inputLine()->html();
- //restore
+ // restore
inputLine()->setHistory(historyMap[currentBufferId].history);
inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
inputLine()->setIdx(historyMap[currentBufferId].idx);
// FIXME this really should be in MultiLineEdit (and the const int on top removed)
QTextBlockFormat format = inputLine()->textCursor().blockFormat();
- format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
+ format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
inputLine()->textCursor().setBlockFormat(format);
}
updateEnabledState();
}
-
-void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
+void InputWidget::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
QItemSelectionRange changedArea(topLeft, bottomRight);
if (changedArea.contains(selectionModel()->currentIndex())) {
bool encrypted = false;
- auto *chan = qobject_cast<IrcChannel *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject *>());
+ auto* chan = qobject_cast<IrcChannel*>(
+ Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject*>());
if (chan)
encrypted = chan->encrypted();
- auto *user = qobject_cast<IrcUser *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject *>());
+ auto* user = qobject_cast<IrcUser*>(
+ Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject*>());
if (user)
encrypted = user->encrypted();
}
}
-
-void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
+void InputWidget::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
NetworkId networkId;
QModelIndex child;
}
}
-
void InputWidget::updateEnabledState()
{
// FIXME: Find a visualization for this that does not disable the widget!
#endif
}
-
-const Network *InputWidget::currentNetwork() const
+const Network* InputWidget::currentNetwork() const
{
return Client::network(_networkId);
}
-
BufferInfo InputWidget::currentBufferInfo() const
{
return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
}
-
void InputWidget::applyFormatActiveColor()
{
if (!ui.textcolorButton->defaultAction()) {
colorChosen(ui.textcolorButton->defaultAction());
}
-
void InputWidget::applyFormatActiveColorFill()
{
if (!ui.highlightcolorButton->defaultAction()) {
colorHighlightChosen(ui.highlightcolorButton->defaultAction());
}
-
void InputWidget::toggleFormatBold()
{
setFormatBold(!ui.boldButton->isChecked());
}
-
void InputWidget::toggleFormatItalic()
{
setFormatItalic(!ui.italicButton->isChecked());
}
-
void InputWidget::toggleFormatUnderline()
{
setFormatUnderline(!ui.underlineButton->isChecked());
}
-
void InputWidget::clearFormat()
{
// Clear all formatting for selection (not global)
setFormatClear(false);
}
-
void InputWidget::setNetwork(NetworkId networkId)
{
if (_networkId == networkId)
return;
- const Network *previousNet = Client::network(_networkId);
+ const Network* previousNet = Client::network(_networkId);
if (previousNet) {
disconnect(previousNet, nullptr, this, nullptr);
if (previousNet->me())
_networkId = networkId;
- const Network *network = Client::network(networkId);
+ const Network* network = Client::network(networkId);
if (network) {
connect(network, &Network::identitySet, this, &InputWidget::setIdentity);
connectMyIrcUser();
}
}
-
void InputWidget::connectMyIrcUser()
{
- const Network *network = currentNetwork();
+ const Network* network = currentNetwork();
if (network->me()) {
connect(network->me(), &IrcUser::nickSet, this, &InputWidget::updateNickSelector);
connect(network->me(), &IrcUser::userModesSet, this, &InputWidget::updateNickSelector);
}
}
-
void InputWidget::setIdentity(IdentityId identityId)
{
if (_identityId == identityId)
return;
- const Identity *previousIdentity = Client::identity(_identityId);
+ const Identity* previousIdentity = Client::identity(_identityId);
if (previousIdentity)
disconnect(previousIdentity, nullptr, this, nullptr);
_identityId = identityId;
- const Identity *identity = Client::identity(identityId);
+ const Identity* identity = Client::identity(identityId);
if (identity) {
connect(identity, &Identity::nicksSet, this, &InputWidget::updateNickSelector);
}
updateNickSelector();
}
-
void InputWidget::updateNickSelector() const
{
ui.ownNick->clear();
- const Network *net = currentNetwork();
+ const Network* net = currentNetwork();
if (!net)
return;
- const Identity *identity = Client::identity(net->identity());
+ const Identity* identity = Client::identity(net->identity());
if (!identity) {
- qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
+ qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId()
+ << "IdentityId:" << net->identity();
return;
}
if (nicks.isEmpty())
return;
- IrcUser *me = net->me();
+ IrcUser* me = net->me();
if (me) {
nicks[nickIdx] = net->myNick();
if (!me->userModes().isEmpty())
ui.ownNick->setCurrentIndex(nickIdx);
}
-
-void InputWidget::changeNick(const QString &newNick) const
+void InputWidget::changeNick(const QString& newNick) const
{
- const Network *net = currentNetwork();
+ const Network* net = currentNetwork();
if (!net || net->isMyNick(newNick))
return;
Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
}
-
-void InputWidget::onTextEntered(const QString &text)
+void InputWidget::onTextEntered(const QString& text)
{
Client::userInput(currentBufferInfo(), text);
setFormatClear(true);
}
-
void InputWidget::setFormatClear(const bool global)
{
// Apply formatting
fmt.clearBackground();
if (global) {
inputLine()->setCurrentCharFormat(fmt);
- } else {
+ }
+ else {
setFormatOnSelection(fmt);
}
ui.underlineButton->setChecked(false);
}
-
void InputWidget::setFormatBold(const bool bold)
{
// Apply formatting
ui.boldButton->setChecked(bold);
}
-
void InputWidget::setFormatItalic(const bool italic)
{
// Apply formatting
ui.italicButton->setChecked(italic);
}
-
void InputWidget::setFormatUnderline(const bool underline)
{
// Apply formatting
ui.underlineButton->setChecked(underline);
}
-
-void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format)
+void InputWidget::mergeFormatOnSelection(const QTextCharFormat& format)
{
QTextCursor cursor = inputLine()->textCursor();
cursor.mergeCharFormat(format);
inputLine()->mergeCurrentCharFormat(format);
}
-
-void InputWidget::setFormatOnSelection(const QTextCharFormat &format)
+void InputWidget::setFormatOnSelection(const QTextCharFormat& format)
{
QTextCursor cursor = inputLine()->textCursor();
cursor.setCharFormat(format);
inputLine()->setCurrentCharFormat(format);
}
-
QTextCharFormat InputWidget::getFormatOfWordOrSelection()
{
QTextCursor cursor = inputLine()->textCursor();
return cursor.charFormat();
}
-
void InputWidget::setStyleOptionsExpanded(bool expanded)
{
ui.styleFrame->setVisible(expanded);
if (expanded) {
ui.showStyleButton->setArrowType(Qt::LeftArrow);
ui.showStyleButton->setToolTip(tr("Hide formatting options"));
- } else {
+ }
+ else {
ui.showStyleButton->setArrowType(Qt::RightArrow);
ui.showStyleButton->setToolTip(tr("Show formatting options"));
}
}
-
-void InputWidget::currentCharFormatChanged(const QTextCharFormat &format)
+void InputWidget::currentCharFormatChanged(const QTextCharFormat& format)
{
fontChanged(format.font());
}
-
void InputWidget::on_boldButton_clicked(bool checked)
{
setFormatBold(checked);
}
-
void InputWidget::on_underlineButton_clicked(bool checked)
{
setFormatUnderline(checked);
}
-
void InputWidget::on_italicButton_clicked(bool checked)
{
setFormatItalic(checked);
}
-
-void InputWidget::fontChanged(const QFont &f)
+void InputWidget::fontChanged(const QFont& f)
{
ui.boldButton->setChecked(f.bold());
ui.italicButton->setChecked(f.italic());
ui.underlineButton->setChecked(f.underline());
}
-
-void InputWidget::colorChosen(QAction *action)
+void InputWidget::colorChosen(QAction* action)
{
QTextCharFormat fmt;
QColor color;
ui.textcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-text-color"), color));
}
-
-void InputWidget::colorHighlightChosen(QAction *action)
+void InputWidget::colorHighlightChosen(QAction* action)
{
QTextCharFormat fmt;
QColor color;
ui.highlightcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-fill-color"), color));
}
-
void InputWidget::on_showStyleButton_toggled(bool checked)
{
setStyleOptionsExpanded(checked);
}
-
-QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color)
+QIcon InputWidget::createColorToolButtonIcon(const QIcon& icon, const QColor& color)
{
QPixmap pixmap(16, 16);
pixmap.fill(Qt::transparent);
return QIcon(pixmap);
}
-
// MOUSE WHEEL FILTER
-MouseWheelFilter::MouseWheelFilter(QObject *parent)
+MouseWheelFilter::MouseWheelFilter(QObject* parent)
: QObject(parent)
-{
-}
-
+{}
-bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event)
+bool MouseWheelFilter::eventFilter(QObject* obj, QEvent* event)
{
if (event->type() != QEvent::Wheel)
return QObject::eventFilter(obj, event);
#include "abstractitemview.h"
#include "action.h"
-#include "buffermodel.h"
#include "bufferinfo.h"
+#include "buffermodel.h"
#include "identity.h"
#include "network.h"
Q_OBJECT
public:
- InputWidget(QWidget *parent = nullptr);
+ InputWidget(QWidget* parent = nullptr);
- const Network *currentNetwork() const;
+ const Network* currentNetwork() const;
- inline MultiLineEdit *inputLine() const { return ui.inputEdit; }
+ inline MultiLineEdit* inputLine() const { return ui.inputEdit; }
public slots:
/**
void clearFormat();
protected:
- bool eventFilter(QObject *watched, QEvent *event) override;
+ bool eventFilter(QObject* watched, QEvent* event) override;
protected slots:
- void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) override;
- void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) override;
- void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) override;
+ void currentChanged(const QModelIndex& current, const QModelIndex& previous) override;
+ void rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) override;
+ void dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight) override;
private slots:
- void setCustomFont(const QVariant &font);
- void setUseCustomFont(const QVariant &);
- void setEnableEmacsMode(const QVariant &);
- void setShowNickSelector(const QVariant &);
- void setShowStyleButtons(const QVariant &);
- void setEnablePerChatHistory(const QVariant &);
- void setMaxLines(const QVariant &);
- void setLineWrapEnabled(const QVariant &);
- void setMultiLineEnabled(const QVariant &);
- void setScrollBarsEnabled(const QVariant &);
- void onTextEntered(const QString &text);
- void changeNick(const QString &newNick) const;
+ void setCustomFont(const QVariant& font);
+ void setUseCustomFont(const QVariant&);
+ void setEnableEmacsMode(const QVariant&);
+ void setShowNickSelector(const QVariant&);
+ void setShowStyleButtons(const QVariant&);
+ void setEnablePerChatHistory(const QVariant&);
+ void setMaxLines(const QVariant&);
+ void setLineWrapEnabled(const QVariant&);
+ void setMultiLineEnabled(const QVariant&);
+ void setScrollBarsEnabled(const QVariant&);
+ void onTextEntered(const QString& text);
+ void changeNick(const QString& newNick) const;
void setNetwork(NetworkId networkId);
void setIdentity(IdentityId identityId);
*/
void setStyleOptionsExpanded(const bool visible);
- void currentCharFormatChanged(const QTextCharFormat &format);
+ void currentCharFormatChanged(const QTextCharFormat& format);
void on_showStyleButton_toggled(bool checked);
void on_boldButton_clicked(bool checked);
void on_italicButton_clicked(bool checked);
void on_underlineButton_clicked(bool checked);
- void colorChosen(QAction *action);
- void colorHighlightChosen(QAction *action);
+ void colorChosen(QAction* action);
+ void colorHighlightChosen(QAction* action);
private:
/**
IdentityId _identityId;
QMenu *_colorMenu, *_colorFillMenu;
- void mergeFormatOnSelection(const QTextCharFormat &format);
- void fontChanged(const QFont &f);
- QIcon createColorToolButtonIcon(const QIcon &icon, const QColor &color);
+ void mergeFormatOnSelection(const QTextCharFormat& format);
+ void fontChanged(const QFont& f);
+ QIcon createColorToolButtonIcon(const QIcon& icon, const QColor& color);
QTextCharFormat getFormatOfWordOrSelection();
- void setFormatOnSelection(const QTextCharFormat &format);
+ void setFormatOnSelection(const QTextCharFormat& format);
bool _perChatHistory;
- struct HistoryState {
+ struct HistoryState
+ {
QStringList history;
QHash<int, QString> tempHistory;
qint32 idx{0};
QMap<BufferId, HistoryState> historyMap;
};
-
class MouseWheelFilter : public QObject
{
Q_OBJECT
public:
- MouseWheelFilter(QObject *parent = nullptr);
- bool eventFilter(QObject *obj, QEvent *event) override;
+ MouseWheelFilter(QObject* parent = nullptr);
+ bool eventFilter(QObject* obj, QEvent* event) override;
};
#include "ircconnectionwizard.h"
+#include <QVBoxLayout>
+
#include "client.h"
#include "identityeditwidget.h"
-#include "simplenetworkeditor.h"
#include "presetnetworks.h"
+#include "simplenetworkeditor.h"
-#include <QVBoxLayout>
-
-IrcConnectionWizard::IrcConnectionWizard(QWidget *parent, Qt::WindowFlags flags)
+IrcConnectionWizard::IrcConnectionWizard(QWidget* parent, Qt::WindowFlags flags)
: QWizard(parent, flags)
{
_introductionPage = createIntroductionPage(this);
setButtonText(QWizard::FinishButton, tr("Save && Connect"));
}
-
-QWizardPage *IrcConnectionWizard::createIntroductionPage(QWidget *parent)
+QWizardPage* IrcConnectionWizard::createIntroductionPage(QWidget* parent)
{
- auto *page = new QWizardPage(parent);
+ auto* page = new QWizardPage(parent);
page->setTitle(QObject::tr("Welcome to Quassel IRC"));
- QLabel *label = new QLabel(QObject::tr("This wizard will help you to set up your default identity and your IRC network connection.<br>"
- "This only covers basic settings. You can cancel this wizard any time and use the settings dialog for more detailed changes."), page);
+ QLabel* label = new QLabel(
+ QObject::tr(
+ "This wizard will help you to set up your default identity and your IRC network connection.<br>"
+ "This only covers basic settings. You can cancel this wizard any time and use the settings dialog for more detailed changes."),
+ page);
label->setWordWrap(true);
- auto *layout = new QVBoxLayout;
+ auto* layout = new QVBoxLayout;
layout->addWidget(label);
page->setLayout(layout);
return page;
}
-
void IrcConnectionWizard::finishClicked()
{
- CertIdentity *identity = static_cast<IdentityPage *>(_identityPage)->identity();
+ CertIdentity* identity = static_cast<IdentityPage*>(_identityPage)->identity();
if (identity->id().isValid()) {
Client::updateIdentity(identity->id(), identity->toVariantMap());
identityReady(identity->id());
}
}
-
void IrcConnectionWizard::identityReady(IdentityId id)
{
disconnect(Client::instance(), &Client::identityCreated, this, &IrcConnectionWizard::identityReady);
- auto *networkPage = static_cast<NetworkPage *>(_networkPage);
+ auto* networkPage = static_cast<NetworkPage*>(_networkPage);
NetworkInfo networkInfo = networkPage->networkInfo();
QStringList channels = networkPage->channelList();
networkInfo.identity = id;
Client::createNetwork(networkInfo, channels);
}
-
void IrcConnectionWizard::networkReady(NetworkId id)
{
disconnect(Client::instance(), &Client::networkCreated, this, &IrcConnectionWizard::networkReady);
- const Network *net = Client::network(id);
+ const Network* net = Client::network(id);
Q_ASSERT(net);
net->requestConnect();
deleteLater();
}
-
// ==============================
// Wizard Pages
// ==============================
// Identity Page
-IdentityPage::IdentityPage(QWidget *parent)
- : QWizardPage(parent),
- _identityEditWidget(new IdentityEditWidget(this))
+IdentityPage::IdentityPage(QWidget* parent)
+ : QWizardPage(parent)
+ , _identityEditWidget(new IdentityEditWidget(this))
{
setTitle(tr("Setup Identity"));
_identityEditWidget->displayIdentity(_identity);
_identityEditWidget->showAdvanced(false);
- auto *layout = new QVBoxLayout;
+ auto* layout = new QVBoxLayout;
layout->addWidget(_identityEditWidget);
setLayout(layout);
}
-
-CertIdentity *IdentityPage::identity()
+CertIdentity* IdentityPage::identity()
{
_identityEditWidget->saveToIdentity(_identity);
return _identity;
}
-
// Network Page
-NetworkPage::NetworkPage(QWidget *parent)
- : QWizardPage(parent),
- _networkEditor(new SimpleNetworkEditor(this))
+NetworkPage::NetworkPage(QWidget* parent)
+ : QWizardPage(parent)
+ , _networkEditor(new SimpleNetworkEditor(this))
{
QStringList defaultNets = PresetNetworks::names(true);
if (!defaultNets.isEmpty()) {
setTitle(tr("Setup Network Connection"));
- auto *layout = new QVBoxLayout;
+ auto* layout = new QVBoxLayout;
layout->addWidget(_networkEditor);
setLayout(layout);
}
-
NetworkInfo NetworkPage::networkInfo()
{
_networkEditor->saveToNetworkInfo(_networkInfo);
return _networkInfo;
}
-
QStringList NetworkPage::channelList()
{
_channelList = _networkEditor->defaultChannels();
Q_OBJECT
public:
- IrcConnectionWizard(QWidget *parent = nullptr, Qt::WindowFlags flags = nullptr);
+ IrcConnectionWizard(QWidget* parent = nullptr, Qt::WindowFlags flags = nullptr);
- static QWizardPage *createIntroductionPage(QWidget *parent = nullptr);
+ static QWizardPage* createIntroductionPage(QWidget* parent = nullptr);
private slots:
void finishClicked();
void networkReady(NetworkId id);
private:
- QWizardPage *_introductionPage{nullptr};
- QWizardPage *_identityPage{nullptr};
- QWizardPage *_networkPage{nullptr};
+ QWizardPage* _introductionPage{nullptr};
+ QWizardPage* _identityPage{nullptr};
+ QWizardPage* _networkPage{nullptr};
};
-
// ==============================
// Wizard Pages
// ==============================
Q_OBJECT
public:
- IdentityPage(QWidget *parent = nullptr);
+ IdentityPage(QWidget* parent = nullptr);
- CertIdentity *identity();
+ CertIdentity* identity();
private:
- IdentityEditWidget *_identityEditWidget;
- CertIdentity *_identity{nullptr};
+ IdentityEditWidget* _identityEditWidget;
+ CertIdentity* _identity{nullptr};
};
-
// Network Page
#include "network.h"
Q_OBJECT
public:
- NetworkPage(QWidget *parent = nullptr);
+ NetworkPage(QWidget* parent = nullptr);
NetworkInfo networkInfo();
QStringList channelList();
private:
- SimpleNetworkEditor *_networkEditor;
+ SimpleNetworkEditor* _networkEditor;
NetworkInfo _networkInfo;
QStringList _channelList;
};
-
-#endif //IRCCONNECTIONWIZARD_H
+#endif // IRCCONNECTIONWIZARD_H
#include "qtui.h"
#include "util.h"
-KNotificationBackend::KNotificationBackend(QObject *parent)
+KNotificationBackend::KNotificationBackend(QObject* parent)
: AbstractNotificationBackend(parent)
{
- connect(QtUi::mainWindow()->systemTray(), &SystemTray::activated,
- this, selectOverload<SystemTray::ActivationReason>(&KNotificationBackend::notificationActivated));
+ connect(QtUi::mainWindow()->systemTray(),
+ &SystemTray::activated,
+ this,
+ selectOverload<SystemTray::ActivationReason>(&KNotificationBackend::notificationActivated));
updateToolTip();
}
-
-void KNotificationBackend::notify(const Notification &n)
+void KNotificationBackend::notify(const Notification& n)
{
QString type;
switch (n.type) {
case Highlight:
- type = "Highlight"; break;
+ type = "Highlight";
+ break;
case HighlightFocused:
- type = "HighlightFocused"; break;
+ type = "HighlightFocused";
+ break;
case PrivMsg:
- type = "PrivMsg"; break;
+ type = "PrivMsg";
+ break;
case PrivMsgFocused:
- type = "PrivMsgFocused"; break;
+ type = "PrivMsgFocused";
+ break;
}
QString message = QString("<b><%1></b> %2").arg(n.sender, n.message.toHtmlEscaped());
- KNotification *notification = KNotification::event(type, message, icon::get("dialog-information").pixmap(48), QtUi::mainWindow(),
- KNotification::RaiseWidgetOnActivation
- |KNotification::CloseWhenWidgetActivated
- |KNotification::CloseOnTimeout);
- connect(notification, selectOverload<uint>(&KNotification::activated), this, selectOverload<>(&KNotificationBackend::notificationActivated));
+ KNotification* notification = KNotification::event(type,
+ message,
+ icon::get("dialog-information").pixmap(48),
+ QtUi::mainWindow(),
+ KNotification::RaiseWidgetOnActivation | KNotification::CloseWhenWidgetActivated
+ | KNotification::CloseOnTimeout);
+ connect(notification,
+ selectOverload<uint>(&KNotification::activated),
+ this,
+ selectOverload<>(&KNotificationBackend::notificationActivated));
notification->setActions(QStringList("View"));
notification->setProperty("notificationId", n.notificationId);
updateToolTip();
}
-
void KNotificationBackend::removeNotificationById(uint notificationId)
{
- QList<QPair<uint, QPointer<KNotification> > >::iterator i = _notifications.begin();
+ QList<QPair<uint, QPointer<KNotification>>>::iterator i = _notifications.begin();
while (i != _notifications.end()) {
if (i->first == notificationId) {
if (i->second)
updateToolTip();
}
-
void KNotificationBackend::close(uint notificationId)
{
removeNotificationById(notificationId);
- //if(!_notifications.count()) // FIXME make configurable
+ // if(!_notifications.count()) // FIXME make configurable
}
-
void KNotificationBackend::notificationActivated()
{
uint id = 0;
- KNotification *n = qobject_cast<KNotification *>(sender());
+ KNotification* n = qobject_cast<KNotification*>(sender());
if (n)
id = n->property("notificationId").toUInt();
notificationActivated(id);
}
-
void KNotificationBackend::notificationActivated(SystemTray::ActivationReason reason)
{
if (reason == SystemTray::Trigger) {
}
}
-
void KNotificationBackend::notificationActivated(uint notificationId)
{
emit activated(notificationId);
}
-
void KNotificationBackend::updateToolTip()
{
QtUi::mainWindow()->systemTray()->setToolTip("Quassel IRC",
- _notifications.count() ? tr("%n pending highlight(s)", "", _notifications.count()) : QString());
+ _notifications.count() ? tr("%n pending highlight(s)", "", _notifications.count())
+ : QString());
}
-
-SettingsPage *KNotificationBackend::createConfigWidget() const
+SettingsPage* KNotificationBackend::createConfigWidget() const
{
return new ConfigWidget();
}
-
/***************************************************************************/
-KNotificationBackend::ConfigWidget::ConfigWidget(QWidget *parent) : SettingsPage("Internal", "KNotification", parent)
+KNotificationBackend::ConfigWidget::ConfigWidget(QWidget* parent)
+ : SettingsPage("Internal", "KNotification", parent)
{
_widget = new KNotifyConfigWidget(this);
_widget->setApplication("quassel");
- QVBoxLayout *layout = new QVBoxLayout(this);
+ QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(_widget);
connect(_widget, &KNotifyConfigWidget::changed, this, &ConfigWidget::widgetChanged);
}
-
void KNotificationBackend::ConfigWidget::widgetChanged(bool changed)
{
setChangedState(changed);
}
-
void KNotificationBackend::ConfigWidget::load()
{
setChangedState(false);
}
-
void KNotificationBackend::ConfigWidget::save()
{
_widget->save();
Q_OBJECT
public:
- KNotificationBackend(QObject *parent = nullptr);
+ KNotificationBackend(QObject* parent = nullptr);
- void notify(const Notification &) override;
+ void notify(const Notification&) override;
void close(uint notificationId) override;
- SettingsPage *createConfigWidget() const override;
+ SettingsPage* createConfigWidget() const override;
private slots:
void notificationActivated();
QList<QPair<uint, QPointer<KNotification>>> _notifications;
};
-
class KNotificationBackend::ConfigWidget : public SettingsPage
{
Q_OBJECT
public:
- ConfigWidget(QWidget *parent = nullptr);
+ ConfigWidget(QWidget* parent = nullptr);
void save() override;
void load() override;
void widgetChanged(bool);
private:
- KNotifyConfigWidget *_widget;
+ KNotifyConfigWidget* _widget;
};
#ifndef QT_NO_SYSTEMTRAYICON
-#include "legacysystemtray.h"
+# include "legacysystemtray.h"
-#include "icon.h"
-#include "mainwin.h"
-#include "qtui.h"
+# include "icon.h"
+# include "mainwin.h"
+# include "qtui.h"
-LegacySystemTray::LegacySystemTray(QWidget *parent)
+LegacySystemTray::LegacySystemTray(QWidget* parent)
: SystemTray(parent)
, _trayIcon{new QSystemTrayIcon(associatedWidget())}
{
-
-#ifndef Q_OS_MAC
- connect(_trayIcon, &QSystemTrayIcon::activated,
- this, &LegacySystemTray::onActivated);
-#endif
- connect(_trayIcon, &QSystemTrayIcon::messageClicked,
- this, &LegacySystemTray::onMessageClicked);
+# ifndef Q_OS_MAC
+ connect(_trayIcon, &QSystemTrayIcon::activated, this, &LegacySystemTray::onActivated);
+# endif
+ connect(_trayIcon, &QSystemTrayIcon::messageClicked, this, &LegacySystemTray::onMessageClicked);
_trayIcon->setContextMenu(trayMenu());
_trayIcon->setVisible(false);
updateToolTip();
}
-
bool LegacySystemTray::isSystemTrayAvailable() const
{
- return mode() == Mode::Legacy
- ? QSystemTrayIcon::isSystemTrayAvailable()
- : SystemTray::isSystemTrayAvailable();
+ return mode() == Mode::Legacy ? QSystemTrayIcon::isSystemTrayAvailable() : SystemTray::isSystemTrayAvailable();
}
-
void LegacySystemTray::onVisibilityChanged(bool isVisible)
{
if (mode() == Legacy) {
}
}
-
void LegacySystemTray::onModeChanged(Mode mode)
{
if (mode == Mode::Legacy) {
}
}
-
void LegacySystemTray::updateIcon()
{
QString iconName = (state() == NeedsAttention) ? currentAttentionIconName() : currentIconName();
_trayIcon->setIcon(icon::get(iconName, QString{":/icons/hicolor/24x24/status/%1.svg"}.arg(iconName)));
}
-
void LegacySystemTray::updateToolTip()
{
-#if defined Q_OS_MAC || defined Q_OS_WIN
+# if defined Q_OS_MAC || defined Q_OS_WIN
QString tooltip = QString("%1").arg(toolTipTitle());
if (!toolTipSubTitle().isEmpty())
tooltip += QString("\n%1").arg(toolTipSubTitle());
-#else
+# else
QString tooltip = QString("<b>%1</b>").arg(toolTipTitle());
if (!toolTipSubTitle().isEmpty())
tooltip += QString("<br>%1").arg(toolTipSubTitle());
-#endif
+# endif
_trayIcon->setToolTip(tooltip);
}
-
void LegacySystemTray::onActivated(QSystemTrayIcon::ActivationReason reason)
{
activate((SystemTray::ActivationReason)reason);
}
-
void LegacySystemTray::onMessageClicked()
{
emit messageClicked(_lastMessageId);
}
-
-void LegacySystemTray::showMessage(const QString &title, const QString &message, SystemTray::MessageIcon icon, int msTimeout, uint id)
+void LegacySystemTray::showMessage(const QString& title, const QString& message, SystemTray::MessageIcon icon, int msTimeout, uint id)
{
// fancy stuff later: show messages in order
// for now, we just show the last message
_trayIcon->showMessage(title, message, (QSystemTrayIcon::MessageIcon)icon, msTimeout);
}
-
void LegacySystemTray::closeMessage(uint notificationId)
{
Q_UNUSED(notificationId)
// there really seems to be no sane way to close the bubble... :(
-#ifdef Q_WS_X11
+# ifdef Q_WS_X11
showMessage("", "", NoIcon, 1);
-#endif
+# endif
}
-
#endif /* QT_NO_SYSTEMTRAYICON */
#ifndef QT_NO_SYSTEMTRAYICON
-#include <QString>
-#include <QSystemTrayIcon>
+# include <QString>
+# include <QSystemTrayIcon>
-#include "systemtray.h"
+# include "systemtray.h"
class LegacySystemTray : public SystemTray
{
Q_OBJECT
public:
- explicit LegacySystemTray(QWidget *parent);
+ explicit LegacySystemTray(QWidget* parent);
bool isSystemTrayAvailable() const override;
public slots:
- void showMessage(const QString &title, const QString &message, MessageIcon icon = Information, int msTimeout = 10000, uint notificationId = 0) override;
+ void showMessage(const QString& title,
+ const QString& message,
+ MessageIcon icon = Information,
+ int msTimeout = 10000,
+ uint notificationId = 0) override;
void closeMessage(uint notificationId) override;
private slots:
void updateToolTip();
private:
- uint _lastMessageId {0};
+ uint _lastMessageId{0};
- QSystemTrayIcon *_trayIcon;
+ QSystemTrayIcon* _trayIcon;
};
#endif /* QT_NO_SYSTEMTRAYICON */
#include "mainpage.h"
-#include <QPushButton>
#include <QImage>
#include <QLabel>
#include <QLayout>
#include <QPainter>
+#include <QPushButton>
#include "client.h"
#include "coreconnectdlg.h"
#include "icon.h"
-MainPage::MainPage(QWidget *parent) : QWidget(parent)
+MainPage::MainPage(QWidget* parent)
+ : QWidget(parent)
{
- auto *layout = new QVBoxLayout(this);
+ auto* layout = new QVBoxLayout(this);
layout->setAlignment(Qt::AlignCenter);
- QLabel *label = new QLabel(this);
+ QLabel* label = new QLabel(this);
label->setPixmap(QPixmap(":/pics/quassel-logo.png"));
layout->addWidget(label);
{
if (Client::coreConnection()->state() == CoreConnection::Disconnected) {
_connectButton->setEnabled(true);
- } else {
+ }
+ else {
_connectButton->setDisabled(true);
}
}
Q_OBJECT
public:
- MainPage(QWidget *parent = nullptr);
+ MainPage(QWidget* parent = nullptr);
private slots:
void showCoreConnectionDlg();
void coreConnectionStateChanged();
private:
- QPushButton *_connectButton;
+ QPushButton* _connectButton;
};
-
#endif
#include "mainwin.h"
#include <QIcon>
+#include <QInputDialog>
#include <QMenuBar>
#include <QMessageBox>
#include <QStatusBar>
#include <QTableView>
#include <QToolBar>
-#include <QInputDialog>
#ifdef HAVE_KF5
-# include <kconfigwidgets_version.h>
-# include <KConfigWidgets/KStandardAction>
-# include <KXmlGui/KHelpMenu>
-# include <KXmlGui/KShortcutsDialog>
-# include <KXmlGui/KToolBar>
-# include <KWidgetsAddons/KToggleFullScreenAction>
+# include <kconfigwidgets_version.h>
+
+# include <KConfigWidgets/KStandardAction>
+# include <KWidgetsAddons/KToggleFullScreenAction>
+# include <KXmlGui/KHelpMenu>
+# include <KXmlGui/KShortcutsDialog>
+# include <KXmlGui/KToolBar>
#endif
#ifdef Q_WS_X11
-# include <QX11Info>
+# include <QX11Info>
#endif
#include "aboutdlg.h"
-#include "awaylogfilter.h"
-#include "awaylogview.h"
#include "action.h"
#include "actioncollection.h"
+#include "awaylogfilter.h"
+#include "awaylogview.h"
#include "bufferhotlistfilter.h"
#include "buffermodel.h"
#include "bufferview.h"
#include "clientignorelistmanager.h"
#include "clienttransfer.h"
#include "clienttransfermanager.h"
+#include "contextmenuactionprovider.h"
#include "coreconfigwizard.h"
#include "coreconnectdlg.h"
#include "coreconnection.h"
#include "coreconnectionstatuswidget.h"
#include "coreinfodlg.h"
-#include "contextmenuactionprovider.h"
#include "debugbufferviewoverlay.h"
#include "debuglogdlg.h"
#include "debugmessagemodelfilter.h"
#include "flatproxymodel.h"
#include "icon.h"
#include "inputwidget.h"
-#include "irclistmodel.h"
#include "ircconnectionwizard.h"
+#include "irclistmodel.h"
#include "legacysystemtray.h"
#include "msgprocessorstatuswidget.h"
#include "nicklistwidget.h"
#include "verticaldock.h"
#ifndef HAVE_KDE
-# ifdef HAVE_QTMULTIMEDIA
-# include "qtmultimedianotificationbackend.h"
-# endif
-# include "systraynotificationbackend.h"
-# include "taskbarnotificationbackend.h"
+# ifdef HAVE_QTMULTIMEDIA
+# include "qtmultimedianotificationbackend.h"
+# endif
+# include "systraynotificationbackend.h"
+# include "taskbarnotificationbackend.h"
#else /* HAVE_KDE */
-# include "knotificationbackend.h"
+# include "knotificationbackend.h"
#endif /* HAVE_KDE */
#include "systrayanimationnotificationbackend.h"
-
#ifdef HAVE_LIBSNORE
-# include "snorenotificationbackend.h"
+# include "snorenotificationbackend.h"
#endif
#ifdef HAVE_SSL
-# include "sslinfodlg.h"
+# include "sslinfodlg.h"
#endif
#ifdef HAVE_NOTIFICATION_CENTER
- #include "osxnotificationbackend.h"
+# include "osxnotificationbackend.h"
#endif
#ifdef HAVE_DBUS
- #include "dockmanagernotificationbackend.h"
+# include "dockmanagernotificationbackend.h"
#endif
+#include <settingspages/corehighlightsettingspage.h>
+
#include "settingspages/aliasessettingspage.h"
#include "settingspages/appearancesettingspage.h"
#include "settingspages/backlogsettingspage.h"
#include "settingspages/bufferviewsettingspage.h"
#include "settingspages/chatmonitorsettingspage.h"
-#include "settingspages/chatviewsettingspage.h"
#include "settingspages/chatviewcolorsettingspage.h"
+#include "settingspages/chatviewsettingspage.h"
#include "settingspages/connectionsettingspage.h"
#include "settingspages/coreaccountsettingspage.h"
#include "settingspages/coreconnectionsettingspage.h"
-#include <settingspages/corehighlightsettingspage.h>
#include "settingspages/dccsettingspage.h"
#include "settingspages/highlightsettingspage.h"
#include "settingspages/identitiessettingspage.h"
#include "settingspages/topicwidgetsettingspage.h"
#ifndef HAVE_KDE
-# include "settingspages/shortcutssettingspage.h"
+# include "settingspages/shortcutssettingspage.h"
#endif
#ifdef HAVE_SONNET
-# include "settingspages/sonnetsettingspage.h"
+# include "settingspages/sonnetsettingspage.h"
#endif
-
-MainWin::MainWin(QWidget *parent)
+MainWin::MainWin(QWidget* parent)
#ifdef HAVE_KDE
- : KMainWindow(parent), _kHelpMenu(new KHelpMenu(this)),
+ : KMainWindow(parent)
+ , _kHelpMenu(new KHelpMenu(this))
+ ,
#else
- : QMainWindow(parent),
+ : QMainWindow(parent)
+ ,
#endif
- _msgProcessorStatusWidget(new MsgProcessorStatusWidget(this)),
- _coreConnectionStatusWidget(new CoreConnectionStatusWidget(Client::coreConnection(), this)),
- _titleSetter(this)
+ _msgProcessorStatusWidget(new MsgProcessorStatusWidget(this))
+ , _coreConnectionStatusWidget(new CoreConnectionStatusWidget(Client::coreConnection(), this))
+ , _titleSetter(this)
{
- setAttribute(Qt::WA_DeleteOnClose, false); // we delete the mainwin manually
+ setAttribute(Qt::WA_DeleteOnClose, false); // we delete the mainwin manually
QtUiSettings uiSettings;
QString style = uiSettings.value("Style", QString()).toString();
updateIcon();
}
-
void MainWin::init()
{
connect(Client::instance(), &Client::networkCreated, this, &MainWin::clientNetworkCreated);
connect(Client::instance(), &Client::networkRemoved, this, &MainWin::clientNetworkRemoved);
- connect(Client::messageModel(), &QAbstractItemModel::rowsInserted,
- this, &MainWin::messagesInserted);
- connect(GraphicalUi::contextMenuActionProvider(),
- &NetworkModelController::showChannelList,
- this, &MainWin::showChannelList);
- connect(Client::instance(),
- &Client::showChannelList,
- this, &MainWin::showChannelList);
+ connect(Client::messageModel(), &QAbstractItemModel::rowsInserted, this, &MainWin::messagesInserted);
+ connect(GraphicalUi::contextMenuActionProvider(), &NetworkModelController::showChannelList, this, &MainWin::showChannelList);
+ connect(Client::instance(), &Client::showChannelList, this, &MainWin::showChannelList);
connect(GraphicalUi::contextMenuActionProvider(), &NetworkModelController::showNetworkConfig, this, &MainWin::showNetworkConfig);
connect(GraphicalUi::contextMenuActionProvider(), &NetworkModelController::showIgnoreList, this, &MainWin::showIgnoreList);
connect(Client::instance(), &Client::showIgnoreList, this, &MainWin::showIgnoreList);
_chatMonitorView->setFocusProxy(_inputWidget);
#ifndef HAVE_KDE
-# ifdef HAVE_QTMULTIMEDIA
+# ifdef HAVE_QTMULTIMEDIA
QtUi::registerNotificationBackend(new QtMultimediaNotificationBackend(this));
-# endif
+# endif
QtUi::registerNotificationBackend(new TaskbarNotificationBackend(this));
-#else /* HAVE_KDE */
+#else /* HAVE_KDE */
QtUi::registerNotificationBackend(new KNotificationBackend(this));
#endif /* HAVE_KDE */
-
#ifndef QT_NO_SYSTEMTRAYICON
QtUi::registerNotificationBackend(new SystrayAnimationNotificationBackend(this));
#endif
connect(bufferWidget(), selectOverload<BufferId>(&AbstractBufferContainer::currentChanged), this, &MainWin::currentBufferChanged);
- setDisconnectedState(); // Disable menus and stuff
+ setDisconnectedState(); // Disable menus and stuff
#ifdef HAVE_KDE
setAutoSaveSettings();
QTimer::singleShot(0, this, &MainWin::doAutoConnect);
}
-
-void MainWin::saveStateToSettings(UiSettings &s)
+void MainWin::saveStateToSettings(UiSettings& s)
{
s.setValue("MainWinSize", _normalSize);
s.setValue("MainWinPos", _normalPos);
#endif
}
-
-void MainWin::restoreStateFromSettings(UiSettings &s)
+void MainWin::restoreStateFromSettings(UiSettings& s)
{
_normalSize = s.value("MainWinSize", size()).toSize();
_normalPos = s.value("MainWinPos", pos()).toPoint();
move(_normalPos);
#endif
- if ((Quassel::isOptionSet("hidewindow")
- || s.value("MainWinHidden").toBool())
- && _systemTray->isSystemTrayAvailable())
+ if ((Quassel::isOptionSet("hidewindow") || s.value("MainWinHidden").toBool()) && _systemTray->isSystemTrayAvailable())
QtUi::hideMainWidget();
else if (s.value("MainWinMinimized").toBool())
showMinimized();
show();
}
-QMenu *MainWin::createPopupMenu()
+QMenu* MainWin::createPopupMenu()
{
- QMenu *popupMenu = QMainWindow::createPopupMenu();
+ QMenu* popupMenu = QMainWindow::createPopupMenu();
popupMenu->addSeparator();
- ActionCollection *coll = QtUi::actionCollection("General");
+ ActionCollection* coll = QtUi::actionCollection("General");
popupMenu->addAction(coll->action("ToggleMenuBar"));
return popupMenu;
}
-
void MainWin::updateIcon()
{
QIcon icon;
setWindowIcon(icon);
}
-
void MainWin::setupActions()
{
- QAction *action{nullptr};
- ActionCollection *coll = QtUi::actionCollection("General", tr("General"));
+ QAction* action{nullptr};
+ ActionCollection* coll = QtUi::actionCollection("General", tr("General"));
// File
- coll->addActions({
- {"ConnectCore", new Action(icon::get("connect-quassel"), tr("&Connect to Core..."), coll, this, &MainWin::showCoreConnectionDlg)},
- {"DisconnectCore", new Action(icon::get("disconnect-quassel"), tr("&Disconnect from Core"), coll, Client::instance(), &Client::disconnectFromCore)},
- {"ChangePassword", new Action(icon::get("dialog-password"), tr("Change &Password..."), coll, this, &MainWin::showPasswordChangeDlg)},
- {"CoreInfo", new Action(icon::get("help-about"), tr("Core &Info..."), coll, this, &MainWin::showCoreInfoDlg)},
- {"ConfigureNetworks", new Action(icon::get("configure"), tr("Configure &Networks..."), coll, this, &MainWin::onConfigureNetworksTriggered)},
- {"Quit", new Action(icon::get("application-exit"), tr("&Quit"), coll, Quassel::instance(), &Quassel::quit, Qt::CTRL + Qt::Key_Q)}
- });
+ coll->addActions(
+ {{"ConnectCore", new Action(icon::get("connect-quassel"), tr("&Connect to Core..."), coll, this, &MainWin::showCoreConnectionDlg)},
+ {"DisconnectCore",
+ new Action(icon::get("disconnect-quassel"), tr("&Disconnect from Core"), coll, Client::instance(), &Client::disconnectFromCore)},
+ {"ChangePassword", new Action(icon::get("dialog-password"), tr("Change &Password..."), coll, this, &MainWin::showPasswordChangeDlg)},
+ {"CoreInfo", new Action(icon::get("help-about"), tr("Core &Info..."), coll, this, &MainWin::showCoreInfoDlg)},
+ {"ConfigureNetworks",
+ new Action(icon::get("configure"), tr("Configure &Networks..."), coll, this, &MainWin::onConfigureNetworksTriggered)},
+ {"Quit", new Action(icon::get("application-exit"), tr("&Quit"), coll, Quassel::instance(), &Quassel::quit, Qt::CTRL + Qt::Key_Q)}});
// View
coll->addAction("ConfigureBufferViews", new Action(tr("&Configure Chat Lists..."), coll, this, &MainWin::onConfigureViewsTriggered));
connect(action, &QAction::toggled, this, &MainWin::onLockLayoutToggled);
#ifdef HAVE_KDE
-#if KCONFIGWIDGETS_VERSION < QT_VERSION_CHECK(5,23,0)
+# if KCONFIGWIDGETS_VERSION < QT_VERSION_CHECK(5, 23, 0)
_fullScreenAction = KStandardAction::fullScreen(this, SLOT(onFullScreenToggled()), this, coll);
-#else
+# else
_fullScreenAction = KStandardAction::fullScreen(this, &MainWin::onFullScreenToggled, this, coll);
-#endif
+# endif
#else
- _fullScreenAction = new Action(icon::get("view-fullscreen"), tr("&Full Screen Mode"), coll, this, &MainWin::onFullScreenToggled, QKeySequence::FullScreen);
+ _fullScreenAction = new Action(icon::get("view-fullscreen"),
+ tr("&Full Screen Mode"),
+ coll,
+ this,
+ &MainWin::onFullScreenToggled,
+ QKeySequence::FullScreen);
_fullScreenAction->setCheckable(true);
coll->addAction("ToggleFullScreen", _fullScreenAction);
#endif
// Settings
- coll->addAction("ConfigureShortcuts", new Action(icon::get("configure-shortcuts"), tr("Configure &Shortcuts..."), coll,
- this, &MainWin::showShortcutsDlg))->setMenuRole(QAction::NoRole);
- coll->addAction("ConfigureQuassel", new Action(icon::get("configure"), tr("&Configure Quassel..."), coll,
- this, &MainWin::showSettingsDlg, QKeySequence(Qt::Key_F7)))->setMenuRole(QAction::PreferencesRole);
+ coll->addAction("ConfigureShortcuts",
+ new Action(icon::get("configure-shortcuts"), tr("Configure &Shortcuts..."), coll, this, &MainWin::showShortcutsDlg))
+ ->setMenuRole(QAction::NoRole);
+ coll->addAction("ConfigureQuassel",
+ new Action(icon::get("configure"), tr("&Configure Quassel..."), coll, this, &MainWin::showSettingsDlg, QKeySequence(Qt::Key_F7)))
+ ->setMenuRole(QAction::PreferencesRole);
// Help
- coll->addAction("AboutQuassel", new Action(icon::get("quassel"), tr("&About Quassel"), coll, this, &MainWin::showAboutDlg))->setMenuRole(QAction::AboutRole);
- coll->addAction("AboutQt", new Action(QIcon(":/pics/qt-logo.png"), tr("About &Qt"), coll, qApp, &QApplication::aboutQt))->setMenuRole(QAction::AboutQtRole);
- coll->addActions({
- {"DebugNetworkModel", new Action(icon::get("tools-report-bug"), tr("Debug &NetworkModel"), coll, this, &MainWin::onDebugNetworkModelTriggered)},
- {"DebugBufferViewOverlay", new Action(icon::get("tools-report-bug"), tr("Debug &BufferViewOverlay"), coll, this, &MainWin::onDebugBufferViewOverlayTriggered)},
- {"DebugMessageModel", new Action(icon::get("tools-report-bug"), tr("Debug &MessageModel"), coll, this, &MainWin::onDebugMessageModelTriggered)},
- {"DebugHotList", new Action(icon::get("tools-report-bug"), tr("Debug &HotList"), coll, this, &MainWin::onDebugHotListTriggered)},
- {"DebugLog", new Action(icon::get("tools-report-bug"), tr("Debug &Log"), coll, this, &MainWin::onDebugLogTriggered)},
- {"ShowResourceTree", new Action(icon::get("tools-report-bug"), tr("Show &Resource Tree"), coll, this, &MainWin::onShowResourceTreeTriggered)},
- {"ReloadStyle", new Action(icon::get("view-refresh"), tr("Reload Stylesheet"), coll, QtUi::style(), &UiStyle::reload, QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_R))}
- });
+ coll->addAction("AboutQuassel", new Action(icon::get("quassel"), tr("&About Quassel"), coll, this, &MainWin::showAboutDlg))
+ ->setMenuRole(QAction::AboutRole);
+ coll->addAction("AboutQt", new Action(QIcon(":/pics/qt-logo.png"), tr("About &Qt"), coll, qApp, &QApplication::aboutQt))
+ ->setMenuRole(QAction::AboutQtRole);
+ coll->addActions(
+ {{"DebugNetworkModel",
+ new Action(icon::get("tools-report-bug"), tr("Debug &NetworkModel"), coll, this, &MainWin::onDebugNetworkModelTriggered)},
+ {"DebugBufferViewOverlay",
+ new Action(icon::get("tools-report-bug"), tr("Debug &BufferViewOverlay"), coll, this, &MainWin::onDebugBufferViewOverlayTriggered)},
+ {"DebugMessageModel",
+ new Action(icon::get("tools-report-bug"), tr("Debug &MessageModel"), coll, this, &MainWin::onDebugMessageModelTriggered)},
+ {"DebugHotList", new Action(icon::get("tools-report-bug"), tr("Debug &HotList"), coll, this, &MainWin::onDebugHotListTriggered)},
+ {"DebugLog", new Action(icon::get("tools-report-bug"), tr("Debug &Log"), coll, this, &MainWin::onDebugLogTriggered)},
+ {"ShowResourceTree",
+ new Action(icon::get("tools-report-bug"), tr("Show &Resource Tree"), coll, this, &MainWin::onShowResourceTreeTriggered)},
+ {"ReloadStyle",
+ new Action(icon::get("view-refresh"),
+ tr("Reload Stylesheet"),
+ coll,
+ QtUi::style(),
+ &UiStyle::reload,
+ QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_R))}});
// Other
coll->addAction("HideCurrentBuffer", new Action(tr("Hide Current Buffer"), coll, this, &MainWin::hideCurrentBuffer, QKeySequence::Close));
// Text formatting
coll = QtUi::actionCollection("TextFormat", tr("Text formatting"));
- coll->addActions({
- {"FormatApplyColor", new Action(
- icon::get("format-text-color"), tr("Apply foreground color"), coll,
- this, &MainWin::onFormatApplyColorTriggered,
- QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_G))
- },
- {"FormatApplyColorFill", new Action(
- icon::get("format-fill-color"), tr("Apply background color"), coll,
- this, &MainWin::onFormatApplyColorFillTriggered,
- QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_B))
- },
- {"FormatClear", new Action(
- icon::get("edit-clear"), tr("Clear formatting"), coll,
- this, &MainWin::onFormatClearTriggered,
- QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C))
- },
- {"FormatBold", new Action(
- icon::get("format-text-bold"), tr("Toggle bold"), coll,
- this, &MainWin::onFormatBoldTriggered,
- QKeySequence::Bold)
- },
- {"FormatItalic", new Action(
- icon::get("format-text-italic"), tr("Toggle italics"), coll,
- this, &MainWin::onFormatItalicTriggered,
- QKeySequence::Italic)
- },
- {"FormatUnderline", new Action(
- icon::get("format-text-underline"), tr("Toggle underline"), coll,
- this, &MainWin::onFormatUnderlineTriggered,
- QKeySequence::Underline)
- }
- });
+ coll->addActions(
+ {{"FormatApplyColor",
+ new Action(icon::get("format-text-color"),
+ tr("Apply foreground color"),
+ coll,
+ this,
+ &MainWin::onFormatApplyColorTriggered,
+ QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_G))},
+ {"FormatApplyColorFill",
+ new Action(icon::get("format-fill-color"),
+ tr("Apply background color"),
+ coll,
+ this,
+ &MainWin::onFormatApplyColorFillTriggered,
+ QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_B))},
+ {"FormatClear",
+ new Action(icon::get("edit-clear"),
+ tr("Clear formatting"),
+ coll,
+ this,
+ &MainWin::onFormatClearTriggered,
+ QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C))},
+ {"FormatBold",
+ new Action(icon::get("format-text-bold"), tr("Toggle bold"), coll, this, &MainWin::onFormatBoldTriggered, QKeySequence::Bold)},
+ {"FormatItalic",
+ new Action(icon::get("format-text-italic"), tr("Toggle italics"), coll, this, &MainWin::onFormatItalicTriggered, QKeySequence::Italic)},
+ {"FormatUnderline",
+ new Action(icon::get("format-text-underline"),
+ tr("Toggle underline"),
+ coll,
+ this,
+ &MainWin::onFormatUnderlineTriggered,
+ QKeySequence::Underline)}});
// Navigation
coll = QtUi::actionCollection("Navigation", tr("Navigation"));
- coll->addActions({
- {"JumpHotBuffer", new Action(tr("Jump to hot chat"), coll, this, &MainWin::onJumpHotBufferTriggered, QKeySequence(Qt::META + Qt::Key_A))},
- {"ActivateBufferFilter", new Action(tr("Activate the buffer search"), coll, this, &MainWin::onBufferSearchTriggered, QKeySequence(Qt::CTRL + Qt::Key_S))}
- });
+ coll->addActions(
+ {{"JumpHotBuffer",
+ new Action(tr("Jump to hot chat"), coll, this, &MainWin::onJumpHotBufferTriggered, QKeySequence(Qt::META + Qt::Key_A))},
+ {"ActivateBufferFilter",
+ new Action(tr("Activate the buffer search"), coll, this, &MainWin::onBufferSearchTriggered, QKeySequence(Qt::CTRL + Qt::Key_S))}});
// Jump keys
#ifdef Q_OS_MAC
const int jumpModifier = Qt::AltModifier;
#endif
- coll->addAction("BindJumpKey0", new Action(tr("Set Quick Access #0"), coll, this, &MainWin::bindJumpKey,
- QKeySequence(bindModifier + Qt::Key_0)))->setProperty("Index", 0);
- coll->addAction("BindJumpKey1", new Action(tr("Set Quick Access #1"), coll, this, &MainWin::bindJumpKey,
- QKeySequence(bindModifier + Qt::Key_1)))->setProperty("Index", 1);
- coll->addAction("BindJumpKey2", new Action(tr("Set Quick Access #2"), coll, this, &MainWin::bindJumpKey,
- QKeySequence(bindModifier + Qt::Key_2)))->setProperty("Index", 2);
- coll->addAction("BindJumpKey3", new Action(tr("Set Quick Access #3"), coll, this, &MainWin::bindJumpKey,
- QKeySequence(bindModifier + Qt::Key_3)))->setProperty("Index", 3);
- coll->addAction("BindJumpKey4", new Action(tr("Set Quick Access #4"), coll, this, &MainWin::bindJumpKey,
- QKeySequence(bindModifier + Qt::Key_4)))->setProperty("Index", 4);
- coll->addAction("BindJumpKey5", new Action(tr("Set Quick Access #5"), coll, this, &MainWin::bindJumpKey,
- QKeySequence(bindModifier + Qt::Key_5)))->setProperty("Index", 5);
- coll->addAction("BindJumpKey6", new Action(tr("Set Quick Access #6"), coll, this, &MainWin::bindJumpKey,
- QKeySequence(bindModifier + Qt::Key_6)))->setProperty("Index", 6);
- coll->addAction("BindJumpKey7", new Action(tr("Set Quick Access #7"), coll, this, &MainWin::bindJumpKey,
- QKeySequence(bindModifier + Qt::Key_7)))->setProperty("Index", 7);
- coll->addAction("BindJumpKey8", new Action(tr("Set Quick Access #8"), coll, this, &MainWin::bindJumpKey,
- QKeySequence(bindModifier + Qt::Key_8)))->setProperty("Index", 8);
- coll->addAction("BindJumpKey9", new Action(tr("Set Quick Access #9"), coll, this, &MainWin::bindJumpKey,
- QKeySequence(bindModifier + Qt::Key_9)))->setProperty("Index", 9);
-
- coll->addAction("JumpKey0", new Action(tr("Quick Access #0"), coll, this, &MainWin::onJumpKey,
- QKeySequence(jumpModifier + Qt::Key_0)))->setProperty("Index", 0);
- coll->addAction("JumpKey1", new Action(tr("Quick Access #1"), coll, this, &MainWin::onJumpKey,
- QKeySequence(jumpModifier + Qt::Key_1)))->setProperty("Index", 1);
- coll->addAction("JumpKey2", new Action(tr("Quick Access #2"), coll, this, &MainWin::onJumpKey,
- QKeySequence(jumpModifier + Qt::Key_2)))->setProperty("Index", 2);
- coll->addAction("JumpKey3", new Action(tr("Quick Access #3"), coll, this, &MainWin::onJumpKey,
- QKeySequence(jumpModifier + Qt::Key_3)))->setProperty("Index", 3);
- coll->addAction("JumpKey4", new Action(tr("Quick Access #4"), coll, this, &MainWin::onJumpKey,
- QKeySequence(jumpModifier + Qt::Key_4)))->setProperty("Index", 4);
- coll->addAction("JumpKey5", new Action(tr("Quick Access #5"), coll, this, &MainWin::onJumpKey,
- QKeySequence(jumpModifier + Qt::Key_5)))->setProperty("Index", 5);
- coll->addAction("JumpKey6", new Action(tr("Quick Access #6"), coll, this, &MainWin::onJumpKey,
- QKeySequence(jumpModifier + Qt::Key_6)))->setProperty("Index", 6);
- coll->addAction("JumpKey7", new Action(tr("Quick Access #7"), coll, this, &MainWin::onJumpKey,
- QKeySequence(jumpModifier + Qt::Key_7)))->setProperty("Index", 7);
- coll->addAction("JumpKey8", new Action(tr("Quick Access #8"), coll, this, &MainWin::onJumpKey,
- QKeySequence(jumpModifier + Qt::Key_8)))->setProperty("Index", 8);
- coll->addAction("JumpKey9", new Action(tr("Quick Access #9"), coll, this, &MainWin::onJumpKey,
- QKeySequence(jumpModifier + Qt::Key_9)))->setProperty("Index", 9);
+ coll->addAction("BindJumpKey0",
+ new Action(tr("Set Quick Access #0"), coll, this, &MainWin::bindJumpKey, QKeySequence(bindModifier + Qt::Key_0)))
+ ->setProperty("Index", 0);
+ coll->addAction("BindJumpKey1",
+ new Action(tr("Set Quick Access #1"), coll, this, &MainWin::bindJumpKey, QKeySequence(bindModifier + Qt::Key_1)))
+ ->setProperty("Index", 1);
+ coll->addAction("BindJumpKey2",
+ new Action(tr("Set Quick Access #2"), coll, this, &MainWin::bindJumpKey, QKeySequence(bindModifier + Qt::Key_2)))
+ ->setProperty("Index", 2);
+ coll->addAction("BindJumpKey3",
+ new Action(tr("Set Quick Access #3"), coll, this, &MainWin::bindJumpKey, QKeySequence(bindModifier + Qt::Key_3)))
+ ->setProperty("Index", 3);
+ coll->addAction("BindJumpKey4",
+ new Action(tr("Set Quick Access #4"), coll, this, &MainWin::bindJumpKey, QKeySequence(bindModifier + Qt::Key_4)))
+ ->setProperty("Index", 4);
+ coll->addAction("BindJumpKey5",
+ new Action(tr("Set Quick Access #5"), coll, this, &MainWin::bindJumpKey, QKeySequence(bindModifier + Qt::Key_5)))
+ ->setProperty("Index", 5);
+ coll->addAction("BindJumpKey6",
+ new Action(tr("Set Quick Access #6"), coll, this, &MainWin::bindJumpKey, QKeySequence(bindModifier + Qt::Key_6)))
+ ->setProperty("Index", 6);
+ coll->addAction("BindJumpKey7",
+ new Action(tr("Set Quick Access #7"), coll, this, &MainWin::bindJumpKey, QKeySequence(bindModifier + Qt::Key_7)))
+ ->setProperty("Index", 7);
+ coll->addAction("BindJumpKey8",
+ new Action(tr("Set Quick Access #8"), coll, this, &MainWin::bindJumpKey, QKeySequence(bindModifier + Qt::Key_8)))
+ ->setProperty("Index", 8);
+ coll->addAction("BindJumpKey9",
+ new Action(tr("Set Quick Access #9"), coll, this, &MainWin::bindJumpKey, QKeySequence(bindModifier + Qt::Key_9)))
+ ->setProperty("Index", 9);
+
+ coll->addAction("JumpKey0", new Action(tr("Quick Access #0"), coll, this, &MainWin::onJumpKey, QKeySequence(jumpModifier + Qt::Key_0)))
+ ->setProperty("Index", 0);
+ coll->addAction("JumpKey1", new Action(tr("Quick Access #1"), coll, this, &MainWin::onJumpKey, QKeySequence(jumpModifier + Qt::Key_1)))
+ ->setProperty("Index", 1);
+ coll->addAction("JumpKey2", new Action(tr("Quick Access #2"), coll, this, &MainWin::onJumpKey, QKeySequence(jumpModifier + Qt::Key_2)))
+ ->setProperty("Index", 2);
+ coll->addAction("JumpKey3", new Action(tr("Quick Access #3"), coll, this, &MainWin::onJumpKey, QKeySequence(jumpModifier + Qt::Key_3)))
+ ->setProperty("Index", 3);
+ coll->addAction("JumpKey4", new Action(tr("Quick Access #4"), coll, this, &MainWin::onJumpKey, QKeySequence(jumpModifier + Qt::Key_4)))
+ ->setProperty("Index", 4);
+ coll->addAction("JumpKey5", new Action(tr("Quick Access #5"), coll, this, &MainWin::onJumpKey, QKeySequence(jumpModifier + Qt::Key_5)))
+ ->setProperty("Index", 5);
+ coll->addAction("JumpKey6", new Action(tr("Quick Access #6"), coll, this, &MainWin::onJumpKey, QKeySequence(jumpModifier + Qt::Key_6)))
+ ->setProperty("Index", 6);
+ coll->addAction("JumpKey7", new Action(tr("Quick Access #7"), coll, this, &MainWin::onJumpKey, QKeySequence(jumpModifier + Qt::Key_7)))
+ ->setProperty("Index", 7);
+ coll->addAction("JumpKey8", new Action(tr("Quick Access #8"), coll, this, &MainWin::onJumpKey, QKeySequence(jumpModifier + Qt::Key_8)))
+ ->setProperty("Index", 8);
+ coll->addAction("JumpKey9", new Action(tr("Quick Access #9"), coll, this, &MainWin::onJumpKey, QKeySequence(jumpModifier + Qt::Key_9)))
+ ->setProperty("Index", 9);
// Buffer navigation
- coll->addAction("NextBufferView", new Action(icon::get("go-next-view"), tr("Activate Next Chat List"), coll,
- this, &MainWin::nextBufferView, QKeySequence(QKeySequence::Forward)));
- coll->addAction("PreviousBufferView", new Action(icon::get("go-previous-view"), tr("Activate Previous Chat List"), coll,
- this, &MainWin::previousBufferView, QKeySequence::Back));
- coll->addAction("NextBuffer", new Action(icon::get("go-down"), tr("Go to Next Chat"), coll,
- this, &MainWin::nextBuffer, QKeySequence(Qt::ALT + Qt::Key_Down)));
- coll->addAction("PreviousBuffer", new Action(icon::get("go-up"), tr("Go to Previous Chat"), coll,
- this, &MainWin::previousBuffer, QKeySequence(Qt::ALT + Qt::Key_Up)));
+ coll->addAction("NextBufferView",
+ new Action(icon::get("go-next-view"),
+ tr("Activate Next Chat List"),
+ coll,
+ this,
+ &MainWin::nextBufferView,
+ QKeySequence(QKeySequence::Forward)));
+ coll->addAction("PreviousBufferView",
+ new Action(icon::get("go-previous-view"),
+ tr("Activate Previous Chat List"),
+ coll,
+ this,
+ &MainWin::previousBufferView,
+ QKeySequence::Back));
+ coll->addAction("NextBuffer",
+ new Action(icon::get("go-down"),
+ tr("Go to Next Chat"),
+ coll,
+ this,
+ &MainWin::nextBuffer,
+ QKeySequence(Qt::ALT + Qt::Key_Down)));
+ coll->addAction("PreviousBuffer",
+ new Action(icon::get("go-up"),
+ tr("Go to Previous Chat"),
+ coll,
+ this,
+ &MainWin::previousBuffer,
+ QKeySequence(Qt::ALT + Qt::Key_Up)));
}
-
void MainWin::setupMenus()
{
- ActionCollection *coll = QtUi::actionCollection("General");
+ ActionCollection* coll = QtUi::actionCollection("General");
_fileMenu = menuBar()->addMenu(tr("&File"));
- static const QStringList coreActions = QStringList()
- << "ConnectCore" << "DisconnectCore" << "ChangePassword" << "CoreInfo";
+ static const QStringList coreActions = QStringList() << "ConnectCore"
+ << "DisconnectCore"
+ << "ChangePassword"
+ << "CoreInfo";
- QAction *coreAction;
- foreach(QString actionName, coreActions) {
+ QAction* coreAction;
+ foreach (QString actionName, coreActions) {
coreAction = coll->action(actionName);
_fileMenu->addAction(coreAction);
flagRemoteCoreOnly(coreAction);
_settingsMenu = menuBar()->addMenu(tr("&Settings"));
#ifdef HAVE_KDE
-#if KCONFIGWIDGETS_VERSION < QT_VERSION_CHECK(5,23,0)
+# if KCONFIGWIDGETS_VERSION < QT_VERSION_CHECK(5, 23, 0)
_settingsMenu->addAction(KStandardAction::configureNotifications(this, SLOT(showNotificationsDlg()), this));
_settingsMenu->addAction(KStandardAction::keyBindings(this, SLOT(showShortcutsDlg()), this));
-#else
+# else
_settingsMenu->addAction(KStandardAction::configureNotifications(this, &MainWin::showNotificationsDlg, this));
_settingsMenu->addAction(KStandardAction::keyBindings(this, &MainWin::showShortcutsDlg, this));
-#endif
+# endif
#else
_settingsMenu->addAction(coll->action("ConfigureShortcuts"));
#endif
_settingsMenu->addAction(coll->action("ConfigureQuassel"));
-
_helpMenu = menuBar()->addMenu(tr("&Help"));
_helpMenu->addAction(coll->action("AboutQuassel"));
#ifndef HAVE_KDE
_helpMenu->addAction(coll->action("AboutQt"));
#else
-#if KCONFIGWIDGETS_VERSION < QT_VERSION_CHECK(5,23,0)
+# if KCONFIGWIDGETS_VERSION < QT_VERSION_CHECK(5, 23, 0)
_helpMenu->addAction(KStandardAction::aboutKDE(_kHelpMenu, SLOT(aboutKDE()), this));
-#else
+# else
_helpMenu->addAction(KStandardAction::aboutKDE(_kHelpMenu, &KHelpMenu::aboutKDE, this));
-#endif
+# endif
#endif
_helpMenu->addSeparator();
_helpDebugMenu = _helpMenu->addMenu(icon::get("tools-report-bug"), tr("Debug"));
_helpDebugMenu->addAction(coll->action("ReloadStyle"));
// Toggle visibility
- QAction *showMenuBar = QtUi::actionCollection("General")->action("ToggleMenuBar");
+ QAction* showMenuBar = QtUi::actionCollection("General")->action("ToggleMenuBar");
QtUiSettings uiSettings;
bool enabled = uiSettings.value("ShowMenuBar", QVariant(true)).toBool();
connect(showMenuBar, &QAction::toggled, this, &MainWin::saveMenuBarStatus);
}
-
void MainWin::setupBufferWidget()
{
_bufferWidget = new BufferWidget(this);
setCentralWidget(_bufferWidget);
}
-
void MainWin::addBufferView(int bufferViewConfigId)
{
addBufferView(Client::bufferViewManager()->clientBufferViewConfig(bufferViewConfigId));
}
-
-void MainWin::addBufferView(ClientBufferViewConfig *config)
+void MainWin::addBufferView(ClientBufferViewConfig* config)
{
if (!config)
return;
config->setLocked(QtUiSettings().value("LockLayout", false).toBool());
- auto *dock = new BufferViewDock(config, this);
+ auto* dock = new BufferViewDock(config, this);
- //create the view and initialize it's filter
- auto *view = new BufferView(dock);
+ // create the view and initialize it's filter
+ auto* view = new BufferView(dock);
view->setFilteredModel(Client::bufferModel(), config);
- view->installEventFilter(_inputWidget); // for key presses
+ view->installEventFilter(_inputWidget); // for key presses
Client::bufferModel()->synchronizeView(view);
dock->setLocked(QtUiSettings().value("LockLayout", false).toBool());
dock->setWidget(view);
- dock->setVisible(_layoutLoaded); // don't show before state has been restored
+ dock->setVisible(_layoutLoaded); // don't show before state has been restored
addDockWidget(Qt::LeftDockWidgetArea, dock);
_bufferViewsMenu->addAction(dock->toggleViewAction());
nextBufferView();
}
-
void MainWin::removeBufferView(int bufferViewConfigId)
{
QVariant actionData;
- BufferViewDock *dock;
- foreach(QAction *action, _bufferViewsMenu->actions()) {
+ BufferViewDock* dock;
+ foreach (QAction* action, _bufferViewsMenu->actions()) {
actionData = action->data();
if (!actionData.isValid())
continue;
- dock = qobject_cast<BufferViewDock *>(action->parent());
+ dock = qobject_cast<BufferViewDock*>(action->parent());
if (dock && actionData.toInt() == bufferViewConfigId) {
removeAction(action);
Client::bufferViewOverlay()->removeView(dock->bufferViewId());
}
}
-
void MainWin::bufferViewToggled(bool enabled)
{
if (!enabled && !isMinimized()) {
// since this isn't our fault and we can't do anything about it, we suppress the resulting calls
return;
}
- auto *action = qobject_cast<QAction *>(sender());
+ auto* action = qobject_cast<QAction*>(sender());
Q_ASSERT(action);
- auto *dock = qobject_cast<BufferViewDock *>(action->parent());
+ auto* dock = qobject_cast<BufferViewDock*>(action->parent());
Q_ASSERT(dock);
// Make sure we don't toggle backlog fetch for a view we've already removed
Client::bufferViewOverlay()->removeView(dock->bufferViewId());
}
-
void MainWin::bufferViewVisibilityChanged(bool visible)
{
Q_UNUSED(visible);
- auto *dock = qobject_cast<BufferViewDock *>(sender());
+ auto* dock = qobject_cast<BufferViewDock*>(sender());
Q_ASSERT(dock);
if ((!dock->isHidden() && !activeBufferView()) || (dock->isHidden() && dock->isActive()))
nextBufferView();
}
-
-BufferView *MainWin::allBuffersView() const
+BufferView* MainWin::allBuffersView() const
{
// "All Buffers" is always the first dock created
if (_bufferViews.count() > 0)
return nullptr;
}
-
-BufferView *MainWin::activeBufferView() const
+BufferView* MainWin::activeBufferView() const
{
if (_activeBufferViewIndex < 0 || _activeBufferViewIndex >= _bufferViews.count())
return nullptr;
- BufferViewDock *dock = _bufferViews.at(_activeBufferViewIndex);
+ BufferViewDock* dock = _bufferViews.at(_activeBufferViewIndex);
return dock->isActive() ? dock->bufferView() : nullptr;
}
-
void MainWin::changeActiveBufferView(int bufferViewId)
{
if (bufferViewId < 0)
}
for (int i = 0; i < _bufferViews.count(); i++) {
- BufferViewDock *dock = _bufferViews.at(i);
+ BufferViewDock* dock = _bufferViews.at(i);
if (dock->bufferViewId() == bufferViewId && !dock->isHidden()) {
_activeBufferViewIndex = i;
dock->setActive(true);
}
}
- nextBufferView(); // fallback
+ nextBufferView(); // fallback
}
-
void MainWin::showPasswordChangeDlg()
{
- if(Client::isCoreFeatureEnabled(Quassel::Feature::PasswordChange)) {
+ if (Client::isCoreFeatureEnabled(Quassel::Feature::PasswordChange)) {
PasswordChangeDlg{}.exec();
}
else {
- QMessageBox box(QMessageBox::Warning, tr("Feature Not Supported"),
+ QMessageBox box(QMessageBox::Warning,
+ tr("Feature Not Supported"),
tr("<b>Your Quassel Core does not support this feature</b>"),
QMessageBox::Ok);
box.setInformativeText(tr("You need a Quassel Core v0.12.0 or newer in order to be able to remotely change your password."));
}
}
-
void MainWin::showMigrationWarning(bool show)
{
if (show && !_migrationWarning) {
_migrationWarning = new QMessageBox(QMessageBox::Information,
tr("Upgrading..."),
"<b>" + tr("Your database is being upgraded") + "</b>",
- QMessageBox::NoButton, this);
- _migrationWarning->setInformativeText("<p>"
- + tr("In order to support new features, we need to make changes to your backlog database. This may take a long while.")
- + "</p><p>"
- + tr("Do not exit Quassel until the upgrade is complete!")
- + "</p>");
+ QMessageBox::NoButton,
+ this);
+ _migrationWarning->setInformativeText(
+ "<p>" + tr("In order to support new features, we need to make changes to your backlog database. This may take a long while.")
+ + "</p><p>" + tr("Do not exit Quassel until the upgrade is complete!") + "</p>");
_migrationWarning->setStandardButtons(QMessageBox::NoButton);
_migrationWarning->show();
}
}
}
-
-void MainWin::onExitRequested(const QString &reason)
+void MainWin::onExitRequested(const QString& reason)
{
if (!reason.isEmpty()) {
QMessageBox box(QMessageBox::Critical,
}
}
-
void MainWin::changeActiveBufferView(bool backwards)
{
if (_activeBufferViewIndex >= 0 && _activeBufferViewIndex < _bufferViews.count()) {
return;
int c = _bufferViews.count();
- while (c--) { // yes, this will reactivate the current active one if all others fail
+ while (c--) { // yes, this will reactivate the current active one if all others fail
if (backwards) {
if (--_activeBufferViewIndex < 0)
- _activeBufferViewIndex = _bufferViews.count()-1;
+ _activeBufferViewIndex = _bufferViews.count() - 1;
}
else {
if (++_activeBufferViewIndex >= _bufferViews.count())
_activeBufferViewIndex = 0;
}
- BufferViewDock *dock = _bufferViews.at(_activeBufferViewIndex);
+ BufferViewDock* dock = _bufferViews.at(_activeBufferViewIndex);
if (dock->isHidden())
continue;
_activeBufferViewIndex = -1;
}
-
void MainWin::nextBufferView()
{
changeActiveBufferView(false);
}
-
void MainWin::previousBufferView()
{
changeActiveBufferView(true);
}
-
void MainWin::nextBuffer()
{
- BufferView *view = activeBufferView();
+ BufferView* view = activeBufferView();
if (view)
view->nextBuffer();
}
-
void MainWin::previousBuffer()
{
- BufferView *view = activeBufferView();
+ BufferView* view = activeBufferView();
if (view)
view->previousBuffer();
}
-
void MainWin::hideCurrentBuffer()
{
- BufferView *view = activeBufferView();
+ BufferView* view = activeBufferView();
if (view)
view->hideCurrentBuffer();
}
-
void MainWin::showNotificationsDlg()
{
SettingsPageDlg{new NotificationsSettingsPage{}}.exec();
}
-
void MainWin::onConfigureNetworksTriggered()
{
SettingsPageDlg{new NetworksSettingsPage{}}.exec();
}
-
void MainWin::onConfigureViewsTriggered()
{
SettingsPageDlg{new BufferViewSettingsPage{}}.exec();
}
-
void MainWin::onLockLayoutToggled(bool lock)
{
- QList<VerticalDock *> docks = findChildren<VerticalDock *>();
- foreach(VerticalDock *dock, docks) {
+ QList<VerticalDock*> docks = findChildren<VerticalDock*>();
+ foreach (VerticalDock* dock, docks) {
dock->showTitle(!lock);
}
- QList<NickListDock *> nickdocks = findChildren<NickListDock *>();
- foreach(NickListDock *nickdock, nickdocks) {
+ QList<NickListDock*> nickdocks = findChildren<NickListDock*>();
+ foreach (NickListDock* nickdock, nickdocks) {
nickdock->setLocked(lock);
}
- QList<BufferViewDock *> bufferdocks = findChildren<BufferViewDock *>();
- foreach(BufferViewDock *bufferdock, bufferdocks) {
+ QList<BufferViewDock*> bufferdocks = findChildren<BufferViewDock*>();
+ foreach (BufferViewDock* bufferdock, bufferdocks) {
bufferdock->setLocked(lock);
}
if (Client::bufferViewManager()) {
- foreach(ClientBufferViewConfig *config, Client::bufferViewManager()->clientBufferViewConfigs()) {
+ foreach (ClientBufferViewConfig* config, Client::bufferViewManager()->clientBufferViewConfigs()) {
config->setLocked(lock);
}
}
QtUiSettings().setValue("LockLayout", lock);
}
-
void MainWin::setupNickWidget()
{
// create nick dock
- NickListDock *nickDock = new NickListDock(tr("Nicks"), this);
+ NickListDock* nickDock = new NickListDock(tr("Nicks"), this);
nickDock->setObjectName("NickDock");
nickDock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
nickDock->setLocked(QtUiSettings().value("LockLayout", false).toBool());
_nickListWidget->setVisible(false);
}
-
void MainWin::setupChatMonitor()
{
- VerticalDock *dock = new VerticalDock(tr("Chat Monitor"), this);
+ VerticalDock* dock = new VerticalDock(tr("Chat Monitor"), this);
dock->setObjectName("ChatMonitorDock");
- auto *filter = new ChatMonitorFilter(Client::messageModel(), this);
+ auto* filter = new ChatMonitorFilter(Client::messageModel(), this);
_chatMonitorView = new ChatMonitorView(filter, this);
_chatMonitorView->show();
dock->setWidget(_chatMonitorView);
dock->toggleViewAction()->setText(tr("Show Chat Monitor"));
}
-
void MainWin::setupInputWidget()
{
- VerticalDock *dock = new VerticalDock(tr("Inputline"), this);
+ VerticalDock* dock = new VerticalDock(tr("Inputline"), this);
dock->setObjectName("InputDock");
_inputWidget = new InputWidget(dock);
_inputWidget->inputLine()->installEventFilter(_bufferWidget);
}
-
void MainWin::setupTopicWidget()
{
- VerticalDock *dock = new VerticalDock(tr("Topic"), this);
+ VerticalDock* dock = new VerticalDock(tr("Topic"), this);
dock->setObjectName("TopicDock");
_topicWidget = new TopicWidget(dock);
dock->toggleViewAction()->setText(tr("Show Topic Line"));
}
-
void MainWin::setupTransferWidget()
{
auto dock = new QDockWidget(tr("Transfers"), this);
dock->setObjectName("TransferDock");
- dock->setAllowedAreas(Qt::TopDockWidgetArea|Qt::BottomDockWidgetArea);
+ dock->setAllowedAreas(Qt::TopDockWidgetArea | Qt::BottomDockWidgetArea);
- auto view = new QTableView(dock); // to be replaced by the real thing
+ auto view = new QTableView(dock); // to be replaced by the real thing
view->setModel(Client::transferModel());
dock->setWidget(view);
- dock->hide(); // hidden by default
+ dock->hide(); // hidden by default
addDockWidget(Qt::TopDockWidgetArea, dock, Qt::Vertical);
auto action = dock->toggleViewAction();
_viewMenu->addAction(action);
}
-
void MainWin::setupViewMenuTail()
{
_viewMenu->addSeparator();
_viewMenu->addAction(_fullScreenAction);
}
-
void MainWin::setupTitleSetter()
{
_titleSetter.setModel(Client::bufferModel());
_titleSetter.setSelectionModel(Client::bufferModel()->standardSelectionModel());
}
-
void MainWin::setupStatusBar()
{
// MessageProcessor progress
_coreConnectionStatusWidget->update();
statusBar()->addPermanentWidget(_coreConnectionStatusWidget);
- QAction *showStatusbar = QtUi::actionCollection("General")->action("ToggleStatusBar");
+ QAction* showStatusbar = QtUi::actionCollection("General")->action("ToggleStatusBar");
QtUiSettings uiSettings;
connect(showStatusbar, &QAction::toggled, statusBar(), &QWidget::setVisible);
connect(showStatusbar, &QAction::toggled, this, &MainWin::saveStatusBarStatus);
- connect(Client::coreConnection(), &CoreConnection::connectionMsg, statusBar(), [statusBar = statusBar()](auto &&message) {
+ connect(Client::coreConnection(), &CoreConnection::connectionMsg, statusBar(), [statusBar = statusBar()](auto&& message) {
statusBar->showMessage(message);
});
}
-
void MainWin::setupHotList()
{
- auto *flatProxy = new FlatProxyModel(this);
+ auto* flatProxy = new FlatProxyModel(this);
flatProxy->setSourceModel(Client::bufferModel());
_bufferHotList = new BufferHotListFilter(flatProxy);
}
-
void MainWin::saveMenuBarStatus(bool enabled)
{
QtUiSettings uiSettings;
uiSettings.setValue("ShowMenuBar", enabled);
}
-
void MainWin::saveStatusBarStatus(bool enabled)
{
QtUiSettings uiSettings;
uiSettings.setValue("ShowStatusBar", enabled);
}
-
void MainWin::setupSystray()
{
#ifdef HAVE_DBUS
#elif !defined QT_NO_SYSTEMTRAYICON
_systemTray = new LegacySystemTray(this);
#else
- _systemTray = new SystemTray(this); // dummy
+ _systemTray = new SystemTray(this); // dummy
#endif
}
-
void MainWin::setupToolBars()
{
- connect(_bufferWidget, selectOverload<const QModelIndex&>(&AbstractBufferContainer::currentChanged),
- QtUi::toolBarActionProvider(), &ToolBarActionProvider::onCurrentBufferChanged);
- connect(_nickListWidget, &NickListWidget::nickSelectionChanged,
- QtUi::toolBarActionProvider(), &ToolBarActionProvider::onNickSelectionChanged);
+ connect(_bufferWidget,
+ selectOverload<const QModelIndex&>(&AbstractBufferContainer::currentChanged),
+ QtUi::toolBarActionProvider(),
+ &ToolBarActionProvider::onCurrentBufferChanged);
+ connect(_nickListWidget,
+ &NickListWidget::nickSelectionChanged,
+ QtUi::toolBarActionProvider(),
+ &ToolBarActionProvider::onNickSelectionChanged);
#ifdef Q_OS_MAC
setUnifiedTitleAndToolBarOnMac(true);
addToolBar(_mainToolBar);
if (Quassel::runMode() != Quassel::Monolithic) {
- ActionCollection *coll = QtUi::actionCollection("General");
+ ActionCollection* coll = QtUi::actionCollection("General");
_mainToolBar->addAction(coll->action("ConnectCore"));
_mainToolBar->addAction(coll->action("DisconnectCore"));
}
_nickToolBar->setObjectName("NickToolBar");
#endif
_nickToolBar->setWindowTitle(tr("Nick Toolbar"));
- _nickToolBar->setVisible(false); //default: not visible
+ _nickToolBar->setVisible(false); // default: not visible
addToolBar(_nickToolBar);
_nickToolBar->setMovable(!QtUiSettings().value("LockLayout", false).toBool());
#endif
}
-
void MainWin::doAutoConnect()
{
if (!Client::coreConnection()->connectToCore()) {
}
}
-
void MainWin::connectedToCore()
{
Q_CHECK_PTR(Client::bufferViewManager());
setConnectedState();
}
-
void MainWin::setConnectedState()
{
- ActionCollection *coll = QtUi::actionCollection("General");
+ ActionCollection* coll = QtUi::actionCollection("General");
coll->action("ConnectCore")->setEnabled(false);
coll->action("DisconnectCore")->setEnabled(true);
coll->action("ChangePassword")->setEnabled(true);
coll->action("CoreInfo")->setEnabled(true);
- foreach(QAction *action, _fileMenu->actions()) {
+ foreach (QAction* action, _fileMenu->actions()) {
if (isRemoteCoreOnly(action))
action->setVisible(!Client::internalCore());
}
- disconnect(Client::backlogManager(), &ClientBacklogManager::updateProgress, _msgProcessorStatusWidget, &MsgProcessorStatusWidget::setProgress);
+ disconnect(Client::backlogManager(),
+ &ClientBacklogManager::updateProgress,
+ _msgProcessorStatusWidget,
+ &MsgProcessorStatusWidget::setProgress);
disconnect(Client::backlogManager(), &ClientBacklogManager::messagesRequested, this, &MainWin::showStatusBarMessage);
disconnect(Client::backlogManager(), &ClientBacklogManager::messagesProcessed, this, &MainWin::showStatusBarMessage);
if (!Client::internalCore()) {
- connect(Client::backlogManager(), &ClientBacklogManager::updateProgress, _msgProcessorStatusWidget, &MsgProcessorStatusWidget::setProgress);
+ connect(Client::backlogManager(),
+ &ClientBacklogManager::updateProgress,
+ _msgProcessorStatusWidget,
+ &MsgProcessorStatusWidget::setProgress);
connect(Client::backlogManager(), &ClientBacklogManager::messagesRequested, this, &MainWin::showStatusBarMessage);
connect(Client::backlogManager(), &ClientBacklogManager::messagesProcessed, this, &MainWin::showStatusBarMessage);
}
systemTray()->setState(SystemTray::Active);
if (Client::networkIds().isEmpty()) {
- IrcConnectionWizard *wizard = new IrcConnectionWizard(this, Qt::Sheet);
+ IrcConnectionWizard* wizard = new IrcConnectionWizard(this, Qt::Sheet);
wizard->show();
}
else {
}
}
-
void MainWin::loadLayout()
{
QtUiSettings s;
int accountId = Client::currentCoreAccount().accountId().toInt();
QByteArray state = s.value(QString("MainWinState-%1").arg(accountId)).toByteArray();
if (state.isEmpty()) {
- foreach(BufferViewDock *view, _bufferViews)
- view->show();
+ foreach (BufferViewDock* view, _bufferViews)
+ view->show();
_layoutLoaded = true;
return;
}
_layoutLoaded = true;
}
-
void MainWin::saveLayout()
{
QtUiSettings s;
- int accountId = _bufferViews.count() ? Client::currentCoreAccount().accountId().toInt() : 0; // only save if we still have a layout!
+ int accountId = _bufferViews.count() ? Client::currentCoreAccount().accountId().toInt() : 0; // only save if we still have a layout!
if (accountId > 0) {
s.setValue(QString("MainWinState-%1").arg(accountId), saveState(accountId));
- BufferView *view = activeBufferView();
+ BufferView* view = activeBufferView();
s.setValue(QString("ActiveBufferView-%1").arg(accountId), view ? view->config()->bufferViewId() : -1);
}
}
-
void MainWin::disconnectedFromCore()
{
// save core specific layout and remove bufferviews;
_layoutLoaded = false;
QVariant actionData;
- BufferViewDock *dock;
- foreach(QAction *action, _bufferViewsMenu->actions()) {
+ BufferViewDock* dock;
+ foreach (QAction* action, _bufferViewsMenu->actions()) {
actionData = action->data();
if (!actionData.isValid())
continue;
- dock = qobject_cast<BufferViewDock *>(action->parent());
+ dock = qobject_cast<BufferViewDock*>(action->parent());
if (dock && actionData.toInt() != -1) {
removeAction(action);
_bufferViews.removeAll(dock);
setDisconnectedState();
}
-
void MainWin::setDisconnectedState()
{
- ActionCollection *coll = QtUi::actionCollection("General");
- //ui.menuCore->setEnabled(false);
+ ActionCollection* coll = QtUi::actionCollection("General");
+ // ui.menuCore->setEnabled(false);
coll->action("ConnectCore")->setEnabled(true);
coll->action("DisconnectCore")->setEnabled(false);
coll->action("CoreInfo")->setEnabled(false);
_nickListWidget->setVisible(false);
}
-
-void MainWin::userAuthenticationRequired(CoreAccount *account, bool *valid, const QString &errorMessage)
+void MainWin::userAuthenticationRequired(CoreAccount* account, bool* valid, const QString& errorMessage)
{
Q_UNUSED(errorMessage)
CoreConnectAuthDlg dlg(account);
*valid = (dlg.exec() == QDialog::Accepted);
}
-
-void MainWin::handleNoSslInClient(bool *accepted)
+void MainWin::handleNoSslInClient(bool* accepted)
{
- QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your client does not support SSL encryption</b>"),
- QMessageBox::Ignore|QMessageBox::Cancel);
+ QMessageBox box(QMessageBox::Warning,
+ tr("Unencrypted Connection"),
+ tr("<b>Your client does not support SSL encryption</b>"),
+ QMessageBox::Ignore | QMessageBox::Cancel);
box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
box.setDefaultButton(QMessageBox::Ignore);
- *accepted = box.exec() == QMessageBox::Ignore;
+ *accepted = (box.exec() == QMessageBox::Ignore);
}
-
-void MainWin::handleNoSslInCore(bool *accepted)
+void MainWin::handleNoSslInCore(bool* accepted)
{
- QMessageBox box(QMessageBox::Warning, tr("Unencrypted Connection"), tr("<b>Your core does not support SSL encryption</b>"),
- QMessageBox::Ignore|QMessageBox::Cancel);
+ QMessageBox box(QMessageBox::Warning,
+ tr("Unencrypted Connection"),
+ tr("<b>Your core does not support SSL encryption</b>"),
+ QMessageBox::Ignore | QMessageBox::Cancel);
box.setInformativeText(tr("Sensitive data, like passwords, will be transmitted unencrypted to your Quassel core."));
box.setDefaultButton(QMessageBox::Ignore);
- *accepted = box.exec() == QMessageBox::Ignore;
+ *accepted = (box.exec() == QMessageBox::Ignore);
}
-
#ifdef HAVE_SSL
-void MainWin::handleSslErrors(const QSslSocket *socket, bool *accepted, bool *permanently)
+void MainWin::handleSslErrors(const QSslSocket* socket, bool* accepted, bool* permanently)
{
QString errorString = "<ul>";
- foreach(const QSslError error, socket->sslErrors())
- errorString += QString("<li>%1</li>").arg(error.errorString());
+ foreach (const QSslError error, socket->sslErrors())
+ errorString += QString("<li>%1</li>").arg(error.errorString());
errorString += "</ul>";
QMessageBox box(QMessageBox::Warning,
- tr("Untrusted Security Certificate"),
- tr("<b>The SSL certificate provided by the core at %1 is untrusted for the following reasons:</b>").arg(socket->peerName()),
- QMessageBox::Cancel);
+ tr("Untrusted Security Certificate"),
+ tr("<b>The SSL certificate provided by the core at %1 is untrusted for the following reasons:</b>").arg(socket->peerName()),
+ QMessageBox::Cancel);
box.setInformativeText(errorString);
box.addButton(tr("Continue"), QMessageBox::AcceptRole);
box.setDefaultButton(box.addButton(tr("Show Certificate"), QMessageBox::HelpRole));
SslInfoDlg dlg(socket);
dlg.exec();
}
- }
- while (role == QMessageBox::HelpRole);
+ } while (role == QMessageBox::HelpRole);
*accepted = role == QMessageBox::AcceptRole;
if (*accepted) {
QMessageBox box2(QMessageBox::Warning,
- tr("Untrusted Security Certificate"),
- tr("Would you like to accept this certificate forever without being prompted?"),
- 0);
+ tr("Untrusted Security Certificate"),
+ tr("Would you like to accept this certificate forever without being prompted?"),
+ QMessageBox::NoButton);
box2.setDefaultButton(box2.addButton(tr("Current Session Only"), QMessageBox::NoRole));
box2.addButton(tr("Forever"), QMessageBox::YesRole);
box2.exec();
- *permanently = box2.buttonRole(box2.clickedButton()) == QMessageBox::YesRole;
+ *permanently = (box2.buttonRole(box2.clickedButton()) == QMessageBox::YesRole);
}
}
-
#endif /* HAVE_SSL */
-void MainWin::handleCoreConnectionError(const QString &error)
+void MainWin::handleCoreConnectionError(const QString& error)
{
QMessageBox::critical(this, tr("Core Connection Error"), error, QMessageBox::Ok);
}
-
void MainWin::showCoreConnectionDlg()
{
CoreConnectDlg dlg;
}
}
-
-void MainWin::showCoreConfigWizard(const QVariantList &backends, const QVariantList &authenticators)
+void MainWin::showCoreConfigWizard(const QVariantList& backends, const QVariantList& authenticators)
{
- auto *wizard = new CoreConfigWizard(Client::coreConnection(), backends, authenticators, this);
+ auto* wizard = new CoreConfigWizard(Client::coreConnection(), backends, authenticators, this);
wizard->show();
}
-
-void MainWin::showChannelList(NetworkId netId, const QString &channelFilters, bool listImmediately)
+void MainWin::showChannelList(NetworkId netId, const QString& channelFilters, bool listImmediately)
{
if (!netId.isValid()) {
- auto *action = qobject_cast<QAction *>(sender());
+ auto* action = qobject_cast<QAction*>(sender());
if (action)
netId = action->data().value<NetworkId>();
if (!netId.isValid()) {
// We still haven't found a valid network, probably no network selected, e.g. "/list"
// on the client homescreen when no networks are connected.
- QMessageBox box(QMessageBox::Information, tr("No network selected"),
+ QMessageBox box(QMessageBox::Information,
+ tr("No network selected"),
QString("<b>%1</b>").arg(tr("No network selected")),
QMessageBox::Ok);
box.setInformativeText(tr("Select a network before trying to view the channel list."));
}
}
- auto *channelListDlg = new ChannelListDlg(this);
+ auto* channelListDlg = new ChannelListDlg(this);
channelListDlg->setAttribute(Qt::WA_DeleteOnClose);
channelListDlg->setNetwork(netId);
if (!channelFilters.isEmpty()) {
channelListDlg->show();
}
-
void MainWin::showNetworkConfig(NetworkId netId)
{
SettingsPageDlg dlg{new NetworksSettingsPage{}};
if (netId.isValid())
- qobject_cast<NetworksSettingsPage *>(dlg.currentPage())->bufferList_Open(netId);
+ qobject_cast<NetworksSettingsPage*>(dlg.currentPage())->bufferList_Open(netId);
dlg.exec();
}
-
void MainWin::showIgnoreList(QString newRule)
{
SettingsPageDlg dlg{new IgnoreListSettingsPage{}};
// prepare config dialog for new rule
if (!newRule.isEmpty())
- qobject_cast<IgnoreListSettingsPage *>(dlg.currentPage())->editIgnoreRule(newRule);
+ qobject_cast<IgnoreListSettingsPage*>(dlg.currentPage())->editIgnoreRule(newRule);
dlg.exec();
}
-
void MainWin::showCoreInfoDlg()
{
CoreInfoDlg{}.exec();
}
-
void MainWin::showAwayLog()
{
if (_awayLog)
return;
- auto *filter = new AwayLogFilter(Client::messageModel());
+ auto* filter = new AwayLogFilter(Client::messageModel());
_awayLog = new AwayLogView(filter, nullptr);
filter->setParent(_awayLog);
connect(_awayLog, &QObject::destroyed, this, &MainWin::awayLogDestroyed);
_awayLog->show();
}
-
void MainWin::awayLogDestroyed()
{
_awayLog = nullptr;
}
-
void MainWin::showSettingsDlg()
{
- auto *dlg = new SettingsDlg();
+ auto dlg = new SettingsDlg();
- //Category: Interface
+ // Category: Interface
dlg->registerSettingsPage(new AppearanceSettingsPage(dlg));
dlg->registerSettingsPage(new ChatViewSettingsPage(dlg));
dlg->registerSettingsPage(new ChatViewColorSettingsPage(dlg));
dlg->registerSettingsPage(new NotificationsSettingsPage(dlg));
dlg->registerSettingsPage(new BacklogSettingsPage(dlg));
- //Category: IRC
+ // Category: IRC
dlg->registerSettingsPage(new ConnectionSettingsPage(dlg));
dlg->registerSettingsPage(new IdentitiesSettingsPage(dlg));
dlg->registerSettingsPage(new NetworksSettingsPage(dlg));
dlg->show();
}
-
void MainWin::showAboutDlg()
{
AboutDlg{}.exec();
}
-
void MainWin::showShortcutsDlg()
{
#ifdef HAVE_KDE
KShortcutsDialog dlg(KShortcutsEditor::AllActions, KShortcutsEditor::LetterShortcutsDisallowed);
- foreach(KActionCollection *coll, QtUi::actionCollections())
- dlg.addCollection(coll, coll->property("Category").toString());
+ foreach (KActionCollection* coll, QtUi::actionCollections()) {
+ dlg.addCollection(coll, coll->property("Category").toString());
+ }
dlg.configure(true);
#else
SettingsPageDlg{new ShortcutsSettingsPage{QtUi::actionCollections()}}.exec();
#endif
}
-
-void MainWin::showNewTransferDlg(const QUuid &transferId)
+void MainWin::showNewTransferDlg(const QUuid& transferId)
{
auto transfer = Client::transferManager()->transfer(transferId);
if (transfer) {
if (transfer->status() == Transfer::Status::New) {
- auto *dlg = new ReceiveFileDlg(transfer, this);
+ auto* dlg = new ReceiveFileDlg(transfer, this);
dlg->show();
}
}
}
}
-
void MainWin::onFullScreenToggled()
{
// Relying on QWidget::isFullScreen is discouraged, see the KToggleFullScreenAction docs
#endif
}
-
/********************************************************************************************************/
-bool MainWin::event(QEvent *event)
+bool MainWin::event(QEvent* event)
{
- switch(event->type()) {
+ switch (event->type()) {
case QEvent::WindowActivate: {
BufferId bufferId = Client::bufferModel()->currentBuffer();
if (bufferId.isValid())
return QMainWindow::event(event);
}
-
-void MainWin::moveEvent(QMoveEvent *event)
+void MainWin::moveEvent(QMoveEvent* event)
{
if (!(windowState() & Qt::WindowMaximized))
_normalPos = event->pos();
QMainWindow::moveEvent(event);
}
-
-void MainWin::resizeEvent(QResizeEvent *event)
+void MainWin::resizeEvent(QResizeEvent* event)
{
if (!(windowState() & Qt::WindowMaximized))
_normalSize = event->size();
QMainWindow::resizeEvent(event);
}
-
-void MainWin::closeEvent(QCloseEvent *event)
+void MainWin::closeEvent(QCloseEvent* event)
{
QtUiSettings s;
- auto *app = qobject_cast<QtUiApplication *> qApp;
+ auto* app = qobject_cast<QtUiApplication*> qApp;
Q_ASSERT(app);
// On OSX it can happen that the closeEvent occurs twice. (Especially if packaged with Frameworks)
// This messes up MainWinState/MainWinHidden save/restore.
QtUi::hideMainWidget();
event->ignore();
}
- else if(!_aboutToQuit) {
+ else if (!_aboutToQuit) {
_aboutToQuit = true;
event->accept();
Quassel::instance()->quit();
}
}
-
-void MainWin::messagesInserted(const QModelIndex &parent, int start, int end)
+void MainWin::messagesInserted(const QModelIndex& parent, int start, int end)
{
Q_UNUSED(parent);
BufferInfo::Type bufType = Client::networkModel()->bufferType(bufId);
// check if bufferId belongs to the shown chatlists
- if (!(Client::bufferViewOverlay()->bufferIds().contains(bufId) ||
- Client::bufferViewOverlay()->tempRemovedBufferIds().contains(bufId)))
+ if (!(Client::bufferViewOverlay()->bufferIds().contains(bufId) || Client::bufferViewOverlay()->tempRemovedBufferIds().contains(bufId)))
continue;
// check if it's the buffer currently displayed
continue;
// and of course: don't notify for ignored messages
- if (Client::ignoreListManager() && Client::ignoreListManager()->match(idx.data(MessageModel::MessageRole).value<Message>(), Client::networkModel()->networkName(bufId)))
+ if (Client::ignoreListManager()
+ && Client::ignoreListManager()->match(idx.data(MessageModel::MessageRole).value<Message>(),
+ Client::networkModel()->networkName(bufId)))
continue;
// seems like we have a legit notification candidate!
}
}
-
void MainWin::currentBufferChanged(BufferId buffer)
{
if (buffer.isValid())
Client::instance()->markBufferAsRead(buffer);
}
-
void MainWin::clientNetworkCreated(NetworkId id)
{
- const Network *net = Client::network(id);
- auto *act = new QAction(net->networkName(), this);
+ const Network* net = Client::network(id);
+ auto* act = new QAction(net->networkName(), this);
act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
act->setData(QVariant::fromValue<NetworkId>(id));
connect(net, &SyncableObject::updatedRemotely, this, &MainWin::clientNetworkUpdated);
connect(act, &QAction::triggered, this, &MainWin::connectOrDisconnectFromNet);
- QAction *beforeAction = nullptr;
- foreach(QAction *action, _networksMenu->actions()) {
- if (!action->data().isValid()) // ignore stock actions
+ QAction* beforeAction = nullptr;
+ foreach (QAction* action, _networksMenu->actions()) {
+ if (!action->data().isValid()) // ignore stock actions
continue;
if (net->networkName().localeAwareCompare(action->text()) < 0) {
beforeAction = action;
_networksMenu->insertAction(beforeAction, act);
}
-
void MainWin::clientNetworkUpdated()
{
- const auto *net = qobject_cast<const Network *>(sender());
+ const auto* net = qobject_cast<const Network*>(sender());
if (!net)
return;
- auto *action = findChild<QAction *>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
+ auto* action = findChild<QAction*>(QString("NetworkAction-%1").arg(net->networkId().toInt()));
if (!action)
return;
}
}
-
void MainWin::clientNetworkRemoved(NetworkId id)
{
- auto *action = findChild<QAction *>(QString("NetworkAction-%1").arg(id.toInt()));
+ auto* action = findChild<QAction*>(QString("NetworkAction-%1").arg(id.toInt()));
if (!action)
return;
action->deleteLater();
}
-
void MainWin::connectOrDisconnectFromNet()
{
- auto *act = qobject_cast<QAction *>(sender());
- if (!act) return;
- const Network *net = Client::network(act->data().value<NetworkId>());
- if (!net) return;
- if (net->connectionState() == Network::Disconnected) net->requestConnect();
- else net->requestDisconnect();
+ auto* act = qobject_cast<QAction*>(sender());
+ if (!act)
+ return;
+ const Network* net = Client::network(act->data().value<NetworkId>());
+ if (!net)
+ return;
+ if (net->connectionState() == Network::Disconnected)
+ net->requestConnect();
+ else
+ net->requestDisconnect();
}
-
void MainWin::onFormatApplyColorTriggered()
{
if (!_inputWidget)
_inputWidget->applyFormatActiveColor();
}
-
void MainWin::onFormatApplyColorFillTriggered()
{
if (!_inputWidget)
_inputWidget->applyFormatActiveColorFill();
}
-
void MainWin::onFormatClearTriggered()
{
if (!_inputWidget)
_inputWidget->clearFormat();
}
-
void MainWin::onFormatBoldTriggered()
{
if (!_inputWidget)
_inputWidget->toggleFormatBold();
}
-
void MainWin::onFormatItalicTriggered()
{
if (!_inputWidget)
_inputWidget->toggleFormatItalic();
}
-
void MainWin::onFormatUnderlineTriggered()
{
if (!_inputWidget)
_inputWidget->toggleFormatUnderline();
}
-
void MainWin::onJumpHotBufferTriggered()
{
if (!_bufferHotList->rowCount())
_bufferViews[_activeBufferViewIndex]->activateFilter();
}
-
void MainWin::onJumpKey()
{
- auto *action = qobject_cast<QAction *>(sender());
+ auto* action = qobject_cast<QAction*>(sender());
if (!action || !Client::bufferModel())
return;
int idx = action->property("Index").toInt();
Client::bufferModel()->switchToBuffer(buffer);
}
-
void MainWin::bindJumpKey()
{
- auto *action = qobject_cast<QAction *>(sender());
+ auto* action = qobject_cast<QAction*>(sender());
if (!action || !Client::bufferModel())
return;
int idx = action->property("Index").toInt();
CoreAccountSettings().setJumpKeyMap(_jumpKeyMap);
}
-
void MainWin::onDebugNetworkModelTriggered()
{
- auto *view = new QTreeView;
+ auto* view = new QTreeView;
view->setAttribute(Qt::WA_DeleteOnClose);
view->setWindowTitle("Debug NetworkModel View");
view->setModel(Client::networkModel());
view->show();
}
-
void MainWin::onDebugHotListTriggered()
{
_bufferHotList->invalidate();
_bufferHotList->sort(0, Qt::DescendingOrder);
- auto *view = new QTreeView;
+ auto* view = new QTreeView;
view->setAttribute(Qt::WA_DeleteOnClose);
view->setModel(_bufferHotList);
view->show();
}
-
void MainWin::onDebugBufferViewOverlayTriggered()
{
- auto *overlay = new DebugBufferViewOverlay(nullptr);
+ auto* overlay = new DebugBufferViewOverlay(nullptr);
overlay->setAttribute(Qt::WA_DeleteOnClose);
overlay->show();
}
-
void MainWin::onDebugMessageModelTriggered()
{
- auto *view = new QTableView(nullptr);
- auto *filter = new DebugMessageModelFilter(view);
+ auto* view = new QTableView(nullptr);
+ auto* filter = new DebugMessageModelFilter(view);
filter->setSourceModel(Client::messageModel());
view->setModel(filter);
view->setAttribute(Qt::WA_DeleteOnClose, true);
view->show();
}
-
void MainWin::onDebugLogTriggered()
{
auto dlg = new DebugLogDlg(this); // will be deleted on close
dlg->show();
}
-void MainWin::showStatusBarMessage(const QString &message)
+void MainWin::showStatusBarMessage(const QString& message)
{
statusBar()->showMessage(message, 10000);
}
#include <QUuid>
#ifdef HAVE_KF5
-# include <KXmlGui/KMainWindow>
+# include <KXmlGui/KMainWindow>
#else
-# include <QMainWindow>
+# include <QMainWindow>
#endif
#include "qtui.h"
//!\brief The main window of Quassel's QtUi.
class MainWin
#ifdef HAVE_KDE
- : public KMainWindow {
+ : public KMainWindow
+{
#else
- : public QMainWindow {
+ : public QMainWindow
+{
#endif
Q_OBJECT
public:
- MainWin(QWidget *parent = nullptr);
+ MainWin(QWidget* parent = nullptr);
void init();
- void addBufferView(ClientBufferViewConfig *config);
- BufferView *allBuffersView() const;
- BufferView *activeBufferView() const;
+ void addBufferView(ClientBufferViewConfig* config);
+ BufferView* allBuffersView() const;
+ BufferView* activeBufferView() const;
- inline BufferWidget *bufferWidget() const { return _bufferWidget; }
- inline SystemTray *systemTray() const { return _systemTray; }
+ inline BufferWidget* bufferWidget() const { return _bufferWidget; }
+ inline SystemTray* systemTray() const { return _systemTray; }
- bool event(QEvent *event) override;
+ bool event(QEvent* event) override;
- static void flagRemoteCoreOnly(QObject *object) { object->setProperty("REMOTE_CORE_ONLY", true); }
- static bool isRemoteCoreOnly(QObject *object) { return object->property("REMOTE_CORE_ONLY").toBool(); }
+ static void flagRemoteCoreOnly(QObject* object) { object->setProperty("REMOTE_CORE_ONLY", true); }
+ static bool isRemoteCoreOnly(QObject* object) { return object->property("REMOTE_CORE_ONLY").toBool(); }
- void saveStateToSettings(UiSettings &);
- void restoreStateFromSettings(UiSettings &);
+ void saveStateToSettings(UiSettings&);
+ void restoreStateFromSettings(UiSettings&);
// We need to override this to add the show/hide menu bar option
- QMenu *createPopupMenu() override;
+ QMenu* createPopupMenu() override;
public slots:
- void showStatusBarMessage(const QString &message);
+ void showStatusBarMessage(const QString& message);
void hideCurrentBuffer();
- void nextBufferView(); //!< Activate the next bufferview
- void previousBufferView(); //!< Activate the previous bufferview
+ void nextBufferView(); //!< Activate the next bufferview
+ void previousBufferView(); //!< Activate the previous bufferview
void nextBuffer();
void previousBuffer();
void showMigrationWarning(bool show);
- void onExitRequested(const QString &reason);
+ void onExitRequested(const QString& reason);
protected:
- void closeEvent(QCloseEvent *event) override;
- void moveEvent(QMoveEvent *event) override;
- void resizeEvent(QResizeEvent *event) override;
+ void closeEvent(QCloseEvent* event) override;
+ void moveEvent(QMoveEvent* event) override;
+ void resizeEvent(QResizeEvent* event) override;
protected slots:
void connectedToCore();
void awayLogDestroyed();
void removeBufferView(int bufferViewConfigId);
void currentBufferChanged(BufferId);
- void messagesInserted(const QModelIndex &parent, int start, int end);
+ void messagesInserted(const QModelIndex& parent, int start, int end);
void showAboutDlg();
/**
* @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 netId = {}, const QString &channelFilters = {},
- bool listImmediately = false);
+ void showChannelList(NetworkId netId = {}, const QString& channelFilters = {}, bool listImmediately = false);
void showNetworkConfig(NetworkId netId = NetworkId());
void showCoreConnectionDlg();
- void showCoreConfigWizard(const QVariantList &, const QVariantList &);
+ void showCoreConfigWizard(const QVariantList&, const QVariantList&);
void showCoreInfoDlg();
void showAwayLog();
void showSettingsDlg();
void showIgnoreList(QString newRule = QString());
void showShortcutsDlg();
void showPasswordChangeDlg();
- void showNewTransferDlg(const QUuid &transferId);
+ void showNewTransferDlg(const QUuid& transferId);
void onFullScreenToggled();
void doAutoConnect();
- void handleCoreConnectionError(const QString &errorMsg);
- void userAuthenticationRequired(CoreAccount *, bool *valid, const QString &errorMessage);
- void handleNoSslInClient(bool *accepted);
- void handleNoSslInCore(bool *accepted);
+ void handleCoreConnectionError(const QString& errorMsg);
+ void userAuthenticationRequired(CoreAccount*, bool* valid, const QString& errorMessage);
+ 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 onConfigureNetworksTriggered();
void changeActiveBufferView(int bufferViewId);
signals:
- void connectToCore(const QVariantMap &connInfo);
+ void connectToCore(const QVariantMap& connInfo);
void disconnectFromCore();
private:
#ifdef HAVE_KDE
- KHelpMenu *_kHelpMenu;
+ KHelpMenu* _kHelpMenu;
#endif
- MsgProcessorStatusWidget *_msgProcessorStatusWidget;
- CoreConnectionStatusWidget *_coreConnectionStatusWidget;
- SystemTray *_systemTray;
+ MsgProcessorStatusWidget* _msgProcessorStatusWidget;
+ CoreConnectionStatusWidget* _coreConnectionStatusWidget;
+ SystemTray* _systemTray;
TitleSetter _titleSetter;
void updateIcon();
void enableMenus();
- QList<BufferViewDock *> _bufferViews;
- BufferWidget *_bufferWidget;
- NickListWidget *_nickListWidget;
- InputWidget *_inputWidget;
- ChatMonitorView *_chatMonitorView;
- TopicWidget *_topicWidget;
+ QList<BufferViewDock*> _bufferViews;
+ BufferWidget* _bufferWidget;
+ NickListWidget* _nickListWidget;
+ InputWidget* _inputWidget;
+ ChatMonitorView* _chatMonitorView;
+ TopicWidget* _topicWidget;
- QAction *_fullScreenAction{nullptr};
+ QAction* _fullScreenAction{nullptr};
QMenu *_fileMenu, *_networksMenu, *_viewMenu, *_bufferViewsMenu, *_settingsMenu, *_helpMenu, *_helpDebugMenu;
- QMenu *_toolbarMenu;
+ QMenu* _toolbarMenu;
QToolBar *_mainToolBar, *_chatViewToolBar, *_nickToolBar;
- QWidget *_awayLog{nullptr};
+ QWidget* _awayLog{nullptr};
QMessageBox* _migrationWarning{nullptr};
bool _layoutLoaded{false};
- QSize _normalSize; //!< Size of the non-maximized window
- QPoint _normalPos; //!< Position of the non-maximized window
+ QSize _normalSize; //!< Size of the non-maximized window
+ QPoint _normalPos; //!< Position of the non-maximized window
- BufferHotListFilter *_bufferHotList;
+ BufferHotListFilter* _bufferHotList;
QHash<int, BufferId> _jumpKeyMap;
int _activeBufferViewIndex{-1};
- bool _aboutToQuit{false}; //closeEvent can occur multiple times on OSX
+ bool _aboutToQuit{false}; // closeEvent can occur multiple times on OSX
friend class QtUi;
};
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "markerlineitem.h"
+
#include <QPainter>
-#include "markerlineitem.h"
#include "qtui.h"
-MarkerLineItem::MarkerLineItem(qreal sceneWidth, QGraphicsItem *parent)
- : QGraphicsObject(parent),
- _boundingRect(0, 0, sceneWidth, 1),
- _chatLine(nullptr)
+MarkerLineItem::MarkerLineItem(qreal sceneWidth, QGraphicsItem* parent)
+ : QGraphicsObject(parent)
+ , _boundingRect(0, 0, sceneWidth, 1)
+ , _chatLine(nullptr)
{
setVisible(false);
setZValue(8);
- styleChanged(); // init brush and height
+ styleChanged(); // init brush and height
connect(QtUi::style(), &UiStyle::changed, this, &MarkerLineItem::styleChanged);
}
-
-void MarkerLineItem::setChatLine(ChatLine *line)
+void MarkerLineItem::setChatLine(ChatLine* line)
{
_chatLine = line;
if (!line)
setVisible(false);
}
-
void MarkerLineItem::styleChanged()
{
_brush = QtUi::style()->brush(UiStyle::ColorRole::MarkerLine);
_boundingRect = QRectF(0, 0, scene() ? scene()->width() : 100, height);
}
-
-void MarkerLineItem::sceneRectChanged(const QRectF &rect)
+void MarkerLineItem::sceneRectChanged(const QRectF& rect)
{
prepareGeometryChange();
_boundingRect.setWidth(rect.width());
}
-
-void MarkerLineItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
+void MarkerLineItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
Q_OBJECT
public:
- MarkerLineItem(qreal sceneWidth, QGraphicsItem *parent = nullptr);
+ MarkerLineItem(qreal sceneWidth, QGraphicsItem* parent = nullptr);
inline int type() const override { return ChatScene::MarkerLineType; }
inline QRectF boundingRect() const override { return _boundingRect; }
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override;
+ void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override;
- inline ChatLine *chatLine() const { return _chatLine; }
+ inline ChatLine* chatLine() const { return _chatLine; }
public slots:
//! Set the ChatLine this MarkerLineItem is associated to
- void setChatLine(ChatLine *line);
- void sceneRectChanged(const QRectF &);
+ void setChatLine(ChatLine* line);
+ void sceneRectChanged(const QRectF&);
private slots:
void styleChanged();
private:
QRectF _boundingRect;
QBrush _brush;
- ChatLine *_chatLine;
+ ChatLine* _chatLine;
};
-
#endif
#include "msgprocessorstatuswidget.h"
-MsgProcessorStatusWidget::MsgProcessorStatusWidget(QWidget *parent)
+MsgProcessorStatusWidget::MsgProcessorStatusWidget(QWidget* parent)
: QWidget(parent)
{
ui.setupUi(this);
hide();
}
-
void MsgProcessorStatusWidget::setProgress(int value, int max)
{
if (max <= 0 || value == max) {
Q_OBJECT
public:
- MsgProcessorStatusWidget(QWidget *parent = nullptr);
+ MsgProcessorStatusWidget(QWidget* parent = nullptr);
public slots:
void setProgress(int value, int max);
Ui::MsgProcessorStatusWidget ui;
};
-
#endif
#include "nicklistwidget.h"
-#include "nickview.h"
+#include <QAbstractButton>
+#include <QAction>
+#include <QDebug>
+#include <QEvent>
+
+#include "buffermodel.h"
#include "client.h"
#include "networkmodel.h"
-#include "buffermodel.h"
+#include "nickview.h"
#include "nickviewfilter.h"
#include "qtuisettings.h"
-#include <QAction>
-#include <QDebug>
-#include <QEvent>
-#include <QAbstractButton>
-
-NickListWidget::NickListWidget(QWidget *parent)
+NickListWidget::NickListWidget(QWidget* parent)
: AbstractItemView(parent)
{
ui.setupUi(this);
}
-
-QDockWidget *NickListWidget::dock() const
+QDockWidget* NickListWidget::dock() const
{
- auto *dock = qobject_cast<QDockWidget *>(parent());
+ auto* dock = qobject_cast<QDockWidget*>(parent());
if (dock)
return dock;
else
return nullptr;
}
-
-void NickListWidget::hideEvent(QHideEvent *event)
+void NickListWidget::hideEvent(QHideEvent* event)
{
emit nickSelectionChanged(QModelIndexList());
AbstractItemView::hideEvent(event);
}
-
-void NickListWidget::showEvent(QShowEvent *event)
+void NickListWidget::showEvent(QShowEvent* event)
{
- auto *view = qobject_cast<NickView *>(ui.stackedWidget->currentWidget());
+ auto* view = qobject_cast<NickView*>(ui.stackedWidget->currentWidget());
if (view)
emit nickSelectionChanged(view->selectedIndexes());
AbstractItemView::showEvent(event);
}
-
void NickListWidget::showWidget(bool visible)
{
if (!selectionModel())
QModelIndex currentIndex = selectionModel()->currentIndex();
if (currentIndex.data(NetworkModel::BufferTypeRole) == BufferInfo::ChannelBuffer) {
- QDockWidget *dock_ = dock();
+ QDockWidget* dock_ = dock();
if (!dock_)
return;
void NickListWidget::setVisible(bool visible)
{
QWidget::setVisible(visible);
- QDockWidget *dock_ = dock();
+ QDockWidget* dock_ = dock();
if (!dock_)
return;
dock_->close();
}
-
-void NickListWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
+void NickListWidget::currentChanged(const QModelIndex& current, const QModelIndex& previous)
{
BufferInfo::Type bufferType = (BufferInfo::Type)current.data(NetworkModel::BufferTypeRole).toInt();
BufferId newBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
}
// See NickListDock::NickListDock() below
-// if(bufferType != BufferInfo::ChannelBuffer) {
-// ui.stackedWidget->setCurrentWidget(ui.emptyPage);
-// QDockWidget *dock_ = dock();
-// if(dock_) {
-// dock_->close();
-// }
-// return;
-// } else {
-// QDockWidget *dock_ = dock();
-// if(dock_ && dock_->toggleViewAction()->isChecked()) {
-// dock_->show();
-// }
-// }
+ // if(bufferType != BufferInfo::ChannelBuffer) {
+ // ui.stackedWidget->setCurrentWidget(ui.emptyPage);
+ // QDockWidget *dock_ = dock();
+ // if(dock_) {
+ // dock_->close();
+ // }
+ // return;
+ // } else {
+ // QDockWidget *dock_ = dock();
+ // if(dock_ && dock_->toggleViewAction()->isChecked()) {
+ // dock_->show();
+ // }
+ // }
if (newBufferId == oldBufferId)
return;
- NickView *view;
+ NickView* view;
if (nickViews.contains(newBufferId)) {
view = nickViews.value(newBufferId);
ui.stackedWidget->setCurrentWidget(view);
}
else {
view = new NickView(this);
- auto *filter = new NickViewFilter(newBufferId, Client::networkModel());
+ auto* filter = new NickViewFilter(newBufferId, Client::networkModel());
view->setModel(filter);
QModelIndex source_current = Client::bufferModel()->mapToSource(current);
view->setRootIndex(filter->mapFromSource(source_current));
emit nickSelectionChanged(view->selectedIndexes());
}
-
void NickListWidget::onNickSelectionChanged()
{
- auto *view = qobject_cast<NickView *>(sender());
+ auto* view = qobject_cast<NickView*>(sender());
Q_ASSERT(view);
if (view != ui.stackedWidget->currentWidget()) {
qDebug() << "Nick selection of hidden view changed!";
emit nickSelectionChanged(view->selectedIndexes());
}
-
-void NickListWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
+void NickListWidget::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
Q_ASSERT(model());
if (!parent.isValid()) {
// ok this means that whole networks are about to be removed
// we can't determine which buffers are affect, so we hope that all nets are removed
// this is the most common case (for example disconnecting from the core or terminating the clint)
- NickView *nickView;
- QHash<BufferId, NickView *>::iterator iter = nickViews.begin();
+ NickView* nickView;
+ QHash<BufferId, NickView*>::iterator iter = nickViews.begin();
while (iter != nickViews.end()) {
nickView = *iter;
iter = nickViews.erase(iter);
ui.stackedWidget->removeWidget(nickView);
- QAbstractItemModel *model = nickView->model();
+ QAbstractItemModel* model = nickView->model();
nickView->setModel(nullptr);
- if (auto *filter = qobject_cast<QSortFilterProxyModel *>(model))
+ if (auto* filter = qobject_cast<QSortFilterProxyModel*>(model))
filter->setSourceModel(nullptr);
model->deleteLater();
nickView->deleteLater();
}
}
-
void NickListWidget::removeBuffer(BufferId bufferId)
{
if (!nickViews.contains(bufferId))
return;
- NickView *view = nickViews.take(bufferId);
+ NickView* view = nickViews.take(bufferId);
ui.stackedWidget->removeWidget(view);
- QAbstractItemModel *model = view->model();
+ QAbstractItemModel* model = view->model();
view->setModel(nullptr);
- if (auto *filter = qobject_cast<QSortFilterProxyModel *>(model))
+ if (auto* filter = qobject_cast<QSortFilterProxyModel*>(model))
filter->setSourceModel(nullptr);
model->deleteLater();
view->deleteLater();
}
-
QSize NickListWidget::sizeHint() const
{
- QWidget *currentWidget = ui.stackedWidget->currentWidget();
+ QWidget* currentWidget = ui.stackedWidget->currentWidget();
if (!currentWidget || currentWidget == ui.emptyPage)
return {100, height()};
else
return currentWidget->sizeHint();
}
-
// ==============================
// NickList Dock
// ==============================
-NickListDock::NickListDock(const QString &title, QWidget *parent)
+NickListDock::NickListDock(const QString& title, QWidget* parent)
: QDockWidget(title, parent)
{
// THIS STUFF IS NEEDED FOR NICKLIST AUTOHIDE...
// AS THIS BRINGS LOTS OF FUCKUPS WITH IT IT'S DEACTIVATED FOR NOW...
-// QAction *toggleView = toggleViewAction();
-// disconnect(toggleView, SIGNAL(triggered(bool)), this, 0);
-// toggleView->setChecked(QtUiSettings().value("ShowNickList", QVariant(true)).toBool());
+ // QAction *toggleView = toggleViewAction();
+ // disconnect(toggleView, SIGNAL(triggered(bool)), this, 0);
+ // toggleView->setChecked(QtUiSettings().value("ShowNickList", QVariant(true)).toBool());
-// // reconnecting the closebuttons clicked signal to the action
-// foreach(QAbstractButton *button, findChildren<QAbstractButton *>()) {
-// if(disconnect(button, SIGNAL(clicked()), this, SLOT(close())))
-// connect(button, SIGNAL(clicked()), toggleView, SLOT(trigger()));
-// }
+ // // reconnecting the closebuttons clicked signal to the action
+ // foreach(QAbstractButton *button, findChildren<QAbstractButton *>()) {
+ // if(disconnect(button, SIGNAL(clicked()), this, SLOT(close())))
+ // connect(button, SIGNAL(clicked()), toggleView, SLOT(trigger()));
+ // }
}
-void NickListDock::setLocked(bool locked) {
+void NickListDock::setLocked(bool locked)
+{
if (locked) {
setFeatures(nullptr);
}
#ifndef NICKLISTWIDGET_H_
#define NICKLISTWIDGET_H_
-#include "ui_nicklistwidget.h"
+#include <QDockWidget>
+#include <QHash>
+
#include "abstractitemview.h"
#include "buffermodel.h"
-
#include "types.h"
-#include <QHash>
-#include <QDockWidget>
+#include "ui_nicklistwidget.h"
class Buffer;
class NickView;
Q_OBJECT
public:
- NickListWidget(QWidget *parent = nullptr);
+ NickListWidget(QWidget* parent = nullptr);
public slots:
void showWidget(bool visible);
void setVisible(bool visible) override;
signals:
- void nickSelectionChanged(const QModelIndexList &);
+ void nickSelectionChanged(const QModelIndexList&);
protected:
QSize sizeHint() const override;
- void hideEvent(QHideEvent *) override;
- void showEvent(QShowEvent *) override;
+ void hideEvent(QHideEvent*) override;
+ void showEvent(QShowEvent*) override;
protected slots:
- void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) override;
- void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) override;
+ void currentChanged(const QModelIndex& current, const QModelIndex& previous) override;
+ void rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) override;
private:
void removeBuffer(BufferId bufferId);
private:
Ui::NickListWidget ui;
- QHash<BufferId, NickView *> nickViews;
+ QHash<BufferId, NickView*> nickViews;
- QDockWidget *dock() const;
+ QDockWidget* dock() const;
};
-
// ==============================
// NickList Dock
// ==============================
Q_OBJECT
public:
- NickListDock(const QString &title, QWidget *parent = nullptr);
+ NickListDock(const QString& title, QWidget* parent = nullptr);
// ~NickListDock();
void setLocked(bool locked);
// virtual bool event(QEvent *event);
};
-
#endif
Q_OBJECT
public:
- OSXNotificationBackend(QObject *parent = 0);
+ OSXNotificationBackend(QObject* parent = 0);
- void notify(const Notification &);
+ void notify(const Notification&);
void close(uint notificationId);
- virtual SettingsPage *createConfigWidget() const;
+ virtual SettingsPage* createConfigWidget() const;
private slots:
- void enabledChanged(const QVariant &value);
+ void enabledChanged(const QVariant& value);
private:
class ConfigWidget;
Q_OBJECT
public:
- ConfigWidget(QWidget *parent = 0);
+ ConfigWidget(QWidget* parent = 0);
void save();
void load();
bool hasDefaults() const;
void widgetChanged();
private:
- QCheckBox *_enabledBox;
+ QCheckBox* _enabledBox;
bool _enabled;
};
-#endif // OSXNOTIFICATIONBACKEND_H_
+#endif // OSXNOTIFICATIONBACKEND_H_
#include "client.h"
-PasswordChangeDlg::PasswordChangeDlg(QWidget *parent) : QDialog(parent)
+PasswordChangeDlg::PasswordChangeDlg(QWidget* parent)
+ : QDialog(parent)
{
ui.setupUi(this);
CoreAccount account = Client::currentCoreAccount();
ui.infoLabel->setText(tr("This changes the password for your username <b>%1</b> "
"on the Quassel Core running at <b>%2</b>.")
- .arg(account.user(), account.hostName()));
+ .arg(account.user(), account.hostName()));
connect(ui.oldPasswordEdit, &QLineEdit::textChanged, this, &PasswordChangeDlg::inputChanged);
connect(ui.newPasswordEdit, &QLineEdit::textChanged, this, &PasswordChangeDlg::inputChanged);
ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
}
-
void PasswordChangeDlg::inputChanged()
{
bool ok = !ui.oldPasswordEdit->text().isEmpty() && !ui.newPasswordEdit->text().isEmpty()
ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok);
}
-
void PasswordChangeDlg::changePassword()
{
ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
Client::changePassword(ui.oldPasswordEdit->text(), ui.newPasswordEdit->text());
}
-
void PasswordChangeDlg::passwordChanged(bool success)
{
if (!success) {
- QMessageBox box(QMessageBox::Warning, tr("Password Not Changed"),
- tr("<b>Password change failed</b>"),
- QMessageBox::Ok, this);
- box.setInformativeText(tr("The core reported an error when trying to change your password. Make sure you entered your old password correctly!"));
+ QMessageBox box(QMessageBox::Warning, tr("Password Not Changed"), tr("<b>Password change failed</b>"), QMessageBox::Ok, this);
+ box.setInformativeText(
+ tr("The core reported an error when trying to change your password. Make sure you entered your old password correctly!"));
box.exec();
}
else {
Q_OBJECT
public:
- PasswordChangeDlg(QWidget *parent = nullptr);
+ PasswordChangeDlg(QWidget* parent = nullptr);
private slots:
void inputChanged();
#include "qtmultimedianotificationbackend.h"
+#include <memory>
+
#include <QFileDialog>
#include <QUrl>
-#include <memory>
#include "clientsettings.h"
#include "icon.h"
#include "mainwin.h"
#include "qtui.h"
-QtMultimediaNotificationBackend::QtMultimediaNotificationBackend(QObject *parent)
+QtMultimediaNotificationBackend::QtMultimediaNotificationBackend(QObject* parent)
: AbstractNotificationBackend(parent)
{
NotificationSettings notificationSettings;
_enabled = notificationSettings.value("QtMultimedia/Enabled", true).toBool();
}
-
-void QtMultimediaNotificationBackend::notify(const Notification ¬ification)
+void QtMultimediaNotificationBackend::notify(const Notification& notification)
{
if (_enabled && (notification.type == Highlight || notification.type == PrivMsg)) {
if (_media && _media->availability() == QMultimedia::Available) {
}
}
-
void QtMultimediaNotificationBackend::close(uint notificationId)
{
Q_UNUSED(notificationId);
}
-
-void QtMultimediaNotificationBackend::enabledChanged(const QVariant &v)
+void QtMultimediaNotificationBackend::enabledChanged(const QVariant& v)
{
_enabled = v.toBool();
}
-
-void QtMultimediaNotificationBackend::audioFileChanged(const QVariant &v)
+void QtMultimediaNotificationBackend::audioFileChanged(const QVariant& v)
{
createMediaObject(v.toString());
}
-
-SettingsPage *QtMultimediaNotificationBackend::createConfigWidget() const
+SettingsPage* QtMultimediaNotificationBackend::createConfigWidget() const
{
return new ConfigWidget();
}
-
-void QtMultimediaNotificationBackend::createMediaObject(const QString &file)
+void QtMultimediaNotificationBackend::createMediaObject(const QString& file)
{
if (file.isEmpty()) {
_media.reset();
_media->setMedia(QUrl::fromLocalFile(file));
}
-
/***************************************************************************/
-QtMultimediaNotificationBackend::ConfigWidget::ConfigWidget(QWidget *parent)
+QtMultimediaNotificationBackend::ConfigWidget::ConfigWidget(QWidget* parent)
: SettingsPage("Internal", "QtMultimediaNotification", parent)
{
ui.setupUi(this);
connect(ui.filename, &QLineEdit::textChanged, this, &ConfigWidget::widgetChanged);
}
-
void QtMultimediaNotificationBackend::ConfigWidget::widgetChanged()
{
- if (! _audioAvailable) {
+ if (!_audioAvailable) {
ui.play->setEnabled(ui.enabled->isChecked());
ui.open->setEnabled(false);
ui.filename->setEnabled(false);
}
}
-
bool QtMultimediaNotificationBackend::ConfigWidget::hasDefaults() const
{
return true;
}
-
void QtMultimediaNotificationBackend::ConfigWidget::defaults()
{
ui.enabled->setChecked(false);
widgetChanged();
}
-
void QtMultimediaNotificationBackend::ConfigWidget::load()
{
NotificationSettings s;
setChangedState(false);
}
-
void QtMultimediaNotificationBackend::ConfigWidget::save()
{
NotificationSettings s;
load();
}
-
void QtMultimediaNotificationBackend::ConfigWidget::on_open_clicked()
{
QString file = QFileDialog::getOpenFileName(this, tr("Select Audio File"));
}
}
-
void QtMultimediaNotificationBackend::ConfigWidget::on_play_clicked()
{
if (_audioAvailable) {
Q_OBJECT
public:
- QtMultimediaNotificationBackend(QObject *parent = nullptr);
+ QtMultimediaNotificationBackend(QObject* parent = nullptr);
- void notify(const Notification &) override;
+ void notify(const Notification&) override;
void close(uint notificationId) override;
- SettingsPage *createConfigWidget() const override;
+ SettingsPage* createConfigWidget() const override;
private slots:
- void enabledChanged(const QVariant &);
- void audioFileChanged(const QVariant &);
- void createMediaObject(const QString &name);
+ void enabledChanged(const QVariant&);
+ void audioFileChanged(const QVariant&);
+ void createMediaObject(const QString& name);
private:
class ConfigWidget;
std::unique_ptr<QMediaPlayer> _media;
};
-
class QtMultimediaNotificationBackend::ConfigWidget : public SettingsPage
{
Q_OBJECT
public:
- ConfigWidget(QWidget *parent = nullptr);
+ ConfigWidget(QWidget* parent = nullptr);
void save() override;
void load() override;
#include "qtui.h"
+#include <memory>
+
#include <QApplication>
#include <QFile>
#include <QFileInfo>
#include <QIcon>
#include <QStringList>
-#include <memory>
#include "abstractnotificationbackend.h"
#include "buffermodel.h"
#include "types.h"
#include "util.h"
-QList<AbstractNotificationBackend *> QtUi::_notificationBackends;
+QList<AbstractNotificationBackend*> QtUi::_notificationBackends;
QList<AbstractNotificationBackend::Notification> QtUi::_notifications;
-
-QtUi *QtUi::instance()
+QtUi* QtUi::instance()
{
return static_cast<QtUi*>(GraphicalUi::instance());
}
-
QtUi::QtUi()
: GraphicalUi()
, _systemIconTheme{QIcon::themeName()}
setUiStyle(new QtUiStyle(this));
}
-
QtUi::~QtUi()
{
unregisterAllNotificationBackends();
}
-
void QtUi::init()
{
setContextMenuActionProvider(new ContextMenuActionProvider(this));
QtUiSettings uiSettings;
uiSettings.initAndNotify("UseSystemTrayIcon", this, &QtUi::useSystemTrayChanged, true);
- GraphicalUi::init(); // needs to be called after the mainWin is initialized
+ GraphicalUi::init(); // needs to be called after the mainWin is initialized
}
-
-MessageModel *QtUi::createMessageModel(QObject *parent)
+MessageModel* QtUi::createMessageModel(QObject* parent)
{
return new ChatLineModel(parent);
}
-
-AbstractMessageProcessor *QtUi::createMessageProcessor(QObject *parent)
+AbstractMessageProcessor* QtUi::createMessageProcessor(QObject* parent)
{
return new QtUiMessageProcessor(parent);
}
-
void QtUi::connectedToCore()
{
_mainWin->connectedToCore();
}
-
void QtUi::disconnectedFromCore()
{
_mainWin->disconnectedFromCore();
GraphicalUi::disconnectedFromCore();
}
-
-void QtUi::useSystemTrayChanged(const QVariant &v)
+void QtUi::useSystemTrayChanged(const QVariant& v)
{
_useSystemTray = v.toBool();
- SystemTray *tray = mainWindow()->systemTray();
+ SystemTray* tray = mainWindow()->systemTray();
if (_useSystemTray) {
if (tray->isSystemTrayAvailable())
tray->setVisible(true);
}
}
-
bool QtUi::haveSystemTray()
{
return mainWindow()->systemTray()->isSystemTrayAvailable() && instance()->_useSystemTray;
}
-
bool QtUi::isHidingMainWidgetAllowed() const
{
return haveSystemTray();
}
-
void QtUi::minimizeRestore(bool show)
{
- SystemTray *tray = mainWindow()->systemTray();
+ SystemTray* tray = mainWindow()->systemTray();
if (show) {
if (tray && !_useSystemTray)
tray->setVisible(false);
GraphicalUi::minimizeRestore(show);
}
-
-void QtUi::registerNotificationBackend(AbstractNotificationBackend *backend)
+void QtUi::registerNotificationBackend(AbstractNotificationBackend* backend)
{
if (!_notificationBackends.contains(backend)) {
_notificationBackends.append(backend);
}
}
-
-void QtUi::unregisterNotificationBackend(AbstractNotificationBackend *backend)
+void QtUi::unregisterNotificationBackend(AbstractNotificationBackend* backend)
{
_notificationBackends.removeAll(backend);
}
-
void QtUi::unregisterAllNotificationBackends()
{
_notificationBackends.clear();
}
-
-const QList<AbstractNotificationBackend *> &QtUi::notificationBackends()
+const QList<AbstractNotificationBackend*>& QtUi::notificationBackends()
{
return _notificationBackends;
}
-
-uint QtUi::invokeNotification(BufferId bufId, AbstractNotificationBackend::NotificationType type, const QString &sender, const QString &text)
+uint QtUi::invokeNotification(BufferId bufId, AbstractNotificationBackend::NotificationType type, const QString& sender, const QString& text)
{
static int notificationId = 0;
AbstractNotificationBackend::Notification notification(++notificationId, bufId, type, sender, text);
_notifications.append(notification);
- foreach(AbstractNotificationBackend *backend, _notificationBackends)
- backend->notify(notification);
+ foreach (AbstractNotificationBackend* backend, _notificationBackends)
+ backend->notify(notification);
return notificationId;
}
-
void QtUi::closeNotification(uint notificationId)
{
QList<AbstractNotificationBackend::Notification>::iterator i = _notifications.begin();
while (i != _notifications.end()) {
if (i->notificationId == notificationId) {
- foreach(AbstractNotificationBackend *backend, _notificationBackends)
- backend->close(notificationId);
+ foreach (AbstractNotificationBackend* backend, _notificationBackends)
+ backend->close(notificationId);
i = _notifications.erase(i);
}
- else ++i;
+ else
+ ++i;
}
}
-
void QtUi::closeNotifications(BufferId bufferId)
{
QList<AbstractNotificationBackend::Notification>::iterator i = _notifications.begin();
while (i != _notifications.end()) {
if (!bufferId.isValid() || i->bufferId == bufferId) {
- foreach(AbstractNotificationBackend *backend, _notificationBackends)
- backend->close(i->notificationId);
+ foreach (AbstractNotificationBackend* backend, _notificationBackends)
+ backend->close(i->notificationId);
i = _notifications.erase(i);
}
- else ++i;
+ else
+ ++i;
}
}
-
-const QList<AbstractNotificationBackend::Notification> &QtUi::activeNotifications()
+const QList<AbstractNotificationBackend::Notification>& QtUi::activeNotifications()
{
return _notifications;
}
-
void QtUi::notificationActivated(uint notificationId)
{
if (notificationId != 0) {
activateMainWidget();
}
-
void QtUi::bufferMarkedAsRead(BufferId bufferId)
{
if (bufferId.isValid()) {
}
}
-
std::vector<std::pair<QString, QString>> QtUi::availableIconThemes() const
{
//: Supported icon theme names
- static const std::vector<std::pair<QString, QString>> supported {
- { "breeze", tr("Breeze") },
- { "breeze-dark", tr("Breeze Dark") },
+ static const std::vector<std::pair<QString, QString>> supported{{"breeze", tr("Breeze")},
+ {"breeze-dark", tr("Breeze Dark")},
#ifdef WITH_OXYGEN_ICONS
- { "oxygen", tr("Oxygen") }
+ {"oxygen", tr("Oxygen")}
#endif
};
std::vector<std::pair<QString, QString>> result;
- for (auto &&themePair : supported) {
- for (auto &&dir : QIcon::themeSearchPaths()) {
+ for (auto&& themePair : supported) {
+ for (auto&& dir : QIcon::themeSearchPaths()) {
if (QFileInfo{dir + "/" + themePair.first + "/index.theme"}.exists()) {
result.push_back(themePair);
break;
return result;
}
-
QString QtUi::systemIconTheme() const
{
return _systemIconTheme;
}
-
void QtUi::setupIconTheme()
{
// Add paths to our own icon sets to the theme search paths
QStringList themePaths = QIcon::themeSearchPaths();
themePaths.removeAll(":/icons"); // this should come last
- for (auto &&dataDir : Quassel::dataDirPaths()) {
+ for (auto&& dataDir : Quassel::dataDirPaths()) {
QString iconDir{dataDir + "icons"};
if (QFileInfo{iconDir}.isDir()) {
themePaths << iconDir;
refreshIconTheme();
}
-
void QtUi::refreshIconTheme()
{
// List of available fallback themes
QStringList availableThemes;
- for (auto &&themePair : availableIconThemes()) {
+ for (auto&& themePair : availableIconThemes()) {
availableThemes << themePair.first;
}
// We could probably introduce a more sophisticated fallback handling, such as putting the "most important" icons into hicolor,
// but this just gets complex for no good reason. We really rely on a supported theme to be installed, if not system-wide, then
// as part of the Quassel installation (which is enabled by default anyway).
- qWarning() << tr("No supported icon theme installed, you'll lack icons! Supported are the KDE/Plasma themes Breeze, Breeze Dark and Oxygen.");
+ qWarning() << tr(
+ "No supported icon theme installed, you'll lack icons! Supported are the KDE/Plasma themes Breeze, Breeze Dark and Oxygen.");
return;
}
}
QFile indexFile{_dummyThemeDir->path() + "/icons/quassel-icon-proxy/index.theme"};
- if (!indexFile.open(QFile::WriteOnly|QFile::Truncate)) {
+ if (!indexFile.open(QFile::WriteOnly | QFile::Truncate)) {
qWarning() << "Could not create index file for proxying the system icon theme, using fallback";
QIcon::setThemeName(fallbackTheme);
emit iconThemeRefreshed();
}
// Write a dummy index file that is sufficient to make QIconLoader happy
- auto indexContents = QString{
- "[Icon Theme]\n"
- "Name=quassel-icon-proxy\n"
- "Inherits=%1,%2\n"
- "Directories=apps/32\n"
- "[apps/32]\nSize=32\nType=Fixed\n"
- }.arg(_systemIconTheme, fallbackTheme);
+ auto indexContents = QString{"[Icon Theme]\n"
+ "Name=quassel-icon-proxy\n"
+ "Inherits=%1,%2\n"
+ "Directories=apps/32\n"
+ "[apps/32]\nSize=32\nType=Fixed\n"}
+ .arg(_systemIconTheme, fallbackTheme);
if (indexFile.write(indexContents.toLatin1()) < 0) {
qWarning() << "Could not write index file for proxying the system icon theme, using fallback";
QIcon::setThemeName(fallbackTheme);
QtUi();
~QtUi() override;
- MessageModel *createMessageModel(QObject *parent) override;
- AbstractMessageProcessor *createMessageProcessor(QObject *parent) override;
+ MessageModel* createMessageModel(QObject* parent) override;
+ AbstractMessageProcessor* createMessageProcessor(QObject* parent) override;
- static QtUi *instance();
- inline static QtUiStyle *style();
- inline static MainWin *mainWindow();
+ static QtUi* instance();
+ inline static QtUiStyle* style();
+ inline static MainWin* mainWindow();
QString debugLog() const;
/* Notifications */
- static void registerNotificationBackend(AbstractNotificationBackend *);
- static void unregisterNotificationBackend(AbstractNotificationBackend *);
+ static void registerNotificationBackend(AbstractNotificationBackend*);
+ static void unregisterNotificationBackend(AbstractNotificationBackend*);
static void unregisterAllNotificationBackends();
- static const QList<AbstractNotificationBackend *> ¬ificationBackends();
- static const QList<AbstractNotificationBackend::Notification> &activeNotifications();
+ static const QList<AbstractNotificationBackend*>& notificationBackends();
+ static const QList<AbstractNotificationBackend::Notification>& activeNotifications();
/**
* Determine available fallback icon themes.
public slots:
void init() override;
- uint invokeNotification(BufferId bufId, AbstractNotificationBackend::NotificationType type, const QString &sender, const QString &text);
+ uint invokeNotification(BufferId bufId, AbstractNotificationBackend::NotificationType type, const QString& sender, const QString& text);
void closeNotification(uint notificationId);
void closeNotifications(BufferId bufferId = BufferId());
bool isHidingMainWidgetAllowed() const override;
private slots:
- void useSystemTrayChanged(const QVariant &);
+ void useSystemTrayChanged(const QVariant&);
private:
/**
void setupIconTheme();
private:
- static QList<AbstractNotificationBackend *> _notificationBackends;
+ static QList<AbstractNotificationBackend*> _notificationBackends;
static QList<AbstractNotificationBackend::Notification> _notifications;
std::unique_ptr<MainWin> _mainWin;
bool _useSystemTray;
};
-QtUiStyle *QtUi::style() { return qobject_cast<QtUiStyle *>(uiStyle()); }
-MainWin *QtUi::mainWindow() { return instance()->_mainWin.get(); }
+QtUiStyle* QtUi::style()
+{
+ return qobject_cast<QtUiStyle*>(uiStyle());
+}
+
+MainWin* QtUi::mainWindow()
+{
+ return instance()->_mainWin.get();
+}
#include "qtuisettings.h"
#include "types.h"
-QtUiApplication::QtUiApplication(int &argc, char **argv)
+QtUiApplication::QtUiApplication(int& argc, char** argv)
: QApplication(argc, argv)
{
#if QT_VERSION >= 0x050600
#endif
}
-
void QtUiApplication::init()
{
// Settings upgrade/downgrade handling
});
}
-
Quassel::QuitHandler QtUiApplication::quitHandler()
{
// Wait until the Client instance is destroyed before quitting the event loop
};
}
-
bool QtUiApplication::migrateSettings()
{
// --------
QtUiSettings s;
uint versionMajor = s.version();
if (versionMajor != 1) {
- qCritical() << qPrintable(QString("Invalid client settings version '%1'")
- .arg(versionMajor));
+ qCritical() << qPrintable(QString("Invalid client settings version '%1'").arg(versionMajor));
return false;
}
if (versionMinor == VERSION_MINOR_CURRENT) {
// At latest version, no need to migrate defaults or other settings
return true;
- } else if (versionMinor == 0) {
+ }
+ else if (versionMinor == 0) {
// New configuration, store as current version
- qDebug() << qPrintable(QString("Set up new client settings v%1.%2")
- .arg(versionMajor).arg(VERSION_MINOR_CURRENT));
+ qDebug() << qPrintable(QString("Set up new client settings v%1.%2").arg(versionMajor).arg(VERSION_MINOR_CURRENT));
s.setVersionMinor(VERSION_MINOR_CURRENT);
// Update the settings stylesheet for first setup. We don't know if older content exists,
QtUiStyle qtUiStyle;
qtUiStyle.generateSettingsQss();
return true;
- } else if (versionMinor < VERSION_MINOR_CURRENT) {
+ }
+ else if (versionMinor < VERSION_MINOR_CURRENT) {
// We're upgrading - apply the neccessary upgrades from each interim version
// curVersion will never equal VERSION_MINOR_CURRENT, as it represents the version before
// the most recent applySettingsMigration() call.
// Something went wrong, time to bail out
qCritical() << qPrintable(QString("Could not migrate client settings from v%1.%2 "
"to v%1.%3")
- .arg(versionMajor).arg(curVersion).arg(curVersion + 1));
+ .arg(versionMajor)
+ .arg(curVersion)
+ .arg(curVersion + 1));
// Keep track of the last successful upgrade to avoid repeating it on next start
s.setVersionMinor(curVersion);
return false;
// Migration successful!
qDebug() << qPrintable(QString("Successfully migrated client settings from v%1.%2 to "
"v%1.%3")
- .arg(versionMajor).arg(versionMinor).arg(VERSION_MINOR_CURRENT));
+ .arg(versionMajor)
+ .arg(versionMinor)
+ .arg(VERSION_MINOR_CURRENT));
// Store the new minor version
s.setVersionMinor(VERSION_MINOR_CURRENT);
return true;
- } else {
+ }
+ else {
// versionMinor > VERSION_MINOR_CURRENT
// The user downgraded to an older version of Quassel. Let's hope for the best.
// Don't change the minorVersion as the newer version's upgrade logic has already run.
qWarning() << qPrintable(QString("Client settings v%1.%2 is newer than latest known v%1.%3,"
" things might not work!")
- .arg(versionMajor).arg(versionMinor).arg(VERSION_MINOR_CURRENT));
+ .arg(versionMajor)
+ .arg(versionMinor)
+ .arg(VERSION_MINOR_CURRENT));
return true;
}
}
-
bool QtUiApplication::applySettingsMigration(QtUiSettings settings, const uint newVersion)
{
switch (newVersion) {
// saved. Exceptions will be noted below.
// NOTE: If you add new upgrade logic here, you MUST ALSO increase VERSION_MINOR_CURRENT in
// migrateSettings()! Otherwise, your upgrade logic won't ever be called.
- case 9:
- {
+ case 9: {
// New default changes: show highest sender prefix mode, if available
// --------
const QString senderPrefixModeId = "SenderPrefixMode";
if (!chatViewSettings.valueExists(senderPrefixModeId)) {
// New default is HighestMode, preserve previous behavior by setting to NoModes
- chatViewSettings.setValue(senderPrefixModeId,
- static_cast<int>(UiStyle::SenderPrefixMode::NoModes));
+ chatViewSettings.setValue(senderPrefixModeId, static_cast<int>(UiStyle::SenderPrefixMode::NoModes));
}
// --------
return true;
}
- case 8:
- {
+ case 8: {
// New default changes: RegEx checkbox now toggles Channel regular expressions, too
//
// This only affects local highlights. Core-side highlights weren't released in stable when
// This might be more efficient with std::transform() or such. It /is/ only run once...
auto highlightList = notificationSettings.highlightList();
bool changesMade = false;
- for (int index = 0; index < highlightList.count(); ++index)
- {
+ for (int index = 0; index < highlightList.count(); ++index) {
// Load the highlight rule...
auto highlightRule = highlightList[index].toMap();
// Check if "Channel" has anything set and RegEx is disabled
- if (!highlightRule["Channel"].toString().isEmpty()
- && highlightRule["RegEx"].toBool() == false) {
+ if (!highlightRule["Channel"].toString().isEmpty() && highlightRule["RegEx"].toBool() == false) {
// We have a rule to convert
// Mark as a regular expression, allowing the Channel filtering to work the same as
// Convert the main rule to regular expression, mirroring the conversion to wildcard
// format from QtUiMessageProcessor::checkForHighlight()
- highlightRule["Name"] =
- "(^|\\W)" + QRegExp::escape(highlightRule["Name"].toString()) + "(\\W|$)";
+ highlightRule["Name"] = "(^|\\W)" + QRegExp::escape(highlightRule["Name"].toString()) + "(\\W|$)";
// Save the rule back
highlightList[index] = highlightRule;
// Migration complete!
return true;
}
- case 7:
- {
+ case 7: {
// New default changes: UseProxy is no longer used in CoreAccountSettings
CoreAccountSettings s;
- for (auto &&accountId : s.knownAccounts()) {
+ for (auto&& accountId : s.knownAccounts()) {
auto map = s.retrieveAccountData(accountId);
if (!map.value("UseProxy", false).toBool()) {
map["ProxyType"] = static_cast<int>(QNetworkProxy::ProxyType::NoProxy);
// Migration complete!
return true;
}
- case 6:
- {
+ case 6: {
// New default changes: sender colors switched around to Tango-ish theme
// --------
QtUiStyleSettings settingsUiStyleColors("Colors");
// Preserve the old default values for all variants
const QColor oldDefaultSenderColorSelf = QColor(0, 0, 0);
- const QList<QColor> oldDefaultSenderColors = QList<QColor> {
- QColor(204, 13, 127), /// Sender00
- QColor(142, 85, 233), /// Sender01
- QColor(179, 14, 14), /// Sender02
- QColor( 23, 179, 57), /// Sender03
- QColor( 88, 175, 179), /// Sender04
- QColor(157, 84, 179), /// Sender05
+ const QList<QColor> oldDefaultSenderColors = QList<QColor>{
+ QColor(204, 13, 127), /// Sender00
+ QColor(142, 85, 233), /// Sender01
+ QColor(179, 14, 14), /// Sender02
+ QColor(23, 179, 57), /// Sender03
+ QColor(88, 175, 179), /// Sender04
+ QColor(157, 84, 179), /// Sender05
QColor(179, 151, 117), /// Sender06
- QColor( 49, 118, 179), /// Sender07
- QColor(233, 13, 127), /// Sender08
- QColor(142, 85, 233), /// Sender09
- QColor(179, 14, 14), /// Sender10
- QColor( 23, 179, 57), /// Sender11
- QColor( 88, 175, 179), /// Sender12
- QColor(157, 84, 179), /// Sender13
+ QColor(49, 118, 179), /// Sender07
+ QColor(233, 13, 127), /// Sender08
+ QColor(142, 85, 233), /// Sender09
+ QColor(179, 14, 14), /// Sender10
+ QColor(23, 179, 57), /// Sender11
+ QColor(88, 175, 179), /// Sender12
+ QColor(157, 84, 179), /// Sender13
QColor(179, 151, 117), /// Sender14
- QColor( 49, 118, 179), /// Sender15
+ QColor(49, 118, 179), /// Sender15
};
if (!settingsUiStyleColors.valueExists("SenderSelf")) {
// Preserve the old default sender color if none set
for (int i = 0; i < oldDefaultSenderColors.count(); i++) {
// Get the sender color ID for each available color
QString dez = QString::number(i);
- if (dez.length() == 1) dez.prepend('0');
+ if (dez.length() == 1)
+ dez.prepend('0');
senderColorId = QString("Sender" + dez);
if (!settingsUiStyleColors.valueExists(senderColorId)) {
// Preserve the old default sender color if none set
// Migration complete!
return true;
}
- case 5:
- {
+ case 5: {
// New default changes: sender colors apply to nearly all messages with nicks
// --------
// Migration complete!
return true;
}
- case 4:
- {
+ case 4: {
// New default changes: system locale used to generate a timestamp format string, deciding
// 24-hour or 12-hour timestamp.
// Migration complete!
return true;
}
- case 3:
- {
+ case 3: {
// New default changes: per-chat history and line wrapping enabled by default.
// --------
// Migration complete!
return true;
}
- case 2:
- {
+ case 2: {
// New default changes: sender <nick> brackets disabled, sender colors and sender CTCP
// colors enabled.
}
}
-
-void QtUiApplication::commitData(QSessionManager &manager)
+void QtUiApplication::commitData(QSessionManager& manager)
{
Q_UNUSED(manager)
_aboutToQuit = true;
}
-
-void QtUiApplication::saveState(QSessionManager &manager)
+void QtUiApplication::saveState(QSessionManager& manager)
{
- //qDebug() << QString("saving session state to id %1").arg(manager.sessionId());
+ // qDebug() << QString("saving session state to id %1").arg(manager.sessionId());
// AccountId activeCore = Client::currentCoreAccount().accountId(); // FIXME store this!
SessionSettings s(manager.sessionId());
s.setSessionAge(0);
QtUi::mainWindow()->saveStateToSettings(s);
}
-
void QtUiApplication::resumeSessionIfPossible()
{
// load all sessions
#include <QSessionManager>
#include "client.h"
+#include "qtuisettings.h"
#include "quassel.h"
#include "uisettings.h"
-#include "qtuisettings.h"
class QtUi;
Q_OBJECT
public:
- QtUiApplication(int &, char **);
+ QtUiApplication(int&, char**);
virtual void init();
void resumeSessionIfPossible();
inline bool isAboutToQuit() const { return _aboutToQuit; }
- void commitData(QSessionManager &manager);
- void saveState(QSessionManager &manager);
+ void commitData(QSessionManager& manager);
+ void saveState(QSessionManager& manager);
protected:
virtual Quassel::QuitHandler quitHandler();
#include "messagemodel.h"
#include "network.h"
-QtUiMessageProcessor::QtUiMessageProcessor(QObject *parent)
- : AbstractMessageProcessor(parent),
- _processing(false),
- _processMode(TimerBased)
+QtUiMessageProcessor::QtUiMessageProcessor(QObject* parent)
+ : AbstractMessageProcessor(parent)
+ , _processing(false)
+ , _processMode(TimerBased)
{
NotificationSettings notificationSettings;
_nicksCaseSensitive = notificationSettings.nicksCaseSensitive();
_nickMatcher.setCaseSensitive(_nicksCaseSensitive);
_highlightNick = notificationSettings.highlightNick();
- _nickMatcher.setHighlightMode(
- static_cast<NickHighlightMatcher::HighlightNickType>(_highlightNick));
+ _nickMatcher.setHighlightMode(static_cast<NickHighlightMatcher::HighlightNickType>(_highlightNick));
highlightListChanged(notificationSettings.highlightList());
notificationSettings.notify("Highlights/NicksCaseSensitive", this, &QtUiMessageProcessor::nicksCaseSensitiveChanged);
notificationSettings.notify("Highlights/CustomList", this, &QtUiMessageProcessor::highlightListChanged);
connect(&_processTimer, &QTimer::timeout, this, &QtUiMessageProcessor::processNextMessage);
}
-
void QtUiMessageProcessor::reset()
{
if (processMode() == TimerBased) {
- if (_processTimer.isActive()) _processTimer.stop();
+ if (_processTimer.isActive())
+ _processTimer.stop();
_processing = false;
_currentBatch.clear();
_processQueue.clear();
}
}
-
-void QtUiMessageProcessor::process(Message &msg)
+void QtUiMessageProcessor::process(Message& msg)
{
checkForHighlight(msg);
preProcess(msg);
Client::messageModel()->insertMessage(msg);
}
-
-void QtUiMessageProcessor::process(QList<Message> &msgs)
+void QtUiMessageProcessor::process(QList<Message>& msgs)
{
QList<Message>::iterator msgIter = msgs.begin();
QList<Message>::iterator msgIterEnd = msgs.end();
Client::messageModel()->insertMessages(msgs);
return;
- if (msgs.isEmpty()) return;
+ if (msgs.isEmpty())
+ return;
_processQueue.append(msgs);
if (!isProcessing())
startProcessing();
}
-
void QtUiMessageProcessor::startProcessing()
{
if (processMode() == TimerBased) {
}
}
-
void QtUiMessageProcessor::processNextMessage()
{
if (_currentBatch.isEmpty()) {
process(msg);
}
-
-void QtUiMessageProcessor::checkForHighlight(Message &msg)
+void QtUiMessageProcessor::checkForHighlight(Message& msg)
{
if (!((msg.type() & (Message::Plain | Message::Notice | Message::Action)) && !(msg.flags() & Message::Self)))
return;
// Cached per network
- const NetworkId &netId = msg.bufferInfo().networkId();
- const Network *net = Client::network(netId);
+ const NetworkId& netId = msg.bufferInfo().networkId();
+ const Network* net = Client::network(netId);
if (net && !net->myNick().isEmpty()) {
// Get current nick
QString currentNick = net->myNick();
// Get identity nicks
QStringList identityNicks = {};
- const Identity *myIdentity = Client::identity(net->identity());
+ const Identity* myIdentity = Client::identity(net->identity());
if (myIdentity) {
identityNicks = myIdentity->nicks();
}
bool matches = false;
for (int i = 0; i < _highlightRuleList.count(); i++) {
- auto &rule = _highlightRuleList.at(i);
+ auto& rule = _highlightRuleList.at(i);
if (!rule.isEnabled())
continue;
if (_highlightNick != HighlightNickType::NoNick && !currentNick.isEmpty()) {
// Nickname matching allowed and current nickname is known
// Run the nickname matcher on the unformatted string
- if (_nickMatcher.match(stripFormatCodes(msgContents), netId, currentNick,
- identityNicks)) {
+ if (_nickMatcher.match(stripFormatCodes(msgContents), netId, currentNick, identityNicks)) {
msg.setFlags(msg.flags() | Message::Highlight);
return;
}
}
}
-
-void QtUiMessageProcessor::nicksCaseSensitiveChanged(const QVariant &variant)
+void QtUiMessageProcessor::nicksCaseSensitiveChanged(const QVariant& variant)
{
_nicksCaseSensitive = variant.toBool();
// Update nickname matcher, too
_nickMatcher.setCaseSensitive(_nicksCaseSensitive);
}
-
-void QtUiMessageProcessor::highlightListChanged(const QVariant &variant)
+void QtUiMessageProcessor::highlightListChanged(const QVariant& variant)
{
QVariantList varList = variant.toList();
while (iter != varList.constEnd()) {
QVariantMap rule = iter->toMap();
_highlightRuleList << LegacyHighlightRule(rule["Name"].toString(),
- rule["RegEx"].toBool(),
- rule["CS"].toBool(),
- rule["Enable"].toBool(),
- rule["Channel"].toString());
+ rule["RegEx"].toBool(),
+ rule["CS"].toBool(),
+ rule["Enable"].toBool(),
+ rule["Channel"].toString());
++iter;
}
}
-
-void QtUiMessageProcessor::highlightNickChanged(const QVariant &variant)
+void QtUiMessageProcessor::highlightNickChanged(const QVariant& variant)
{
_highlightNick = (HighlightNickType)variant.toInt();
// Convert from QtUiMessageProcessor::HighlightNickType (which is from NotificationSettings) to
// NickHighlightMatcher::HighlightNickType
- _nickMatcher.setHighlightMode(
- static_cast<NickHighlightMatcher::HighlightNickType>(_highlightNick));
+ _nickMatcher.setHighlightMode(static_cast<NickHighlightMatcher::HighlightNickType>(_highlightNick));
}
-
void QtUiMessageProcessor::networkRemoved(NetworkId id)
{
// Clean up nickname matching cache
_nickMatcher.removeNetwork(id);
}
-
/**************************************************************************
* LegacyHighlightRule
*************************************************************************/
-bool QtUiMessageProcessor::LegacyHighlightRule::operator!=(const LegacyHighlightRule &other) const
+bool QtUiMessageProcessor::LegacyHighlightRule::operator!=(const LegacyHighlightRule& other) const
{
- return (_contents != other._contents ||
- _isRegEx != other._isRegEx ||
- _isCaseSensitive != other._isCaseSensitive ||
- _isEnabled != other._isEnabled ||
- _chanName != other._chanName);
+ return (_contents != other._contents || _isRegEx != other._isRegEx || _isCaseSensitive != other._isCaseSensitive
+ || _isEnabled != other._isEnabled || _chanName != other._chanName);
// Don't compare ExpressionMatch objects as they are created as needed from the above
}
-
void QtUiMessageProcessor::LegacyHighlightRule::determineExpressions() const
{
// Don't update if not needed
// Set up matching rules
// Message is either phrase or regex
- ExpressionMatch::MatchMode contentsMode =
- _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx :
- ExpressionMatch::MatchMode::MatchPhrase;
+ ExpressionMatch::MatchMode contentsMode = _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx : ExpressionMatch::MatchMode::MatchPhrase;
// Sender (when added) and channel are either multiple wildcard entries or regex
- ExpressionMatch::MatchMode scopeMode =
- _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx :
- ExpressionMatch::MatchMode::MatchMultiWildcard;
+ ExpressionMatch::MatchMode scopeMode = _isRegEx ? ExpressionMatch::MatchMode::MatchRegEx : ExpressionMatch::MatchMode::MatchMultiWildcard;
_contentsMatch = ExpressionMatch(_contents, contentsMode, _isCaseSensitive);
_chanNameMatch = ExpressionMatch(_chanName, scopeMode, _isCaseSensitive);
#ifndef QTUIMESSAGEPROCESSOR_H_
#define QTUIMESSAGEPROCESSOR_H_
-#include <QTimer>
#include <utility>
+#include <QTimer>
+
#include "abstractmessageprocessor.h"
#include "expressionmatch.h"
#include "nickhighlightmatcher.h"
Q_OBJECT
public:
- enum Mode {
+ enum Mode
+ {
TimerBased,
Concurrent
};
- QtUiMessageProcessor(QObject *parent);
+ QtUiMessageProcessor(QObject* parent);
inline bool isProcessing() const { return _processing; }
inline Mode processMode() const { return _processMode; }
void reset() override;
public slots:
- void process(Message &msg) override;
- void process(QList<Message> &msgs) override;
+ void process(Message& msg) override;
+ void process(QList<Message>& msgs) override;
/**
* Network removed from system
private slots:
void processNextMessage();
- void nicksCaseSensitiveChanged(const QVariant &variant);
- void highlightListChanged(const QVariant &variant);
- void highlightNickChanged(const QVariant &variant);
+ void nicksCaseSensitiveChanged(const QVariant& variant);
+ void highlightListChanged(const QVariant& variant);
+ void highlightNickChanged(const QVariant& variant);
private:
/**
* @param isEnabled True if enabled, otherwise false
* @param chanName String representing a channel name expression to match
*/
- LegacyHighlightRule(QString contents, bool isRegEx, bool isCaseSensitive, bool isEnabled,
- QString chanName)
- : _contents(std::move(contents)), _isRegEx(isRegEx), _isCaseSensitive(isCaseSensitive),
- _isEnabled(isEnabled), _chanName(std::move(chanName))
+ LegacyHighlightRule(QString contents, bool isRegEx, bool isCaseSensitive, bool isEnabled, QString chanName)
+ : _contents(std::move(contents))
+ , _isRegEx(isRegEx)
+ , _isCaseSensitive(isCaseSensitive)
+ , _isEnabled(isEnabled)
+ , _chanName(std::move(chanName))
{
_cacheInvalid = true;
// Cache expression matches on construction
*
* @return String representing a phrase or expression to match
*/
- inline QString contents() const {
- return _contents;
- }
+ inline QString contents() const { return _contents; }
/**
* Sets the message contents this rule matches
*
* @param contents String representing a phrase or expression to match
*/
- inline void setContents(const QString &contents) {
+ inline void setContents(const QString& contents)
+ {
_contents = contents;
_cacheInvalid = true;
}
*
* @return True if regular expression, otherwise false
*/
- inline bool isRegEx() const {
- return _isRegEx;
- }
+ inline bool isRegEx() const { return _isRegEx; }
/**
* Sets if this rule is a regular expression rule
*
* @param isRegEx True if regular expression, otherwise false
*/
- inline void setIsRegEx(bool isRegEx) {
+ inline void setIsRegEx(bool isRegEx)
+ {
_isRegEx = isRegEx;
_cacheInvalid = true;
}
*
* @return True if case sensitive, otherwise false
*/
- inline bool isCaseSensitive() const {
- return _isCaseSensitive;
- }
+ inline bool isCaseSensitive() const { return _isCaseSensitive; }
/**
* Sets if this rule is case sensitive
*
* @param isCaseSensitive True if case sensitive, otherwise false
*/
- inline void setIsCaseSensitive(bool isCaseSensitive) {
+ inline void setIsCaseSensitive(bool isCaseSensitive)
+ {
_isCaseSensitive = isCaseSensitive;
_cacheInvalid = true;
}
*
* @return True if enabled, otherwise false
*/
- inline bool isEnabled() const {
- return _isEnabled;
- }
+ inline bool isEnabled() const { return _isEnabled; }
/**
* Sets if this rule is enabled and active
*
* @param isEnabled True if enabled, otherwise false
*/
- inline void setIsEnabled(bool isEnabled) {
- _isEnabled = isEnabled;
- }
+ inline void setIsEnabled(bool isEnabled) { _isEnabled = isEnabled; }
/**
* Gets the channel name this rule matches
*
* @return String representing a phrase or expression to match
*/
- inline QString chanName() const {
- return _chanName;
- }
+ inline QString chanName() const { return _chanName; }
/**
* Sets the channel name this rule matches
*
* @param chanName String representing a phrase or expression to match
*/
- inline void setChanName(const QString &chanName) {
+ inline void setChanName(const QString& chanName)
+ {
_chanName = chanName;
_cacheInvalid = true;
}
*
* @return Expression matcher to compare with message contents
*/
- inline ExpressionMatch contentsMatcher() const {
+ inline ExpressionMatch contentsMatcher() const
+ {
if (_cacheInvalid) {
determineExpressions();
}
*
* @return Expression matcher to compare with channel name
*/
- inline ExpressionMatch chanNameMatcher() const {
+ inline ExpressionMatch chanNameMatcher() const
+ {
if (_cacheInvalid) {
determineExpressions();
}
return _chanNameMatch;
}
- bool operator!=(const LegacyHighlightRule &other) const;
+ bool operator!=(const LegacyHighlightRule& other) const;
private:
/**
// These represent internal cache and should be safe to mutate in 'const' functions
// See https://stackoverflow.com/questions/3141087/what-is-meant-with-const-at-end-of-function-declaration
- mutable bool _cacheInvalid = true; ///< If true, match cache needs redone
- mutable ExpressionMatch _contentsMatch = {}; ///< Expression match cache for message content
- mutable ExpressionMatch _chanNameMatch = {}; ///< Expression match cache for channel name
+ mutable bool _cacheInvalid = true; ///< If true, match cache needs redone
+ mutable ExpressionMatch _contentsMatch = {}; ///< Expression match cache for message content
+ mutable ExpressionMatch _chanNameMatch = {}; ///< Expression match cache for channel name
};
using LegacyHighlightRuleList = QList<LegacyHighlightRule>;
- void checkForHighlight(Message &msg);
+ void checkForHighlight(Message& msg);
void startProcessing();
using HighlightNickType = NotificationSettings::HighlightNickType;
- LegacyHighlightRuleList _highlightRuleList; ///< Custom highlight rule list
- NickHighlightMatcher _nickMatcher = {}; ///< Nickname highlight matcher
+ LegacyHighlightRuleList _highlightRuleList; ///< Custom highlight rule list
+ NickHighlightMatcher _nickMatcher = {}; ///< Nickname highlight matcher
/// Nickname highlighting mode
HighlightNickType _highlightNick = HighlightNickType::CurrentNick;
- bool _nicksCaseSensitive = false; ///< If true, match nicknames with exact case
+ bool _nicksCaseSensitive = false; ///< If true, match nicknames with exact case
- QList<QList<Message> > _processQueue;
+ QList<QList<Message>> _processQueue;
QList<Message> _currentBatch;
QTimer _processTimer;
bool _processing;
Mode _processMode;
};
-
#endif
QtUiSettings::QtUiSettings()
: UiSettings("QtUi")
-{
-}
+{}
-
-QtUiSettings::QtUiSettings(const QString &subGroup)
+QtUiSettings::QtUiSettings(const QString& subGroup)
: UiSettings(QString("QtUi/%1").arg(subGroup))
-{
-}
-
+{}
/***********************************************************************/
QtUiStyleSettings::QtUiStyleSettings()
: UiSettings("QtUiStyle")
-{
-}
+{}
-
-QtUiStyleSettings::QtUiStyleSettings(const QString &subGroup)
+QtUiStyleSettings::QtUiStyleSettings(const QString& subGroup)
: UiSettings(QString("QtUiStyle/%1").arg(subGroup))
-{
-}
+{}
/***********************************************************************/
WarningsSettings::WarningsSettings()
: UiSettings("Warnings")
-{
-}
-
+{}
-bool WarningsSettings::showWarning(const QString &key) const
+bool WarningsSettings::showWarning(const QString& key) const
{
return localValue(key, true).toBool();
}
-
-void WarningsSettings::setShowWarning(const QString &key, bool show)
+void WarningsSettings::setShowWarning(const QString& key, bool show)
{
setLocalValue(key, show);
}
{
public:
QtUiSettings();
- QtUiSettings(const QString &subGroup);
+ QtUiSettings(const QString& subGroup);
};
-
class QtUiStyleSettings : public UiSettings
{
public:
QtUiStyleSettings();
- QtUiStyleSettings(const QString &subGroup);
+ QtUiStyleSettings(const QString& subGroup);
};
-
class WarningsSettings : public UiSettings
{
public:
WarningsSettings();
- bool showWarning(const QString &key) const;
- void setShowWarning(const QString &key, bool show);
+ bool showWarning(const QString& key) const;
+ void setShowWarning(const QString& key, bool show);
};
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include "chatviewsettings.h"
#include "qtuistyle.h"
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
-QtUiStyle::QtUiStyle(QObject *parent) : UiStyle(parent)
+#include "chatviewsettings.h"
+
+QtUiStyle::QtUiStyle(QObject* parent)
+ : UiStyle(parent)
{
ChatViewSettings s;
s.initAndNotify("UseCustomTimestampFormat", this, &QtUiStyle::updateUseCustomTimestampFormat);
initializeSettingsQss();
}
-
void QtUiStyle::updateUseCustomTimestampFormat()
{
ChatViewSettings s;
enableSenderBrackets(s.showSenderBrackets());
}
-
void QtUiStyle::initializeSettingsQss()
{
QFileInfo settingsQss(Quassel::configDirPath() + "settings.qss");
{
QFile settingsQss(Quassel::configDirPath() + "settings.qss");
- if (!settingsQss.open(QFile::WriteOnly|QFile::Truncate)) {
+ if (!settingsQss.open(QFile::WriteOnly | QFile::Truncate)) {
qWarning() << "Could not open" << settingsQss.fileName() << "for writing!";
return;
}
if (s.value("UseChatViewColors").toBool()) {
out << "\n// Custom ChatView Colors\n"
- // markerline is special in that it always used to use a gradient, so we keep this behavior even with the new implementation
- << "Palette { marker-line: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 " << color("MarkerLine", s) << ", stop: 0.1 transparent); }\n"
- << "ChatView { background: " << color("ChatViewBackground", s) << "; }\n\n"
- << "ChatLine[label=\"highlight\"] {\n"
- << " foreground: " << color("Highlight", s) << ";\n"
- << " background: " << color("HighlightBackground", s) << ";\n"
- << "}\n\n"
- << "ChatLine::timestamp { foreground: " << color("Timestamp", s) << "; }\n\n"
-
- << msgTypeQss("plain", "ChannelMsg", s)
- << msgTypeQss("notice", "ServerMsg", s)
- << msgTypeQss("action", "ActionMsg", s)
- << msgTypeQss("nick", "CommandMsg", s)
- << msgTypeQss("mode", "CommandMsg", s)
- << msgTypeQss("join", "CommandMsg", s)
- << msgTypeQss("part", "CommandMsg", s)
- << msgTypeQss("quit", "CommandMsg", s)
- << msgTypeQss("kick", "CommandMsg", s)
- << msgTypeQss("kill", "CommandMsg", s)
- << msgTypeQss("server", "ServerMsg", s)
- << msgTypeQss("info", "ServerMsg", s)
- << msgTypeQss("error", "ErrorMsg", s)
- << msgTypeQss("daychange", "ServerMsg", s)
- << msgTypeQss("topic", "CommandMsg", s)
- << msgTypeQss("netsplit-join", "CommandMsg", s)
- << msgTypeQss("netsplit-quit", "CommandMsg", s)
- << msgTypeQss("invite", "CommandMsg", s)
- << "\n";
+ // markerline is special in that it always used to use a gradient, so we keep this behavior even with the new implementation
+ << "Palette { marker-line: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 " << color("MarkerLine", s)
+ << ", stop: 0.1 transparent); }\n"
+ << "ChatView { background: " << color("ChatViewBackground", s) << "; }\n\n"
+ << "ChatLine[label=\"highlight\"] {\n"
+ << " foreground: " << color("Highlight", s) << ";\n"
+ << " background: " << color("HighlightBackground", s) << ";\n"
+ << "}\n\n"
+ << "ChatLine::timestamp { foreground: " << color("Timestamp", s) << "; }\n\n"
+
+ << msgTypeQss("plain", "ChannelMsg", s) << msgTypeQss("notice", "ServerMsg", s) << msgTypeQss("action", "ActionMsg", s)
+ << msgTypeQss("nick", "CommandMsg", s) << msgTypeQss("mode", "CommandMsg", s) << msgTypeQss("join", "CommandMsg", s)
+ << msgTypeQss("part", "CommandMsg", s) << msgTypeQss("quit", "CommandMsg", s) << msgTypeQss("kick", "CommandMsg", s)
+ << msgTypeQss("kill", "CommandMsg", s) << msgTypeQss("server", "ServerMsg", s) << msgTypeQss("info", "ServerMsg", s)
+ << msgTypeQss("error", "ErrorMsg", s) << msgTypeQss("daychange", "ServerMsg", s) << msgTypeQss("topic", "CommandMsg", s)
+ << msgTypeQss("netsplit-join", "CommandMsg", s) << msgTypeQss("netsplit-quit", "CommandMsg", s)
+ << msgTypeQss("invite", "CommandMsg", s) << "\n";
}
if (s.value("UseSenderColors", true).toBool()) {
for (int i = 0; i < defaultSenderColors.count(); i++)
out << nickQss(i);
}
-
}
// ItemViews
if (uiColors.value("UseBufferViewColors").toBool()) {
out << "\n// BufferView Colors\n"
<< "ChatListItem { foreground: " << color("DefaultBuffer", uiColors) << "; }\n"
- << chatListItemQss("inactive", "InactiveBuffer", uiColors)
- << chatListItemQss("channel-event", "ActiveBuffer", uiColors)
- << chatListItemQss("unread-message", "UnreadBuffer", uiColors)
- << chatListItemQss("highlighted", "HighlightedBuffer", uiColors);
+ << chatListItemQss("inactive", "InactiveBuffer", uiColors) << chatListItemQss("channel-event", "ActiveBuffer", uiColors)
+ << chatListItemQss("unread-message", "UnreadBuffer", uiColors) << chatListItemQss("highlighted", "HighlightedBuffer", uiColors);
}
if (uiColors.value("UseNickViewColors").toBool()) {
settingsQss.close();
}
-
-QString QtUiStyle::color(const QString &key, UiSettings &settings, const QColor &defaultColor) const
+QString QtUiStyle::color(const QString& key, UiSettings& settings, const QColor& defaultColor) const
{
return settings.value(key, defaultColor).value<QColor>().name();
}
-
-QString QtUiStyle::fontDescription(const QFont &font) const
+QString QtUiStyle::fontDescription(const QFont& font) const
{
QFont::Style style = font.style();
int weight = font.weight();
return QString("font: %1 %2 %3pt \"%4\"")
- .arg(style == QFont::StyleItalic ? "italic" :
- style == QFont::StyleOblique ? "oblique" :
- "normal")
+ .arg(style == QFont::StyleItalic ? "italic" : style == QFont::StyleOblique ? "oblique" : "normal")
.arg(100 * qBound(1, (weight * 8 + 50) / 100, 9))
.arg(font.pointSize())
.arg(font.family());
}
-
-QString QtUiStyle::msgTypeQss(const QString &msgType, const QString &key, UiSettings &settings) const
+QString QtUiStyle::msgTypeQss(const QString& msgType, const QString& key, UiSettings& settings) const
{
return QString("ChatLine#%1 { foreground: %2; }\n").arg(msgType, color(key, settings));
}
-
-QString QtUiStyle::senderPaletteQss(UiSettings &settings) const
+QString QtUiStyle::senderPaletteQss(UiSettings& settings) const
{
QString result;
result += "Palette {\n";
// Generate entries for sender-color-self
- result += QString(" sender-color-self: %1;\n")
- .arg(color("SenderSelf", settings, defaultSenderColorSelf));
+ result += QString(" sender-color-self: %1;\n").arg(color("SenderSelf", settings, defaultSenderColorSelf));
// Generate entries for sender-color-HASH
for (int i = 0; i < defaultSenderColors.count(); i++) {
QString dez = QString::number(i);
- if (dez.length() == 1) dez.prepend('0');
- result += QString(" sender-color-0%1: %2;\n")
- .arg(QString::number(i, 16), color("Sender"+dez, settings, defaultSenderColors[i]));
+ if (dez.length() == 1)
+ dez.prepend('0');
+ result += QString(" sender-color-0%1: %2;\n").arg(QString::number(i, 16), color("Sender" + dez, settings, defaultSenderColors[i]));
}
result += "}\n\n";
return result;
}
-
-QString QtUiStyle::senderQss(int i, const QString &messageType, bool includeNick) const
+QString QtUiStyle::senderQss(int i, const QString& messageType, bool includeNick) const
{
QString dez = QString::number(i);
- if (dez.length() == 1) dez.prepend('0');
+ if (dez.length() == 1)
+ dez.prepend('0');
if (includeNick) {
// Include the nickname in the color rules
return QString("ChatLine::sender#%1[sender=\"0%2\"] { foreground: palette(sender-color-0%2); }\n"
"ChatLine::nick#%1[sender=\"0%2\"] { foreground: palette(sender-color-0%2); }\n")
- .arg(messageType, QString::number(i, 16));
- } else {
+ .arg(messageType, QString::number(i, 16));
+ }
+ else {
return QString("ChatLine::sender#%1[sender=\"0%2\"] { foreground: palette(sender-color-0%2); }\n")
- .arg(messageType, QString::number(i, 16));
+ .arg(messageType, QString::number(i, 16));
}
}
-
QString QtUiStyle::nickQss(int i) const
{
QString dez = QString::number(i);
- if (dez.length() == 1) dez.prepend('0');
+ if (dez.length() == 1)
+ dez.prepend('0');
- return QString("ChatLine::nick[sender=\"0%1\"] { foreground: palette(sender-color-0%1); }\n")
- .arg(QString::number(i, 16));
+ return QString("ChatLine::nick[sender=\"0%1\"] { foreground: palette(sender-color-0%1); }\n").arg(QString::number(i, 16));
}
-
-QString QtUiStyle::chatListItemQss(const QString &state, const QString &key, UiSettings &settings) const
+QString QtUiStyle::chatListItemQss(const QString& state, const QString& key, UiSettings& settings) const
{
return QString("ChatListItem[state=\"%1\"] { foreground: %2; }\n").arg(state, color(key, settings));
}
#ifndef QTUISTYLE_H_
#define QTUISTYLE_H_
-#include "uistyle.h"
#include "qtuisettings.h"
+#include "uistyle.h"
class QtUiStyle : public UiStyle
{
Q_OBJECT
public:
- QtUiStyle(QObject *parent = nullptr);
+ QtUiStyle(QObject* parent = nullptr);
virtual inline qreal firstColumnSeparator() const { return 6; }
virtual inline qreal secondColumnSeparator() const { return 6; }
void updateShowSenderBrackets();
private:
- QString fontDescription(const QFont &font) const;
+ QString fontDescription(const QFont& font) const;
/**
* Generate a Qt stylesheet color string from a given setting
* @param[in] settings UiSettings manager to search
* @param[in] defaultColor Fallback color if not found; when unspecified default is black
*/
- QString color(const QString &key, UiSettings &settings, const QColor &defaultColor = QColor()) const;
+ QString color(const QString& key, UiSettings& settings, const QColor& defaultColor = QColor()) const;
- QString msgTypeQss(const QString &msgType, const QString &key, UiSettings &settings) const;
+ QString msgTypeQss(const QString& msgType, const QString& key, UiSettings& settings) const;
/**
* Generates the Qss color palette stylesheet for sender colors
* @param[in] settings Reference to current UI settings, used for loading color values
* @return Quassel-theme-compatible Qss color palette
*/
- QString senderPaletteQss(UiSettings &settings) const;
+ QString senderPaletteQss(UiSettings& settings) const;
/**
* Generate a snippet of Qss stylesheet for a given sender-hash index
* @param[in] includeNick Also apply foreground color to Nick
* @return Snippet of Quassel-theme-compatible Qss stylesheet
*/
- QString senderQss(int i, const QString &messageType, bool includeNick = false) const;
+ QString senderQss(int i, const QString& messageType, bool includeNick = false) const;
/**
* Generate a snippet of Qss stylesheet for a given IRC nickname sender-hash index
*/
QString nickQss(int i) const;
- QString chatListItemQss(const QString &state, const QString &key, UiSettings &settings) const;
+ QString chatListItemQss(const QString& state, const QString& key, UiSettings& settings) const;
};
-
#endif
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "receivefiledlg.h"
+
#include <QDir>
#include <QFileDialog>
-#include "receivefiledlg.h"
-
#include "transfer.h"
-ReceiveFileDlg::ReceiveFileDlg(const Transfer *transfer, QWidget *parent)
- : QDialog(parent),
- _transfer(transfer)
+ReceiveFileDlg::ReceiveFileDlg(const Transfer* transfer, QWidget* parent)
+ : QDialog(parent)
+ , _transfer(transfer)
{
setAttribute(Qt::WA_DeleteOnClose);
ui.setupUi(this);
- QString label = tr("<b>%1</b> wants to send you a file:<br>%2 (%3 bytes)").arg(transfer->nick(), transfer->fileName()).arg(transfer->fileSize());
+ QString label
+ = tr("<b>%1</b> wants to send you a file:<br>%2 (%3 bytes)").arg(transfer->nick(), transfer->fileName()).arg(transfer->fileSize());
ui.infoText->setText(label);
}
-
-void ReceiveFileDlg::on_buttonBox_clicked(QAbstractButton *button)
+void ReceiveFileDlg::on_buttonBox_clicked(QAbstractButton* button)
{
if (ui.buttonBox->standardButton(button) == QDialogButtonBox::Save) {
QString name = QFileDialog::getSaveFileName(this, QString(), QDir::currentPath() + "/" + _transfer->fileName());
_transfer->accept(name);
}
-
}
Q_OBJECT
public:
- ReceiveFileDlg(const Transfer *transfer, QWidget *parent = nullptr);
+ ReceiveFileDlg(const Transfer* transfer, QWidget* parent = nullptr);
private slots:
- void on_buttonBox_clicked(QAbstractButton *button);
+ void on_buttonBox_clicked(QAbstractButton* button);
private:
Ui::ReceiveFileDlg ui;
- const Transfer *_transfer;
+ const Transfer* _transfer;
};
#endif
namespace {
-void addEntries(const QString &dir, AbstractTreeItem *parentItem) {
-
- auto entries = QDir{dir}.entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot, QDir::Name|QDir::DirsFirst);
- QList<AbstractTreeItem *> itemList;
- for (auto &&entry : entries) {
+void addEntries(const QString& dir, AbstractTreeItem* parentItem)
+{
+ auto entries = QDir{dir}.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot, QDir::Name | QDir::DirsFirst);
+ QList<AbstractTreeItem*> itemList;
+ for (auto&& entry : entries) {
auto item = new SimpleTreeItem({entry.fileName(), entry.size()}, parentItem);
itemList << item;
if (entry.isDir()) {
parentItem->newChilds(itemList);
}
-}
+} // namespace
-ResourceTreeDlg::ResourceTreeDlg(QWidget *parent)
+ResourceTreeDlg::ResourceTreeDlg(QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
Q_OBJECT
public:
- ResourceTreeDlg(QWidget *parent = nullptr);
+ ResourceTreeDlg(QWidget* parent = nullptr);
private:
Ui::ResourceTreeDlg ui;
#include "client.h"
#include "icon.h"
-SettingsDlg::SettingsDlg(QWidget *parent)
+SettingsDlg::SettingsDlg(QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
setButtonStates();
}
-
void SettingsDlg::coreConnectionStateChanged()
{
for (int i = 0; i < ui.settingsTree->topLevelItemCount(); i++) {
- QTreeWidgetItem *catItem = ui.settingsTree->topLevelItem(i);
+ QTreeWidgetItem* catItem = ui.settingsTree->topLevelItem(i);
for (int j = 0; j < catItem->childCount(); j++) {
- QTreeWidgetItem *item = catItem->child(j);
+ QTreeWidgetItem* item = catItem->child(j);
setItemState(item);
}
setItemState(catItem);
}
}
-
-void SettingsDlg::setItemState(QTreeWidgetItem *item)
+void SettingsDlg::setItemState(QTreeWidgetItem* item)
{
- auto *sp = qobject_cast<SettingsPage *>(item->data(0, SettingsPageRole).value<QObject *>());
+ auto* sp = qobject_cast<SettingsPage*>(item->data(0, SettingsPageRole).value<QObject*>());
Q_ASSERT(sp);
bool disabledDueToConnection = !Client::isConnected() && sp->needsCoreConnection();
bool disabledDueToOwnChoice = !sp->isSelectable();
item->setDisabled(disabledDueToConnection || disabledDueToOwnChoice);
}
-
-void SettingsDlg::registerSettingsPage(SettingsPage *sp)
+void SettingsDlg::registerSettingsPage(SettingsPage* sp)
{
sp->setParent(ui.settingsStack);
ui.settingsStack->addWidget(sp);
connect(sp, &SettingsPage::changed, this, &SettingsDlg::setButtonStates);
- QTreeWidgetItem *cat;
- QList<QTreeWidgetItem *> cats = ui.settingsTree->findItems(sp->category(), Qt::MatchExactly);
+ QTreeWidgetItem* cat;
+ QList<QTreeWidgetItem*> cats = ui.settingsTree->findItems(sp->category(), Qt::MatchExactly);
if (!cats.count()) {
cat = new QTreeWidgetItem(ui.settingsTree, QStringList(sp->category()));
cat->setExpanded(true);
cat = cats[0];
}
- QTreeWidgetItem *item;
+ QTreeWidgetItem* item;
if (sp->title().isEmpty())
item = cat;
else
item = new QTreeWidgetItem(cat, QStringList(sp->title()));
- item->setData(0, SettingsPageRole, QVariant::fromValue<QObject *>(sp));
+ item->setData(0, SettingsPageRole, QVariant::fromValue<QObject*>(sp));
pageIsLoaded[sp] = false;
if (!ui.settingsTree->selectedItems().count())
ui.settingsTree->setCurrentItem(item);
setItemState(item);
}
-
-void SettingsDlg::selectPage(SettingsPage *sp)
+void SettingsDlg::selectPage(SettingsPage* sp)
{
if (!sp) {
_currentPage = nullptr;
}
if (sp != currentPage() && currentPage() != nullptr && currentPage()->hasChanged()) {
- int ret = QMessageBox::warning(this, tr("Save changes"),
- tr("There are unsaved changes on the current configuration page. Would you like to apply your changes now?"),
- QMessageBox::Discard|QMessageBox::Save|QMessageBox::Cancel, QMessageBox::Cancel);
+ int ret = QMessageBox::
+ warning(this,
+ tr("Save changes"),
+ tr("There are unsaved changes on the current configuration page. Would you like to apply your changes now?"),
+ QMessageBox::Discard | QMessageBox::Save | QMessageBox::Cancel,
+ QMessageBox::Cancel);
if (ret == QMessageBox::Save) {
- if (!applyChanges()) sp = currentPage();
+ if (!applyChanges())
+ sp = currentPage();
}
else if (ret == QMessageBox::Discard) {
undoChanges();
}
- else sp = currentPage();
+ else
+ sp = currentPage();
}
if (sp != currentPage()) {
setButtonStates();
}
-
void SettingsDlg::itemSelected()
{
- QList<QTreeWidgetItem *> items = ui.settingsTree->selectedItems();
- SettingsPage *sp = nullptr;
+ QList<QTreeWidgetItem*> items = ui.settingsTree->selectedItems();
+ SettingsPage* sp = nullptr;
if (!items.isEmpty()) {
- sp = qobject_cast<SettingsPage *>(items[0]->data(0, SettingsPageRole).value<QObject *>());
+ sp = qobject_cast<SettingsPage*>(items[0]->data(0, SettingsPageRole).value<QObject*>());
}
selectPage(sp);
}
-
void SettingsDlg::setButtonStates()
{
- SettingsPage *sp = currentPage();
+ SettingsPage* sp = currentPage();
ui.buttonBox->button(QDialogButtonBox::Apply)->setEnabled(sp && sp->hasChanged());
ui.buttonBox->button(QDialogButtonBox::Reset)->setEnabled(sp && sp->hasChanged());
ui.buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(sp && sp->hasDefaults());
}
-
-void SettingsDlg::buttonClicked(QAbstractButton *button)
+void SettingsDlg::buttonClicked(QAbstractButton* button)
{
switch (ui.buttonBox->standardButton(button)) {
case QDialogButtonBox::Ok:
if (currentPage() && currentPage()->hasChanged()) {
- if (applyChanges()) accept();
+ if (applyChanges())
+ accept();
}
- else accept();
+ else
+ accept();
break;
case QDialogButtonBox::Apply:
applyChanges();
}
}
-
bool SettingsDlg::applyChanges()
{
- if (!currentPage()) return false;
+ if (!currentPage())
+ return false;
if (currentPage()->aboutToSave()) {
currentPage()->save();
return true;
return false;
}
-
void SettingsDlg::undoChanges()
{
if (currentPage()) {
}
}
-
void SettingsDlg::reload()
{
- if (!currentPage()) return;
- int ret = QMessageBox::question(this, tr("Reload Settings"), tr("Do you like to reload the settings, undoing your changes on this page?"),
- QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
+ if (!currentPage())
+ return;
+ int ret = QMessageBox::question(this,
+ tr("Reload Settings"),
+ tr("Do you like to reload the settings, undoing your changes on this page?"),
+ QMessageBox::Yes | QMessageBox::No,
+ QMessageBox::No);
if (ret == QMessageBox::Yes) {
currentPage()->load();
}
}
-
void SettingsDlg::loadDefaults()
{
- if (!currentPage()) return;
- int ret = QMessageBox::question(this, tr("Restore Defaults"), tr("Do you like to restore the default values for this page?"),
- QMessageBox::RestoreDefaults|QMessageBox::Cancel, QMessageBox::Cancel);
+ if (!currentPage())
+ return;
+ int ret = QMessageBox::question(this,
+ tr("Restore Defaults"),
+ tr("Do you like to restore the default values for this page?"),
+ QMessageBox::RestoreDefaults | QMessageBox::Cancel,
+ QMessageBox::Cancel);
if (ret == QMessageBox::RestoreDefaults) {
currentPage()->defaults();
}
#include <QDialog>
-#include "ui_settingsdlg.h"
-
#include "settingspage.h"
+#include "ui_settingsdlg.h"
+
class SettingsDlg : public QDialog
{
Q_OBJECT
public:
- SettingsDlg(QWidget *parent = nullptr);
- void registerSettingsPage(SettingsPage *);
- void unregisterSettingsPage(SettingsPage *);
+ SettingsDlg(QWidget* parent = nullptr);
+ void registerSettingsPage(SettingsPage*);
+ void unregisterSettingsPage(SettingsPage*);
- inline SettingsPage *currentPage() const { return _currentPage; }
+ inline SettingsPage* currentPage() const { return _currentPage; }
public slots:
- void selectPage(SettingsPage *sp); // const QString &category, const QString &title);
+ void selectPage(SettingsPage* sp); // const QString &category, const QString &title);
private slots:
void coreConnectionStateChanged();
void itemSelected();
- void buttonClicked(QAbstractButton *);
+ void buttonClicked(QAbstractButton*);
bool applyChanges();
void undoChanges();
void reload();
void loadDefaults();
void setButtonStates();
- void setItemState(QTreeWidgetItem *);
+ void setItemState(QTreeWidgetItem*);
private:
Ui::SettingsDlg ui;
- SettingsPage *_currentPage{nullptr};
- QHash<SettingsPage *, bool> pageIsLoaded;
+ SettingsPage* _currentPage{nullptr};
+ QHash<SettingsPage*, bool> pageIsLoaded;
- enum {
+ enum
+ {
SettingsPageRole = Qt::UserRole
};
};
-
#endif
#include "icon.h"
-SettingsPageDlg::SettingsPageDlg(SettingsPage *page, QWidget *parent)
+SettingsPageDlg::SettingsPageDlg(SettingsPage* page, QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
setButtonStates();
}
-
-SettingsPage *SettingsPageDlg::currentPage() const
+SettingsPage* SettingsPageDlg::currentPage() const
{
return _currentPage;
}
-
void SettingsPageDlg::setButtonStates()
{
- SettingsPage *sp = currentPage();
+ SettingsPage* sp = currentPage();
ui.buttonBox->button(QDialogButtonBox::Apply)->setEnabled(sp && sp->hasChanged());
ui.buttonBox->button(QDialogButtonBox::Reset)->setEnabled(sp && sp->hasChanged());
ui.buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(sp && sp->hasDefaults());
}
-
-void SettingsPageDlg::buttonClicked(QAbstractButton *button)
+void SettingsPageDlg::buttonClicked(QAbstractButton* button)
{
switch (ui.buttonBox->standardButton(button)) {
case QDialogButtonBox::Ok:
if (currentPage() && currentPage()->hasChanged()) {
- if (applyChanges()) accept();
+ if (applyChanges())
+ accept();
}
- else accept();
+ else
+ accept();
break;
case QDialogButtonBox::Apply:
applyChanges();
}
}
-
bool SettingsPageDlg::applyChanges()
{
- if (!currentPage()) return false;
+ if (!currentPage())
+ return false;
if (currentPage()->aboutToSave()) {
currentPage()->save();
return true;
return false;
}
-
void SettingsPageDlg::undoChanges()
{
if (currentPage()) {
}
}
-
void SettingsPageDlg::reload()
{
- if (!currentPage()) return;
- int ret = QMessageBox::question(this, tr("Reload Settings"), tr("Do you like to reload the settings, undoing your changes on this page?"),
- QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
+ if (!currentPage())
+ return;
+ int ret = QMessageBox::question(this,
+ tr("Reload Settings"),
+ tr("Do you like to reload the settings, undoing your changes on this page?"),
+ QMessageBox::Yes | QMessageBox::No,
+ QMessageBox::No);
if (ret == QMessageBox::Yes) {
currentPage()->load();
}
}
-
void SettingsPageDlg::loadDefaults()
{
- if (!currentPage()) return;
- int ret = QMessageBox::question(this, tr("Restore Defaults"), tr("Do you like to restore the default values for this page?"),
- QMessageBox::RestoreDefaults|QMessageBox::Cancel, QMessageBox::Cancel);
+ if (!currentPage())
+ return;
+ int ret = QMessageBox::question(this,
+ tr("Restore Defaults"),
+ tr("Do you like to restore the default values for this page?"),
+ QMessageBox::RestoreDefaults | QMessageBox::Cancel,
+ QMessageBox::Cancel);
if (ret == QMessageBox::RestoreDefaults) {
currentPage()->defaults();
}
#include <QDialog>
-#include "ui_settingspagedlg.h"
-
#include "settingspage.h"
+#include "ui_settingspagedlg.h"
+
class SettingsPageDlg : public QDialog
{
Q_OBJECT
public:
- SettingsPageDlg(SettingsPage *page, QWidget *parent = nullptr);
+ SettingsPageDlg(SettingsPage* page, QWidget* parent = nullptr);
- SettingsPage *currentPage() const;
+ SettingsPage* currentPage() const;
private slots:
- void buttonClicked(QAbstractButton *);
+ void buttonClicked(QAbstractButton*);
bool applyChanges();
void undoChanges();
void reload();
private:
Ui::SettingsPageDlg ui;
- SettingsPage *_currentPage;
+ SettingsPage* _currentPage;
};
-
#endif
#include "client.h"
#include "signalproxy.h"
-AliasesModel::AliasesModel(QObject *parent)
+AliasesModel::AliasesModel(QObject* parent)
: QAbstractItemModel(parent)
{
// we need this signal for future connects to reset the data;
emit modelReady(false);
}
-
-QVariant AliasesModel::data(const QModelIndex &index, int role) const
+QVariant AliasesModel::data(const QModelIndex& index, int role) const
{
if (!_modelReady)
return QVariant();
return tr("<b>The shortcut for the alias</b><br />"
"It can be used as a regular slash command.<br /><br />"
"<b>Example:</b> \"foo\" can be used per /foo");
- case 1:
- {
+ case 1: {
// To avoid overwhelming the user, organize things into a table
QString strTooltip;
- QTextStream tooltip( &strTooltip, QIODevice::WriteOnly );
+ QTextStream tooltip(&strTooltip, QIODevice::WriteOnly);
tooltip << "<qt><style>.bold { font-weight: bold; } .italic { font-style: italic; }</style>";
// Function to add a row to the tooltip table
- auto addRow = [&](
- const QString& key, const QString& value = QString(), bool condition = true) {
+ auto addRow = [&](const QString& key, const QString& value = QString(), bool condition = true) {
if (condition) {
if (value.isEmpty()) {
- tooltip << "<tr><td class='italic' align='left' colspan='2'>"
- << key << "</td></tr>";
- } else {
- tooltip << "<tr><td class='bold' align='left'>"
- << key << "</td><td>" << value << "</td></tr>";
+ tooltip << "<tr><td class='italic' align='left' colspan='2'>" << key << "</td></tr>";
+ }
+ else {
+ tooltip << "<tr><td class='bold' align='left'>" << key << "</td><td>" << value << "</td></tr>";
}
}
};
- tooltip << "<p class='bold'>"
- << tr("The string the shortcut will be expanded to") << "</p>";
+ tooltip << "<p class='bold'>" << tr("The string the shortcut will be expanded to") << "</p>";
- tooltip << "<p class='bold' align='center'>"
- << tr("Special variables") << "</p>";
+ tooltip << "<p class='bold' align='center'>" << tr("Special variables") << "</p>";
// Variable option table
tooltip << "<table cellspacing='5' cellpadding='0'>";
addRow("$i:account",
tr("account of user identified by i'th parameter, or a '*' if logged out or "
"unknown"));
- addRow("$i:hostname",
- tr("hostname of user identified by i'th parameter, or a '*' if unknown"));
- addRow("$i:ident",
- tr("ident of user identified by i'th parameter, or a '*' if unknown"));
+ addRow("$i:hostname", tr("hostname of user identified by i'th parameter, or a '*' if unknown"));
+ addRow("$i:ident", tr("ident of user identified by i'th parameter, or a '*' if unknown"));
addRow("$i:identd",
tr("ident of user identified by i'th parameter if verified, or a '*' if unknown "
"or unverified (prefixed with '~')"));
tooltip << "</table>";
// Example header
- tooltip << "<p>"
- << tr("Multiple commands can be separated with semicolons") << "</p>";
+ tooltip << "<p>" << tr("Multiple commands can be separated with semicolons") << "</p>";
// Example
tooltip << "<p>";
- tooltip << QString("<p><span class='bold'>%1</span> %2<br />").arg(
- tr("Example:"), tr("\"Test $1; Test $2; Test All $0\""));
+ tooltip << QString("<p><span class='bold'>%1</span> %2<br />").arg(tr("Example:"), tr("\"Test $1; Test $2; Test All $0\""));
tooltip << tr("...will be expanded to three separate messages \"Test 1\", \"Test 2\" "
"and \"Test All 1 2 3\" when called like <i>/test 1 2 3</i>")
<< "</p>";
}
}
-
-bool AliasesModel::setData(const QModelIndex &index, const QVariant &value, int role)
+bool AliasesModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!_modelReady)
return false;
}
}
-
void AliasesModel::newAlias()
{
QString newName("alias");
int i = 0;
- AliasManager &manager = cloneAliasManager();
+ AliasManager& manager = cloneAliasManager();
while (manager.contains(newName)) {
i++;
newName = QString("alias%1").arg(i);
endInsertRows();
}
-
void AliasesModel::loadDefaults()
{
if (!_modelReady)
return;
- AliasManager &manager = cloneAliasManager();
+ AliasManager& manager = cloneAliasManager();
if (!manager.isEmpty()) {
beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
AliasManager::AliasList defaults = AliasManager::defaults();
beginInsertRows(QModelIndex(), 0, defaults.count() - 1);
- foreach(AliasManager::Alias alias, defaults) {
+ foreach (AliasManager::Alias alias, defaults) {
manager.addAlias(alias.name, alias.expansion);
}
endInsertRows();
}
-
void AliasesModel::removeAlias(int index)
{
if (index < 0 || index >= rowCount())
return;
- AliasManager &manager = cloneAliasManager();
+ AliasManager& manager = cloneAliasManager();
beginRemoveRows(QModelIndex(), index, index);
manager.removeAt(index);
endRemoveRows();
}
-
-Qt::ItemFlags AliasesModel::flags(const QModelIndex &index) const
+Qt::ItemFlags AliasesModel::flags(const QModelIndex& index) const
{
if (!index.isValid()) {
return Qt::ItemIsDropEnabled;
}
}
-
QVariant AliasesModel::headerData(int section, Qt::Orientation orientation, int role) const
{
QStringList header;
- header << tr("Alias")
- << tr("Expansion");
+ header << tr("Alias") << tr("Expansion");
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return header[section];
return QVariant();
}
-
-QModelIndex AliasesModel::index(int row, int column, const QModelIndex &parent) const
+QModelIndex AliasesModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
if (row >= rowCount() || column >= columnCount())
return createIndex(row, column);
}
-
-const AliasManager &AliasesModel::aliasManager() const
+const AliasManager& AliasesModel::aliasManager() const
{
if (_configChanged)
return _clonedAliasManager;
return *Client::aliasManager();
}
-
-AliasManager &AliasesModel::aliasManager()
+AliasManager& AliasesModel::aliasManager()
{
if (_configChanged)
return _clonedAliasManager;
return *Client::aliasManager();
}
-
-AliasManager &AliasesModel::cloneAliasManager()
+AliasManager& AliasesModel::cloneAliasManager()
{
if (!_configChanged) {
_clonedAliasManager = *Client::aliasManager();
return _clonedAliasManager;
}
-
void AliasesModel::revert()
{
if (!_configChanged)
endResetModel();
}
-
void AliasesModel::commit()
{
if (!_configChanged)
revert();
}
-
void AliasesModel::initDone()
{
_modelReady = true;
emit modelReady(true);
}
-
void AliasesModel::clientConnected()
{
connect(Client::aliasManager(), &AliasManager::updated, this, &AliasesModel::revert);
connect(Client::aliasManager(), &SyncableObject::initDone, this, &AliasesModel::initDone);
}
-
void AliasesModel::clientDisconnected()
{
// clear
Q_OBJECT
public:
- AliasesModel(QObject *parent = nullptr);
+ AliasesModel(QObject* parent = nullptr);
- QVariant data(const QModelIndex &index, int role) const override;
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
+ QVariant data(const QModelIndex& index, int role) const override;
+ bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override;
- Qt::ItemFlags flags(const QModelIndex &index) 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;
- inline int columnCount(const QModelIndex &parent = QModelIndex()) const override;
+ inline int rowCount(const QModelIndex& parent = QModelIndex()) const override;
+ inline int columnCount(const QModelIndex& parent = QModelIndex()) const override;
inline bool hasConfigChanged() const { return _configChanged; }
inline bool isReady() const { return _modelReady; }
bool _configChanged{false};
bool _modelReady{false};
- const AliasManager &aliasManager() const;
- AliasManager &aliasManager();
- AliasManager &cloneAliasManager();
+ const AliasManager& aliasManager() const;
+ AliasManager& aliasManager();
+ AliasManager& cloneAliasManager();
private slots:
void clientConnected();
void initDone();
};
-
// Inlines
-int AliasesModel::rowCount(const QModelIndex &parent) const
+int AliasesModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return isReady() ? aliasManager().count() : 0;
}
-
-int AliasesModel::columnCount(const QModelIndex &parent) const
+int AliasesModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return isReady() ? 2 : 0;
}
-
-#endif //ALIASESMODEL_H
+#endif // ALIASESMODEL_H
#include "icon.h"
-AliasesSettingsPage::AliasesSettingsPage(QWidget *parent)
+AliasesSettingsPage::AliasesSettingsPage(QWidget* parent)
: SettingsPage(tr("IRC"), tr("Aliases"), parent)
{
ui.setupUi(this);
enableDialog(_aliasesModel.isReady());
}
-
void AliasesSettingsPage::load()
{
if (_aliasesModel.hasConfigChanged())
_aliasesModel.revert();
}
-
void AliasesSettingsPage::defaults()
{
_aliasesModel.loadDefaults();
}
-
void AliasesSettingsPage::save()
{
if (_aliasesModel.hasConfigChanged())
_aliasesModel.commit();
}
-
void AliasesSettingsPage::enableDialog(bool enabled)
{
ui.newAliasButton->setEnabled(enabled);
setEnabled(enabled);
}
-
void AliasesSettingsPage::deleteSelectedAlias()
{
if (!ui.aliasesView->selectionModel()->hasSelection())
#ifndef ALIASESSETTINGSPAGE_H
#define ALIASESSETTINGSPAGE_H
+#include "aliasesmodel.h"
#include "settingspage.h"
-#include "ui_aliasessettingspage.h"
-#include "aliasesmodel.h"
+#include "ui_aliasessettingspage.h"
class AliasesSettingsPage : public SettingsPage
{
Q_OBJECT
public:
- AliasesSettingsPage(QWidget *parent = nullptr);
+ AliasesSettingsPage(QWidget* parent = nullptr);
inline bool hasDefaults() const override { return true; }
inline bool needsCoreConnection() const override { return true; }
AliasesModel _aliasesModel;
};
-
-#endif //ALIASESSETTINGSPAGE_H
+#endif // ALIASESSETTINGSPAGE_H
#include "qtuisettings.h"
#include "qtuistyle.h"
-
-AppearanceSettingsPage::AppearanceSettingsPage(QWidget *parent)
+AppearanceSettingsPage::AppearanceSettingsPage(QWidget* parent)
: SettingsPage(tr("Interface"), QString(), parent)
{
ui.setupUi(this);
initLanguageComboBox();
initIconThemeComboBox();
- foreach(QComboBox *comboBox, findChildren<QComboBox *>()) {
+ foreach (QComboBox* comboBox, findChildren<QComboBox*>()) {
connect(comboBox, selectOverload<const QString&>(&QComboBox::currentIndexChanged), this, &AppearanceSettingsPage::widgetHasChanged);
}
- foreach(QCheckBox *checkBox, findChildren<QCheckBox *>()) {
+ foreach (QCheckBox* checkBox, findChildren<QCheckBox*>()) {
connect(checkBox, &QAbstractButton::clicked, this, &AppearanceSettingsPage::widgetHasChanged);
}
connect(ui.errorMsgsInCurrentBuffer, &QAbstractButton::clicked, this, &AppearanceSettingsPage::widgetHasChanged);
}
-
void AppearanceSettingsPage::initStyleComboBox()
{
QStringList styleList = QStyleFactory::keys();
ui.styleComboBox->addItem(tr("<System Default>"));
- foreach(QString style, styleList) {
+ foreach (QString style, styleList) {
ui.styleComboBox->addItem(style);
}
}
-
void AppearanceSettingsPage::initLanguageComboBox()
{
QDir i18nDir(Quassel::translationDirPath(), "*.qm");
QRegExp rx("(qt_)?([a-zA-Z_]+)\\.qm");
- foreach(QString translationFile, i18nDir.entryList()) {
+ foreach (QString translationFile, i18nDir.entryList()) {
if (!rx.exactMatch(translationFile))
continue;
if (!rx.cap(1).isEmpty())
QLocale locale(rx.cap(2));
_locales[QLocale::languageToString(locale.language())] = locale;
}
- foreach(QString language, _locales.keys()) {
+ foreach (QString language, _locales.keys()) {
ui.languageComboBox->addItem(language);
}
}
auto availableThemes = QtUi::instance()->availableIconThemes();
ui.iconThemeComboBox->addItem(tr("Automatic"), QString{});
- for (auto &&p : QtUi::instance()->availableIconThemes()) {
+ for (auto&& p : QtUi::instance()->availableIconThemes()) {
ui.iconThemeComboBox->addItem(p.second, p.first);
}
}
-
void AppearanceSettingsPage::defaults()
{
ui.styleComboBox->setCurrentIndex(0);
widgetHasChanged();
}
-
void AppearanceSettingsPage::load()
{
QtUiSettings uiSettings;
QLocale locale = uiSettings.value("Locale", QLocale::system()).value<QLocale>();
if (locale == QLocale::system())
ui.languageComboBox->setCurrentIndex(1);
- else if (locale.language() == QLocale::C) // we use C for "untranslated"
+ else if (locale.language() == QLocale::C) // we use C for "untranslated"
ui.languageComboBox->setCurrentIndex(0);
else
ui.languageComboBox->setCurrentIndex(ui.languageComboBox->findText(QLocale::languageToString(locale.language()), Qt::MatchExactly));
setChangedState(false);
}
-
void AppearanceSettingsPage::save()
{
QtUiSettings uiSettings;
ui.styleComboBox->setProperty("storedValue", ui.styleComboBox->currentIndex());
if (ui.languageComboBox->currentIndex() == 1) {
- uiSettings.remove("Locale"); // force the default (QLocale::system())
+ uiSettings.remove("Locale"); // force the default (QLocale::system())
}
else {
uiSettings.setValue("Locale", selectedLocale());
ui.languageComboBox->setProperty("storedValue", ui.languageComboBox->currentIndex());
bool needsIconThemeRefresh = ui.iconThemeComboBox->currentIndex() != ui.iconThemeComboBox->property("storedValue").toInt()
- || ui.overrideSystemIconTheme->isChecked() != ui.overrideSystemIconTheme->property("storedValue").toBool();
+ || ui.overrideSystemIconTheme->isChecked() != ui.overrideSystemIconTheme->property("storedValue").toBool();
auto iconTheme = selectedIconTheme();
if (iconTheme.isEmpty()) {
}
ui.iconThemeComboBox->setProperty("storedValue", ui.iconThemeComboBox->currentIndex());
- bool needsStyleReload =
- ui.useCustomStyleSheet->isChecked() != ui.useCustomStyleSheet->property("storedValue").toBool()
- || (ui.useCustomStyleSheet->isChecked() && ui.customStyleSheetPath->text() != ui.customStyleSheetPath->property("storedValue").toString());
+ bool needsStyleReload = ui.useCustomStyleSheet->isChecked() != ui.useCustomStyleSheet->property("storedValue").toBool()
+ || (ui.useCustomStyleSheet->isChecked()
+ && ui.customStyleSheetPath->text() != ui.customStyleSheetPath->property("storedValue").toString());
BufferSettings bufferSettings;
int redirectTarget = 0;
QtUi::instance()->refreshIconTheme();
}
-
QLocale AppearanceSettingsPage::selectedLocale() const
{
QLocale locale;
return locale;
}
-
QString AppearanceSettingsPage::selectedIconTheme() const
{
return ui.iconThemeComboBox->itemData(ui.iconThemeComboBox->currentIndex()).toString();
}
-
void AppearanceSettingsPage::chooseStyleSheet()
{
QString dir = ui.customStyleSheetPath->property("storedValue").toString();
ui.customStyleSheetPath->setText(name);
}
-
void AppearanceSettingsPage::widgetHasChanged()
{
setChangedState(testHasChanged());
}
-
bool AppearanceSettingsPage::testHasChanged()
{
- if (ui.styleComboBox->currentIndex() != ui.styleComboBox->property("storedValue").toInt()) return true;
- if (ui.languageComboBox->currentIndex() != ui.languageComboBox->property("storedValue").toInt()) return true;
- if (ui.iconThemeComboBox->currentIndex() != ui.iconThemeComboBox->property("storedValue").toInt()) return true;
-
- if (SettingsPage::hasChanged(ui.userNoticesInStatusBuffer)) return true;
- if (SettingsPage::hasChanged(ui.userNoticesInDefaultBuffer)) return true;
- if (SettingsPage::hasChanged(ui.userNoticesInCurrentBuffer)) return true;
-
- if (SettingsPage::hasChanged(ui.serverNoticesInStatusBuffer)) return true;
- if (SettingsPage::hasChanged(ui.serverNoticesInDefaultBuffer)) return true;
- if (SettingsPage::hasChanged(ui.serverNoticesInCurrentBuffer)) return true;
-
- if (SettingsPage::hasChanged(ui.errorMsgsInStatusBuffer)) return true;
- if (SettingsPage::hasChanged(ui.errorMsgsInDefaultBuffer)) return true;
- if (SettingsPage::hasChanged(ui.errorMsgsInCurrentBuffer)) return true;
+ if (ui.styleComboBox->currentIndex() != ui.styleComboBox->property("storedValue").toInt())
+ return true;
+ if (ui.languageComboBox->currentIndex() != ui.languageComboBox->property("storedValue").toInt())
+ return true;
+ if (ui.iconThemeComboBox->currentIndex() != ui.iconThemeComboBox->property("storedValue").toInt())
+ return true;
+
+ if (SettingsPage::hasChanged(ui.userNoticesInStatusBuffer))
+ return true;
+ if (SettingsPage::hasChanged(ui.userNoticesInDefaultBuffer))
+ return true;
+ if (SettingsPage::hasChanged(ui.userNoticesInCurrentBuffer))
+ return true;
+
+ if (SettingsPage::hasChanged(ui.serverNoticesInStatusBuffer))
+ return true;
+ if (SettingsPage::hasChanged(ui.serverNoticesInDefaultBuffer))
+ return true;
+ if (SettingsPage::hasChanged(ui.serverNoticesInCurrentBuffer))
+ return true;
+
+ if (SettingsPage::hasChanged(ui.errorMsgsInStatusBuffer))
+ return true;
+ if (SettingsPage::hasChanged(ui.errorMsgsInDefaultBuffer))
+ return true;
+ if (SettingsPage::hasChanged(ui.errorMsgsInCurrentBuffer))
+ return true;
return false;
}
#include "settings.h"
#include "settingspage.h"
+
#include "ui_appearancesettingspage.h"
class AppearanceSettingsPage : public SettingsPage
Q_OBJECT
public:
- AppearanceSettingsPage(QWidget *parent = nullptr);
+ AppearanceSettingsPage(QWidget* parent = nullptr);
inline bool hasDefaults() const override { return true; }
inline QString settingsKey() const override { return QString("QtUi"); }
};
-
#endif
#include "backlogsettingspage.h"
-#include "backlogsettings.h"
#include "backlogrequester.h"
+#include "backlogsettings.h"
#include "qtui.h"
#include "widgethelpers.h"
-BacklogSettingsPage::BacklogSettingsPage(QWidget *parent)
+BacklogSettingsPage::BacklogSettingsPage(QWidget* parent)
: SettingsPage(tr("Interface"), tr("Backlog Fetching"), parent)
{
ui.setupUi(this);
connectToWidgetChangedSignal(ui.requesterType, this, &BacklogSettingsPage::widgetHasChanged);
}
-
bool BacklogSettingsPage::hasDefaults() const
{
return true;
}
-
void BacklogSettingsPage::defaults()
{
ui.requesterType->setCurrentIndex(BacklogRequester::PerBufferUnread - 1);
SettingsPage::defaults();
}
-
void BacklogSettingsPage::load()
{
BacklogSettings backlogSettings;
SettingsPage::load();
}
-
void BacklogSettingsPage::save()
{
BacklogSettings backlogSettings;
SettingsPage::save();
}
-
void BacklogSettingsPage::widgetHasChanged()
{
setChangedState(ui.requesterType->currentIndex() != ui.requesterType->property("storedValue").toInt());
#include <QHash>
#include "settingspage.h"
+
#include "ui_backlogsettingspage.h"
class BacklogSettingsPage : public SettingsPage
Q_OBJECT
public:
- BacklogSettingsPage(QWidget *parent = nullptr);
+ BacklogSettingsPage(QWidget* parent = nullptr);
inline QString settingsKey() const override { return "Backlog"; }
bool hasDefaults() const override;
Ui::BacklogSettingsPage ui;
};
-
#endif
#include "bufferviewsettingspage.h"
-#include <QMessageBox>
#include <utility>
+#include <QMessageBox>
+
#include "buffermodel.h"
#include "bufferviewconfig.h"
#include "bufferviewfilter.h"
#include "networkmodel.h"
#include "util.h"
-BufferViewSettingsPage::BufferViewSettingsPage(QWidget *parent)
+BufferViewSettingsPage::BufferViewSettingsPage(QWidget* parent)
: SettingsPage(tr("Interface"), tr("Custom Chat Lists"), parent)
{
ui.setupUi(this);
- //Hide the hide inactive networks feature on older cores (which won't save the setting)
+ // Hide the hide inactive networks feature on older cores (which won't save the setting)
if (!Client::isCoreFeatureEnabled(Quassel::Feature::HideInactiveNetworks))
ui.hideInactiveNetworks->hide();
ui.settingsGroupBox->setEnabled(false);
ui.bufferViewPreview->setEnabled(false);
- coreConnectionStateChanged(Client::isConnected()); // need a core connection!
+ coreConnectionStateChanged(Client::isConnected()); // need a core connection!
connect(Client::instance(), &Client::coreConnectionStateChanged, this, &BufferViewSettingsPage::coreConnectionStateChanged);
- connect(ui.bufferViewList->selectionModel(), &QItemSelectionModel::selectionChanged,
- this, &BufferViewSettingsPage::bufferViewSelectionChanged);
+ connect(ui.bufferViewList->selectionModel(),
+ &QItemSelectionModel::selectionChanged,
+ this,
+ &BufferViewSettingsPage::bufferViewSelectionChanged);
connect(ui.onlyStatusBuffers, &QAbstractButton::clicked, this, &BufferViewSettingsPage::widgetHasChanged);
connect(ui.onlyChannelBuffers, &QAbstractButton::clicked, this, &BufferViewSettingsPage::widgetHasChanged);
connect(ui.networkSelector, selectOverload<int>(&QComboBox::currentIndexChanged), this, &BufferViewSettingsPage::enableStatusBuffers);
}
-
BufferViewSettingsPage::~BufferViewSettingsPage()
{
reset();
}
-
void BufferViewSettingsPage::reset()
{
ui.bufferViewList->clear();
ui.deleteBufferView->setEnabled(false);
- QHash<BufferViewConfig *, BufferViewConfig *>::iterator changedConfigIter = _changedBufferViews.begin();
- QHash<BufferViewConfig *, BufferViewConfig *>::iterator changedConfigIterEnd = _changedBufferViews.end();
- BufferViewConfig *config;
+ QHash<BufferViewConfig*, BufferViewConfig*>::iterator changedConfigIter = _changedBufferViews.begin();
+ QHash<BufferViewConfig*, BufferViewConfig*>::iterator changedConfigIterEnd = _changedBufferViews.end();
+ BufferViewConfig* config;
while (changedConfigIter != changedConfigIterEnd) {
config = changedConfigIter.value();
changedConfigIter = _changedBufferViews.erase(changedConfigIter);
config->deleteLater();
}
- QList<BufferViewConfig *>::iterator newConfigIter = _newBufferViews.begin();
- QList<BufferViewConfig *>::iterator newConfigIterEnd = _newBufferViews.end();
+ QList<BufferViewConfig*>::iterator newConfigIter = _newBufferViews.begin();
+ QList<BufferViewConfig*>::iterator newConfigIterEnd = _newBufferViews.end();
while (newConfigIter != newConfigIterEnd) {
config = *newConfigIter;
newConfigIter = _newBufferViews.erase(newConfigIter);
setChangedState(false);
}
-
void BufferViewSettingsPage::load()
{
bool useBufferViewHint = _useBufferViewHint;
if (!Client::bufferViewManager())
return;
- const QList<BufferViewConfig *> bufferViewConfigs = Client::bufferViewManager()->bufferViewConfigs();
- foreach(BufferViewConfig *bufferViewConfig, bufferViewConfigs) {
+ const QList<BufferViewConfig*> bufferViewConfigs = Client::bufferViewManager()->bufferViewConfigs();
+ foreach (BufferViewConfig* bufferViewConfig, bufferViewConfigs) {
addBufferView(bufferViewConfig);
}
ui.networkSelector->clear();
ui.networkSelector->addItem(tr("All"));
ui.networkSelector->setItemData(0, qVariantFromValue<NetworkId>(NetworkId()));
- const Network *net;
- foreach(NetworkId netId, Client::networkIds()) {
+ const Network* net;
+ foreach (NetworkId netId, Client::networkIds()) {
net = Client::network(netId);
ui.networkSelector->addItem(net->networkName());
ui.networkSelector->setItemData(ui.networkSelector->count() - 1, qVariantFromValue<NetworkId>(net->networkId()));
ui.bufferViewList->setCurrentRow(0);
}
-
void BufferViewSettingsPage::save()
{
setEnabled(false);
- BufferViewConfig *currentConfig = bufferView(ui.bufferViewList->currentRow());
+ BufferViewConfig* currentConfig = bufferView(ui.bufferViewList->currentRow());
if (currentConfig) {
_useBufferViewHint = true;
_bufferViewHint = currentConfig->bufferViewId();
QVariantList deleteConfigs;
QVariantList changedConfigs;
- foreach(int bufferId, _deleteBufferViews) {
+ foreach (int bufferId, _deleteBufferViews) {
deleteConfigs << bufferId;
}
_deleteBufferViews.clear();
Client::bufferViewManager()->requestDeleteBufferViews(deleteConfigs);
}
- QHash<BufferViewConfig *, BufferViewConfig *>::iterator changedConfigIter = _changedBufferViews.begin();
- QHash<BufferViewConfig *, BufferViewConfig *>::iterator changedConfigIterEnd = _changedBufferViews.end();
+ QHash<BufferViewConfig*, BufferViewConfig*>::iterator changedConfigIter = _changedBufferViews.begin();
+ QHash<BufferViewConfig*, BufferViewConfig*>::iterator changedConfigIterEnd = _changedBufferViews.end();
BufferViewConfig *config, *changedConfig;
while (changedConfigIter != changedConfigIterEnd) {
config = changedConfigIter.key();
changedConfig->deleteLater();
}
- QList<BufferViewConfig *>::iterator newConfigIter = _newBufferViews.begin();
- QList<BufferViewConfig *>::iterator newConfigIterEnd = _newBufferViews.end();
+ QList<BufferViewConfig*>::iterator newConfigIter = _newBufferViews.begin();
+ QList<BufferViewConfig*>::iterator newConfigIterEnd = _newBufferViews.end();
while (newConfigIter != newConfigIterEnd) {
config = *newConfigIter;
newConfigIter = _newBufferViews.erase(newConfigIter);
setEnabled(true);
}
-
void BufferViewSettingsPage::coreConnectionStateChanged(bool state)
{
setEnabled(state);
if (state) {
load();
- connect(Client::bufferViewManager(), selectOverload<int>(&BufferViewManager::bufferViewConfigAdded),
- this, selectOverload<int>(&BufferViewSettingsPage::addBufferView));
+ connect(Client::bufferViewManager(),
+ selectOverload<int>(&BufferViewManager::bufferViewConfigAdded),
+ this,
+ selectOverload<int>(&BufferViewSettingsPage::addBufferView));
}
else {
reset();
}
}
-
-void BufferViewSettingsPage::addBufferView(BufferViewConfig *config)
+void BufferViewSettingsPage::addBufferView(BufferViewConfig* config)
{
- auto *item = new QListWidgetItem(config->bufferViewName(), ui.bufferViewList);
- item->setData(Qt::UserRole, qVariantFromValue<QObject *>(qobject_cast<QObject *>(config)));
+ auto* item = new QListWidgetItem(config->bufferViewName(), ui.bufferViewList);
+ item->setData(Qt::UserRole, qVariantFromValue<QObject*>(qobject_cast<QObject*>(config)));
connect(config, &SyncableObject::updatedRemotely, this, &BufferViewSettingsPage::updateBufferView);
connect(config, &QObject::destroyed, this, &BufferViewSettingsPage::bufferViewDeleted);
ui.deleteBufferView->setEnabled(ui.bufferViewList->count() > 1);
}
-
void BufferViewSettingsPage::addBufferView(int bufferViewId)
{
// we are informed about a new bufferview from Client::bufferViewManager()
selectBufferViewById(bufferViewId);
}
-
void BufferViewSettingsPage::bufferViewDeleted()
{
- auto *config = static_cast<BufferViewConfig *>(sender());
- QObject *obj;
+ auto* config = static_cast<BufferViewConfig*>(sender());
+ QObject* obj;
for (int i = 0; i < ui.bufferViewList->count(); i++) {
- obj = ui.bufferViewList->item(i)->data(Qt::UserRole).value<QObject *>();
- if (config == static_cast<BufferViewConfig *>(obj)) {
- QListWidgetItem *item = ui.bufferViewList->takeItem(i);
+ obj = ui.bufferViewList->item(i)->data(Qt::UserRole).value<QObject*>();
+ if (config == static_cast<BufferViewConfig*>(obj)) {
+ QListWidgetItem* item = ui.bufferViewList->takeItem(i);
delete item;
break;
}
ui.deleteBufferView->setEnabled(ui.bufferViewList->count() > 1);
}
-
-void BufferViewSettingsPage::newBufferView(const QString &bufferViewName)
+void BufferViewSettingsPage::newBufferView(const QString& bufferViewName)
{
// id's of newly created bufferviews are negative (-1, -2... -n)
int fakeId = -1 * (_newBufferViews.count() + 1);
- auto *config = new BufferViewConfig(fakeId);
+ auto* config = new BufferViewConfig(fakeId);
config->setBufferViewName(bufferViewName);
config->setInitialized();
QList<BufferId> bufferIds;
ui.bufferViewList->setCurrentRow(listPos(config));
}
-
-int BufferViewSettingsPage::listPos(BufferViewConfig *config)
+int BufferViewSettingsPage::listPos(BufferViewConfig* config)
{
- QObject *obj;
+ QObject* obj;
for (int i = 0; i < ui.bufferViewList->count(); i++) {
- obj = ui.bufferViewList->item(i)->data(Qt::UserRole).value<QObject *>();
- if (config == qobject_cast<BufferViewConfig *>(obj))
+ obj = ui.bufferViewList->item(i)->data(Qt::UserRole).value<QObject*>();
+ if (config == qobject_cast<BufferViewConfig*>(obj))
return i;
}
return -1;
}
-
-BufferViewConfig *BufferViewSettingsPage::bufferView(int listPos)
+BufferViewConfig* BufferViewSettingsPage::bufferView(int listPos)
{
if (listPos < ui.bufferViewList->count() && listPos >= 0) {
- auto *obj = ui.bufferViewList->item(listPos)->data(Qt::UserRole).value<QObject *>();
- return qobject_cast<BufferViewConfig *>(obj);
+ auto* obj = ui.bufferViewList->item(listPos)->data(Qt::UserRole).value<QObject*>();
+ return qobject_cast<BufferViewConfig*>(obj);
}
else {
return nullptr;
}
}
-
bool BufferViewSettingsPage::selectBufferViewById(int bufferViewId)
{
- BufferViewConfig *config;
+ BufferViewConfig* config;
for (int i = 0; i < ui.bufferViewList->count(); i++) {
- config = qobject_cast<BufferViewConfig *>(ui.bufferViewList->item(i)->data(Qt::UserRole).value<QObject *>());
+ config = qobject_cast<BufferViewConfig*>(ui.bufferViewList->item(i)->data(Qt::UserRole).value<QObject*>());
if (config && config->bufferViewId() == bufferViewId) {
ui.bufferViewList->setCurrentRow(i);
return true;
return false;
}
-
void BufferViewSettingsPage::updateBufferView()
{
- auto *config = qobject_cast<BufferViewConfig *>(sender());
+ auto* config = qobject_cast<BufferViewConfig*>(sender());
if (!config)
return;
loadConfig(config);
}
-
void BufferViewSettingsPage::enableStatusBuffers(int networkIdx)
{
// we don't show a status buffer if we show multiple networks as selecting
ui.onlyStatusBuffers->setEnabled(networkIdx != 0);
}
-
void BufferViewSettingsPage::on_addBufferView_clicked()
{
if (!Client::bufferViewManager())
return;
QStringList existing;
- foreach(BufferViewConfig *bufferConfig, Client::bufferViewManager()->bufferViewConfigs()) {
+ foreach (BufferViewConfig* bufferConfig, Client::bufferViewManager()->bufferViewConfigs()) {
existing << bufferConfig->bufferViewName();
}
}
}
-
void BufferViewSettingsPage::on_renameBufferView_clicked()
{
if (ui.bufferViewList->selectedItems().isEmpty())
if (!Client::bufferViewManager())
return;
- BufferViewConfig *config = bufferView(ui.bufferViewList->currentRow());
+ BufferViewConfig* config = bufferView(ui.bufferViewList->currentRow());
if (!config)
return;
QStringList existing;
- foreach(BufferViewConfig *bufferConfig, Client::bufferViewManager()->bufferViewConfigs()) {
+ foreach (BufferViewConfig* bufferConfig, Client::bufferViewManager()->bufferViewConfigs()) {
existing << bufferConfig->bufferViewName();
}
BufferViewEditDlg dlg(config->bufferViewName(), existing, this);
if (dlg.exec() == QDialog::Accepted) {
- BufferViewConfig *changedConfig = cloneConfig(config);
+ BufferViewConfig* changedConfig = cloneConfig(config);
changedConfig->setBufferViewName(dlg.bufferViewName());
ui.bufferViewList->item(listPos(config))->setText(dlg.bufferViewName());
setChangedState(true);
}
}
-
void BufferViewSettingsPage::on_deleteBufferView_clicked()
{
if (ui.bufferViewList->selectedItems().isEmpty())
return;
- QListWidgetItem *currentItem = ui.bufferViewList->item(ui.bufferViewList->currentRow());
+ QListWidgetItem* currentItem = ui.bufferViewList->item(ui.bufferViewList->currentRow());
QString viewName = currentItem->text();
int viewId = bufferView(ui.bufferViewList->currentRow())->bufferViewId();
- int ret = QMessageBox::question(this, tr("Delete Chat List?"),
- tr("Do you really want to delete the chat list \"%1\"?").arg(viewName),
- QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
+ int ret = QMessageBox::question(this,
+ tr("Delete Chat List?"),
+ tr("Do you really want to delete the chat list \"%1\"?").arg(viewName),
+ QMessageBox::Yes | QMessageBox::No,
+ QMessageBox::No);
if (ret == QMessageBox::Yes) {
ui.bufferViewList->removeItemWidget(currentItem);
- auto *config = qobject_cast<BufferViewConfig *>(currentItem->data(Qt::UserRole).value<QObject *>());
+ auto* config = qobject_cast<BufferViewConfig*>(currentItem->data(Qt::UserRole).value<QObject*>());
delete currentItem;
if (viewId >= 0) {
_deleteBufferViews << viewId;
setChangedState(true);
}
else if (config) {
- QList<BufferViewConfig *>::iterator iter = _newBufferViews.begin();
+ QList<BufferViewConfig*>::iterator iter = _newBufferViews.begin();
while (iter != _newBufferViews.end()) {
if (*iter == config) {
iter = _newBufferViews.erase(iter);
}
}
-
-void BufferViewSettingsPage::bufferViewSelectionChanged(const QItemSelection ¤t, const QItemSelection &previous)
+void BufferViewSettingsPage::bufferViewSelectionChanged(const QItemSelection& current, const QItemSelection& previous)
{
Q_UNUSED(previous)
}
}
-
-void BufferViewSettingsPage::loadConfig(BufferViewConfig *config)
+void BufferViewSettingsPage::loadConfig(BufferViewConfig* config)
{
if (!config)
return;
_ignoreWidgetChanges = false;
}
-
-void BufferViewSettingsPage::saveConfig(BufferViewConfig *config)
+void BufferViewSettingsPage::saveConfig(BufferViewConfig* config)
{
if (!config)
return;
config->initSetBufferList(bufferIds);
}
-
void BufferViewSettingsPage::widgetHasChanged()
{
if (_ignoreWidgetChanges)
setChangedState(testHasChanged());
}
-
bool BufferViewSettingsPage::testHasChanged()
{
saveConfig(cloneConfig(bufferView(ui.bufferViewList->currentRow())));
return true;
bool changed = false;
- QHash<BufferViewConfig *, BufferViewConfig *>::iterator iter = _changedBufferViews.begin();
- QHash<BufferViewConfig *, BufferViewConfig *>::iterator iterEnd = _changedBufferViews.end();
+ QHash<BufferViewConfig*, BufferViewConfig*>::iterator iter = _changedBufferViews.begin();
+ QHash<BufferViewConfig*, BufferViewConfig*>::iterator iterEnd = _changedBufferViews.end();
while (iter != iterEnd) {
if (&(iter.key()) == &(iter.value())) {
iter.value()->deleteLater();
return changed;
}
-
-BufferViewConfig *BufferViewSettingsPage::cloneConfig(BufferViewConfig *config)
+BufferViewConfig* BufferViewSettingsPage::cloneConfig(BufferViewConfig* config)
{
if (!config || config->bufferViewId() < 0)
return config;
if (_changedBufferViews.contains(config))
return _changedBufferViews[config];
- auto *changedConfig = new BufferViewConfig(-1, this);
+ auto* changedConfig = new BufferViewConfig(-1, this);
changedConfig->fromVariantMap(config->toVariantMap());
changedConfig->setInitialized();
_changedBufferViews[config] = changedConfig;
changedConfig->setProperty("OriginalBufferList", toVariantList<BufferId>(config->bufferList()));
// if this is the currently displayed view we have to change the config of the preview filter
- auto *filter = qobject_cast<BufferViewFilter *>(ui.bufferViewPreview->model());
+ auto* filter = qobject_cast<BufferViewFilter*>(ui.bufferViewPreview->model());
if (filter && filter->config() == config)
filter->setConfig(changedConfig);
ui.bufferViewPreview->setConfig(changedConfig);
return changedConfig;
}
-
-BufferViewConfig *BufferViewSettingsPage::configForDisplay(BufferViewConfig *config)
+BufferViewConfig* BufferViewSettingsPage::configForDisplay(BufferViewConfig* config)
{
if (_changedBufferViews.contains(config))
return _changedBufferViews[config];
return config;
}
-
/**************************************************************************
* BufferViewEditDlg
*************************************************************************/
-BufferViewEditDlg::BufferViewEditDlg(const QString &old, QStringList exist, QWidget *parent) : QDialog(parent), existing(std::move(exist))
+BufferViewEditDlg::BufferViewEditDlg(const QString& old, QStringList exist, QWidget* parent)
+ : QDialog(parent)
+ , existing(std::move(exist))
{
ui.setupUi(this);
if (old.isEmpty()) {
// new buffer
setWindowTitle(tr("Add Chat List"));
- on_bufferViewEdit_textChanged(""); // disable ok button
+ on_bufferViewEdit_textChanged(""); // disable ok button
}
else {
ui.bufferViewEdit->setText(old);
}
}
-
-void BufferViewEditDlg::on_bufferViewEdit_textChanged(const QString &text)
+void BufferViewEditDlg::on_bufferViewEdit_textChanged(const QString& text)
{
ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text));
}
#pragma once
+#include <QItemSelection>
+
#include "settingspage.h"
-#include "ui_bufferviewsettingspage.h"
-#include "ui_buffervieweditdlg.h"
-#include <QItemSelection>
+#include "ui_buffervieweditdlg.h"
+#include "ui_bufferviewsettingspage.h"
class BufferViewConfig;
Q_OBJECT
public:
- BufferViewSettingsPage(QWidget *parent = nullptr);
+ BufferViewSettingsPage(QWidget* parent = nullptr);
~BufferViewSettingsPage() override;
public slots:
private slots:
void coreConnectionStateChanged(bool state);
- void addBufferView(BufferViewConfig *config);
+ void addBufferView(BufferViewConfig* config);
void addBufferView(int bufferViewId);
void bufferViewDeleted();
- void newBufferView(const QString &bufferViewName);
+ void newBufferView(const QString& bufferViewName);
void updateBufferView();
void enableStatusBuffers(int networkIdx);
void on_addBufferView_clicked();
void on_renameBufferView_clicked();
void on_deleteBufferView_clicked();
- void bufferViewSelectionChanged(const QItemSelection ¤t, const QItemSelection &previous);
+ void bufferViewSelectionChanged(const QItemSelection& current, const QItemSelection& previous);
void widgetHasChanged();
int _bufferViewHint{0};
// list of bufferviews to create
- QList<BufferViewConfig *> _newBufferViews;
+ QList<BufferViewConfig*> _newBufferViews;
// list of buferViews to delete
QList<int> _deleteBufferViews;
// Hash of pointers to cloned bufferViewConfigs holding the changes
- QHash<BufferViewConfig *, BufferViewConfig *> _changedBufferViews;
+ QHash<BufferViewConfig*, BufferViewConfig*> _changedBufferViews;
- int listPos(BufferViewConfig *config);
- BufferViewConfig *bufferView(int listPos);
+ int listPos(BufferViewConfig* config);
+ BufferViewConfig* bufferView(int listPos);
bool selectBufferViewById(int bufferViewId);
- BufferViewConfig *cloneConfig(BufferViewConfig *config);
- BufferViewConfig *configForDisplay(BufferViewConfig *config);
+ BufferViewConfig* cloneConfig(BufferViewConfig* config);
+ BufferViewConfig* configForDisplay(BufferViewConfig* config);
- void loadConfig(BufferViewConfig *config);
- void saveConfig(BufferViewConfig *config);
+ void loadConfig(BufferViewConfig* config);
+ void saveConfig(BufferViewConfig* config);
bool testHasChanged();
};
-
/**************************************************************************
* BufferViewEditDlg
*************************************************************************/
Q_OBJECT
public:
- BufferViewEditDlg(const QString &old, QStringList existing = QStringList(), QWidget *parent = nullptr);
+ BufferViewEditDlg(const QString& old, QStringList existing = QStringList(), QWidget* parent = nullptr);
inline QString bufferViewName() const { return ui.bufferViewEdit->text(); }
private slots:
- void on_bufferViewEdit_textChanged(const QString &);
+ void on_bufferViewEdit_textChanged(const QString&);
private:
Ui::BufferViewEditDlg ui;
#include "chatmonitorsettingspage.h"
-#include "client.h"
-#include "icon.h"
-#include "networkmodel.h"
-#include "bufferviewconfig.h"
+#include <QVariant>
+
#include "buffermodel.h"
#include "bufferview.h"
+#include "bufferviewconfig.h"
#include "bufferviewfilter.h"
#include "chatviewsettings.h"
+#include "client.h"
+#include "icon.h"
+#include "networkmodel.h"
-#include <QVariant>
-
-ChatMonitorSettingsPage::ChatMonitorSettingsPage(QWidget *parent)
+ChatMonitorSettingsPage::ChatMonitorSettingsPage(QWidget* parent)
: SettingsPage(tr("Interface"), tr("Chat Monitor"), parent)
{
ui.setupUi(this);
connect(ui.includeRead, &QAbstractButton::toggled, this, &ChatMonitorSettingsPage::widgetHasChanged);
}
-
bool ChatMonitorSettingsPage::hasDefaults() const
{
return true;
}
-
void ChatMonitorSettingsPage::defaults()
{
// NOTE: Whenever changing defaults here, also update ChatMonitorFilter::ChatMonitorFilter()
widgetHasChanged();
}
-
void ChatMonitorSettingsPage::load()
{
if (settings.contains("Default"))
if (!settings["Buffers"].toList().isEmpty()) {
QList<BufferId> bufferIdsFromConfig;
// remove all active buffers from the available config
- foreach(QVariant v, settings["Buffers"].toList()) {
+ foreach (QVariant v, settings["Buffers"].toList()) {
bufferIdsFromConfig << v.value<BufferId>();
allBufferIds.removeAll(v.value<BufferId>());
}
setChangedState(false);
}
-
void ChatMonitorSettingsPage::loadSettings()
{
// NOTE: Whenever changing defaults here, also update ChatMonitorFilter::ChatMonitorFilter()
// and ChatMonitorSettingsPage::defaults() to match
ChatViewSettings chatViewSettings("ChatMonitor");
- settings["OperationMode"] = (ChatViewSettings::OperationMode)
- chatViewSettings.value("OperationMode", ChatViewSettings::OptOut).toInt();
+ settings["OperationMode"] = (ChatViewSettings::OperationMode)chatViewSettings.value("OperationMode", ChatViewSettings::OptOut).toInt();
settings["ShowHighlights"] = chatViewSettings.value("ShowHighlights", false);
settings["ShowOwnMsgs"] = chatViewSettings.value("ShowOwnMsgs", true);
settings["AlwaysOwn"] = chatViewSettings.value("AlwaysOwn", false);
settings["IncludeRead"] = chatViewSettings.value("IncludeRead", false);
}
-
void ChatMonitorSettingsPage::save()
{
ChatViewSettings chatViewSettings("ChatMonitor");
// save list of active buffers
QVariantList saveableBufferIdList;
- foreach(BufferId id, _configActive->bufferList()) {
+ foreach (BufferId id, _configActive->bufferList()) {
saveableBufferIdList << QVariant::fromValue<BufferId>(id);
}
setChangedState(false);
}
-
void ChatMonitorSettingsPage::widgetHasChanged()
{
bool changed = testHasChanged();
- if (changed != hasChanged()) setChangedState(changed);
+ if (changed != hasChanged())
+ setChangedState(changed);
}
-
bool ChatMonitorSettingsPage::testHasChanged()
{
if (settings["OperationMode"].toInt() != ui.operationMode->currentIndex() + 1)
QSet<BufferId> uiBufs = _configActive->bufferList().toSet();
QSet<BufferId> settingsBufs;
- foreach(QVariant v, settings["Buffers"].toList())
- settingsBufs << v.value<BufferId>();
+ foreach (QVariant v, settings["Buffers"].toList())
+ settingsBufs << v.value<BufferId>();
if (uiBufs != settingsBufs)
return true;
return false;
}
-
-//TODO: - support drag 'n drop
+// TODO: - support drag 'n drop
// - adding of complete networks(?)
/*
toggleBuffers takes each a bufferView and its config for "input" and "output".
Any selected item will be moved over from the input to the output bufferview.
*/
-void ChatMonitorSettingsPage::toggleBuffers(BufferView *inView, BufferViewConfig *inCfg, BufferView *outView, BufferViewConfig *outCfg)
+void ChatMonitorSettingsPage::toggleBuffers(BufferView* inView, BufferViewConfig* inCfg, BufferView* outView, BufferViewConfig* outCfg)
{
// Fill QMap with selected items ordered by selection row
- QMap<int, QList<BufferId> > selectedBuffers;
- foreach(QModelIndex index, inView->selectionModel()->selectedIndexes()) {
+ QMap<int, QList<BufferId>> selectedBuffers;
+ foreach (QModelIndex index, inView->selectionModel()->selectedIndexes()) {
BufferId inBufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
if (index.data(NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType) {
// TODO:
This can probably be removed whenever BufferViewConfig::bulkAdd or something
like that is available.
*/
- qobject_cast<BufferViewFilter *>(outView->model())->setConfig(nullptr);
- qobject_cast<BufferViewFilter *>(inView->model())->setConfig(nullptr);
+ qobject_cast<BufferViewFilter*>(outView->model())->setConfig(nullptr);
+ qobject_cast<BufferViewFilter*>(inView->model())->setConfig(nullptr);
// actually move the ids
- foreach(QList<BufferId> list, selectedBuffers) {
- foreach(BufferId buffer, list) {
+ foreach (QList<BufferId> list, selectedBuffers) {
+ foreach (BufferId buffer, list) {
outCfg->addBuffer(buffer, 0);
inCfg->removeBuffer(buffer);
}
widgetHasChanged();
}
-
void ChatMonitorSettingsPage::on_activateBuffer_clicked()
{
if (ui.availableBuffers->currentIndex().isValid() && ui.availableBuffers->selectionModel()->hasSelection()) {
}
}
-
void ChatMonitorSettingsPage::on_deactivateBuffer_clicked()
{
if (ui.activeBuffers->currentIndex().isValid() && ui.activeBuffers->selectionModel()->hasSelection()) {
}
}
-
/*
switchOperationMode gets called on combobox signal currentIndexChanged.
modeIndex is the row id in combobox itemlist
#ifndef _CHATMONITORSETTINGSPAGE_H_
#define _CHATMONITORSETTINGSPAGE_H_
+#include <QHash>
+
#include "settingspage.h"
-#include "ui_chatmonitorsettingspage.h"
-#include <QHash>
+#include "ui_chatmonitorsettingspage.h"
class BufferViewConfig;
Q_OBJECT
public:
- ChatMonitorSettingsPage(QWidget *parent = nullptr);
+ ChatMonitorSettingsPage(QWidget* parent = nullptr);
bool hasDefaults() const override;
public slots:
Ui::ChatMonitorSettingsPage ui;
QHash<QString, QVariant> settings;
bool testHasChanged();
- void toggleBuffers(BufferView *inView, BufferViewConfig *inCfg, BufferView *outView, BufferViewConfig *outCfg);
+ void toggleBuffers(BufferView* inView, BufferViewConfig* inCfg, BufferView* outView, BufferViewConfig* outCfg);
- BufferViewConfig *_configAvailable;
- BufferViewConfig *_configActive;
+ BufferViewConfig* _configAvailable;
+ BufferViewConfig* _configActive;
};
-
#endif
#include "qtui.h"
#include "qtuistyle.h"
-ChatViewColorSettingsPage::ChatViewColorSettingsPage(QWidget *parent) :
- SettingsPage(tr("Interface"), tr("Chat View Colors"), parent)
+ChatViewColorSettingsPage::ChatViewColorSettingsPage(QWidget* parent)
+ : SettingsPage(tr("Interface"), tr("Chat View Colors"), parent)
{
ui.setupUi(this);
initAutoWidgets();
}
-
void ChatViewColorSettingsPage::save()
{
// Save the general settings
#pragma once
#include "settingspage.h"
+
#include "ui_chatviewcolorsettingspage.h"
class ColorButton;
*
* @param parent Parent QWidget object, such as the settings dialog
*/
- explicit ChatViewColorSettingsPage(QWidget *parent = nullptr);
+ explicit ChatViewColorSettingsPage(QWidget* parent = nullptr);
/**
* Gets whether or not this settings page has defaults
***************************************************************************/
#include "chatviewsettingspage.h"
+
#include "chatviewsettings.h"
#include "client.h"
#include "qtui.h"
#include "qtuistyle.h"
#include "uistyle.h"
-ChatViewSettingsPage::ChatViewSettingsPage(QWidget *parent)
+ChatViewSettingsPage::ChatViewSettingsPage(QWidget* parent)
: SettingsPage(tr("Interface"), tr("Chat View"), parent)
{
ui.setupUi(this);
// [Original tool-tip]
// [Bold 'does not support feature' message]
// [Specific version needed and feature details]
- ui.senderPrefixComboBox->setToolTip(
- QString("<b>%2</b><br/>%3").arg(
- tr("Your Quassel core does not support this feature"),
- tr("You need a Quassel core v0.13.0 or newer in order to show sender "
- "modes before nicknames.")));
+ ui.senderPrefixComboBox->setToolTip(QString("<b>%2</b><br/>%3")
+ .arg(tr("Your Quassel core does not support this feature"),
+ tr("You need a Quassel core v0.13.0 or newer in order to show sender "
+ "modes before nicknames.")));
}
initAutoWidgets();
initSenderPrefixComboBox();
}
-
void ChatViewSettingsPage::initSenderPrefixComboBox()
{
// Fill combobox with sender prefix modes
// Do not change ComboBox ordering without also adjusting chatviewsettingspage.ui "defaultValue"
// and UiStyle::SenderPrefixMode
- ui.senderPrefixComboBox->addItem(tr("No modes"),
- static_cast<int>(UiStyle::SenderPrefixMode::NoModes));
- ui.senderPrefixComboBox->addItem(tr("Highest mode"),
- static_cast<int>(UiStyle::SenderPrefixMode::HighestMode));
- ui.senderPrefixComboBox->addItem(tr("All modes"),
- static_cast<int>(UiStyle::SenderPrefixMode::AllModes));
+ ui.senderPrefixComboBox->addItem(tr("No modes"), static_cast<int>(UiStyle::SenderPrefixMode::NoModes));
+ ui.senderPrefixComboBox->addItem(tr("Highest mode"), static_cast<int>(UiStyle::SenderPrefixMode::HighestMode));
+ ui.senderPrefixComboBox->addItem(tr("All modes"), static_cast<int>(UiStyle::SenderPrefixMode::AllModes));
}
-
void ChatViewSettingsPage::save()
{
- bool needsStyleReload = SettingsPage::hasChanged(ui.customChatViewFont)
- || SettingsPage::hasChanged(ui.chatViewFont);
+ bool needsStyleReload = SettingsPage::hasChanged(ui.customChatViewFont) || SettingsPage::hasChanged(ui.chatViewFont);
// Save the general settings
SettingsPage::save();
#define CHATVIEWSETTINGSPAGE_H_
#include "settingspage.h"
+
#include "ui_chatviewsettingspage.h"
class ColorButton;
Q_OBJECT
public:
- ChatViewSettingsPage(QWidget *parent = nullptr);
+ ChatViewSettingsPage(QWidget* parent = nullptr);
inline bool hasDefaults() const override { return true; }
inline QString settingsKey() const override { return QString("QtUi/ChatView/__default__"); }
};
-
#endif
#include "client.h"
#include "networkconfig.h"
-ConnectionSettingsPage::ConnectionSettingsPage(QWidget *parent)
+ConnectionSettingsPage::ConnectionSettingsPage(QWidget* parent)
: SettingsPage(tr("IRC"), QString(), parent)
{
ui.setupUi(this);
clientConnected();
}
-
void ConnectionSettingsPage::clientConnected()
{
if (Client::networkConfig()->isInitialized())
connect(Client::networkConfig(), &SyncableObject::initDone, this, &ConnectionSettingsPage::initDone);
}
-
void ConnectionSettingsPage::clientDisconnected()
{
setEnabled(false);
setChangedState(false);
}
-
void ConnectionSettingsPage::initDone()
{
setEnabled(true);
}
-
bool ConnectionSettingsPage::hasDefaults() const
{
return true;
}
-
-QVariant ConnectionSettingsPage::loadAutoWidgetValue(const QString &widgetName)
+QVariant ConnectionSettingsPage::loadAutoWidgetValue(const QString& widgetName)
{
if (!isEnabled())
return QVariant();
- NetworkConfig *config = Client::networkConfig();
+ NetworkConfig* config = Client::networkConfig();
if (widgetName == "pingTimeoutEnabled")
return config->pingTimeoutEnabled();
if (widgetName == "pingInterval")
return SettingsPage::loadAutoWidgetValue(widgetName);
}
-
-void ConnectionSettingsPage::saveAutoWidgetValue(const QString &widgetName, const QVariant &value)
+void ConnectionSettingsPage::saveAutoWidgetValue(const QString& widgetName, const QVariant& value)
{
if (!isEnabled())
return;
- NetworkConfig *config = Client::networkConfig();
+ NetworkConfig* config = Client::networkConfig();
if (widgetName == "pingTimeoutEnabled")
config->requestSetPingTimeoutEnabled(value.toBool());
else if (widgetName == "pingInterval")
Q_OBJECT
public:
- ConnectionSettingsPage(QWidget *parent = nullptr);
+ ConnectionSettingsPage(QWidget* parent = nullptr);
bool hasDefaults() const override;
bool needsCoreConnection() const override { return true; }
void initDone();
private:
- QVariant loadAutoWidgetValue(const QString &widgetName) override;
- void saveAutoWidgetValue(const QString &widgetName, const QVariant &value) override;
+ QVariant loadAutoWidgetValue(const QString& widgetName) override;
+ void saveAutoWidgetValue(const QString& widgetName, const QVariant& value) override;
Ui::ConnectionSettingsPage ui;
};
-
#endif
#include "icon.h"
#include "util.h"
-CoreAccountSettingsPage::CoreAccountSettingsPage(QWidget *parent)
- : SettingsPage(tr("Remote Cores"), QString(), parent),
- _lastAccountId(0),
- _lastAutoConnectId(0)
+CoreAccountSettingsPage::CoreAccountSettingsPage(QWidget* parent)
+ : SettingsPage(tr("Remote Cores"), QString(), parent)
+ , _lastAccountId(0)
+ , _lastAutoConnectId(0)
{
ui.setupUi(this);
initAutoWidgets();
setWidgetStates();
}
-
void CoreAccountSettingsPage::setStandAlone(bool standalone)
{
_standalone = standalone;
}
-
void CoreAccountSettingsPage::load()
{
model()->update(Client::coreAccountModel());
setChangedState(false);
}
-
void CoreAccountSettingsPage::save()
{
SettingsPage::save();
ui.autoConnectAccount->setProperty("storedValue", ui.autoConnectAccount->currentIndex());
}
-
// TODO: Qt 4.6 - replace by proper rowsMoved() semantics
// NOTE: This is the filtered model
-void CoreAccountSettingsPage::rowsAboutToBeRemoved(const QModelIndex &index, int start, int end)
+void CoreAccountSettingsPage::rowsAboutToBeRemoved(const QModelIndex& index, int start, int end)
{
_lastAutoConnectId = _lastAccountId = 0;
if (index.isValid() || start != end)
_lastAutoConnectId = id;
}
-
-void CoreAccountSettingsPage::rowsInserted(const QModelIndex &index, int start, int end)
+void CoreAccountSettingsPage::rowsInserted(const QModelIndex& index, int start, int end)
{
if (index.isValid() || start != end)
return;
_lastAccountId = _lastAutoConnectId = 0;
}
-
AccountId CoreAccountSettingsPage::selectedAccount() const
{
QModelIndex index = ui.accountView->currentIndex();
return index.data(CoreAccountModel::AccountIdRole).value<AccountId>();
}
-
void CoreAccountSettingsPage::setSelectedAccount(AccountId accId)
{
QModelIndex index = filteredModel()->mapFromSource(model()->accountIndex(accId));
ui.accountView->setCurrentIndex(index);
}
-
void CoreAccountSettingsPage::on_addAccountButton_clicked()
{
CoreAccountEditDlg dlg(CoreAccount(), this);
}
}
-
void CoreAccountSettingsPage::on_editAccountButton_clicked()
{
QModelIndex idx = ui.accountView->selectionModel()->currentIndex();
editAccount(idx);
}
-
-void CoreAccountSettingsPage::editAccount(const QModelIndex &index)
+void CoreAccountSettingsPage::editAccount(const QModelIndex& index)
{
if (!index.isValid())
return;
}
}
-
void CoreAccountSettingsPage::on_deleteAccountButton_clicked()
{
if (!ui.accountView->selectionModel()->selectedIndexes().count())
}
}
-
-void CoreAccountSettingsPage::on_accountView_doubleClicked(const QModelIndex &index)
+void CoreAccountSettingsPage::on_accountView_doubleClicked(const QModelIndex& index)
{
if (!index.isValid())
return;
editAccount(index);
}
-
void CoreAccountSettingsPage::setWidgetStates()
{
AccountId accId = selectedAccount();
ui.deleteAccountButton->setEnabled(editable);
}
-
void CoreAccountSettingsPage::widgetHasChanged()
{
setChangedState(testHasChanged());
setWidgetStates();
}
-
bool CoreAccountSettingsPage::testHasChanged()
{
- if (ui.autoConnectAccount->currentIndex() !=
- ui.autoConnectAccount->property("storedValue").toInt()) {
+ if (ui.autoConnectAccount->currentIndex() != ui.autoConnectAccount->property("storedValue").toInt()) {
return true;
}
if (*model() != *Client::coreAccountModel()) {
return false;
}
-
/*****************************************************************************************
* CoreAccountEditDlg
*****************************************************************************************/
-CoreAccountEditDlg::CoreAccountEditDlg(const CoreAccount &acct, QWidget *parent)
+CoreAccountEditDlg::CoreAccountEditDlg(const CoreAccount& acct, QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
setWindowTitle(tr("Add Core Account"));
}
-
CoreAccount CoreAccountEditDlg::account()
{
_account.setAccountName(ui.accountName->text().trimmed());
int checkedId = ui.buttonGroupProxyType->checkedId();
switch (checkedId) {
- case NoProxy: // QNetworkProxy::NoProxy
+ case NoProxy: // QNetworkProxy::NoProxy
QNetworkProxyFactory::setUseSystemConfiguration(false);
_account.setProxyType(proxyType);
break;
- case SystemProxy: // QNetworkProxy::DefaultProxy:
+ case SystemProxy: // QNetworkProxy::DefaultProxy:
QNetworkProxyFactory::setUseSystemConfiguration(true);
_account.setProxyType(QNetworkProxy::DefaultProxy);
break;
- case ManualProxy: // QNetworkProxy::Socks5Proxy || QNetworkProxy::HttpProxy
- proxyType = ui.proxyType->currentIndex() == 0 ?
- QNetworkProxy::Socks5Proxy : QNetworkProxy::HttpProxy;
+ case ManualProxy: // QNetworkProxy::Socks5Proxy || QNetworkProxy::HttpProxy
+ proxyType = ui.proxyType->currentIndex() == 0 ? QNetworkProxy::Socks5Proxy : QNetworkProxy::HttpProxy;
QNetworkProxyFactory::setUseSystemConfiguration(false);
_account.setProxyHostName(ui.proxyHostName->text().trimmed());
_account.setProxyPort(ui.proxyPort->value());
return _account;
}
-
void CoreAccountEditDlg::setWidgetStates()
{
- bool ok = !ui.accountName->text().trimmed().isEmpty()
- && !ui.user->text().trimmed().isEmpty()
- && !ui.hostName->text().isEmpty();
+ bool ok = !ui.accountName->text().trimmed().isEmpty() && !ui.user->text().trimmed().isEmpty() && !ui.hostName->text().isEmpty();
ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok);
}
-
-void CoreAccountEditDlg::on_hostName_textChanged(const QString &text)
+void CoreAccountEditDlg::on_hostName_textChanged(const QString& text)
{
Q_UNUSED(text);
setWidgetStates();
}
-
-void CoreAccountEditDlg::on_accountName_textChanged(const QString &text)
+void CoreAccountEditDlg::on_accountName_textChanged(const QString& text)
{
Q_UNUSED(text);
setWidgetStates();
}
-
-void CoreAccountEditDlg::on_user_textChanged(const QString &text)
+void CoreAccountEditDlg::on_user_textChanged(const QString& text)
{
Q_UNUSED(text)
setWidgetStates();
ui.proxyPassword->setEnabled(checked);
}
-
/*****************************************************************************************
* FilteredCoreAccountModel
*****************************************************************************************/
-FilteredCoreAccountModel::FilteredCoreAccountModel(CoreAccountModel *model, QObject *parent) : QSortFilterProxyModel(parent)
+FilteredCoreAccountModel::FilteredCoreAccountModel(CoreAccountModel* model, QObject* parent)
+ : QSortFilterProxyModel(parent)
{
_internalAccount = model->internalAccount();
setSourceModel(model);
}
-
-bool FilteredCoreAccountModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
+bool FilteredCoreAccountModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
if (Quassel::runMode() == Quassel::Monolithic)
return true;
#include <QNetworkProxy>
#include <QSortFilterProxyModel>
-#include "settingspage.h"
-
#include "coreaccount.h"
+#include "settingspage.h"
#include "ui_coreaccounteditdlg.h"
#include "ui_coreaccountsettingspage.h"
Q_OBJECT
public:
- CoreAccountSettingsPage(QWidget *parent = nullptr);
+ CoreAccountSettingsPage(QWidget* parent = nullptr);
inline bool hasDefaults() const override { return false; }
inline bool isStandAlone() const { return _standalone; }
void on_addAccountButton_clicked();
void on_editAccountButton_clicked();
void on_deleteAccountButton_clicked();
- void on_accountView_doubleClicked(const QModelIndex &index);
+ void on_accountView_doubleClicked(const QModelIndex& index);
void setWidgetStates();
void widgetHasChanged();
- void rowsAboutToBeRemoved(const QModelIndex &index, int start, int end);
- void rowsInserted(const QModelIndex &index, int start, int end);
+ void rowsAboutToBeRemoved(const QModelIndex& index, int start, int end);
+ void rowsInserted(const QModelIndex& index, int start, int end);
private:
Ui::CoreAccountSettingsPage ui;
- CoreAccountModel *_model;
- inline CoreAccountModel *model() const { return _model; }
- FilteredCoreAccountModel *_filteredModel;
- inline FilteredCoreAccountModel *filteredModel() const { return _filteredModel; }
+ CoreAccountModel* _model;
+ inline CoreAccountModel* model() const { return _model; }
+ FilteredCoreAccountModel* _filteredModel;
+ inline FilteredCoreAccountModel* filteredModel() const { return _filteredModel; }
AccountId _lastAccountId, _lastAutoConnectId;
bool _standalone{false};
- void editAccount(const QModelIndex &);
+ void editAccount(const QModelIndex&);
bool testHasChanged();
inline QString settingsKey() const override { return QString("CoreAccounts"); }
};
-
// ========================================
// CoreAccountEditDlg
// ========================================
Q_OBJECT
public:
- CoreAccountEditDlg(const CoreAccount &account, QWidget *parent = nullptr);
+ CoreAccountEditDlg(const CoreAccount& account, QWidget* parent = nullptr);
CoreAccount account();
private slots:
- void on_hostName_textChanged(const QString &);
- void on_accountName_textChanged(const QString &);
- void on_user_textChanged(const QString &);
+ void on_hostName_textChanged(const QString&);
+ void on_accountName_textChanged(const QString&);
+ void on_user_textChanged(const QString&);
void on_radioButtonManualProxy_toggled(bool checked);
void setWidgetStates();
private:
Ui::CoreAccountEditDlg ui;
CoreAccount _account;
- enum ProxyType { NoProxy, SystemProxy, ManualProxy };
+ enum ProxyType
+ {
+ NoProxy,
+ SystemProxy,
+ ManualProxy
+ };
};
-
// ========================================
// FilteredCoreAccountModel
// ========================================
Q_OBJECT
public:
- FilteredCoreAccountModel(CoreAccountModel *model, QObject *parent = nullptr);
+ FilteredCoreAccountModel(CoreAccountModel* model, QObject* parent = nullptr);
protected:
- bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override;
+ bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override;
private:
AccountId _internalAccount;
};
-
#endif
#include "coreconnectionsettingspage.h"
-CoreConnectionSettingsPage::CoreConnectionSettingsPage(QWidget *parent)
+CoreConnectionSettingsPage::CoreConnectionSettingsPage(QWidget* parent)
: SettingsPage(tr("Remote Cores"), tr("Connection"), parent)
{
ui.setupUi(this);
connect(ui.useNoTimeout, &QAbstractButton::toggled, this, &CoreConnectionSettingsPage::widgetHasChanged);
}
-
void CoreConnectionSettingsPage::widgetHasChanged()
{
bool hasChanged = false;
setChangedState(hasChanged);
}
-
void CoreConnectionSettingsPage::defaults()
{
setRadioButtons(CoreConnectionSettings::UseQNetworkConfigurationManager);
SettingsPage::defaults();
}
-
void CoreConnectionSettingsPage::load()
{
CoreConnectionSettings s;
SettingsPage::load();
}
-
void CoreConnectionSettingsPage::save()
{
_detectionMode = modeFromRadioButtons();
SettingsPage::save();
}
-
void CoreConnectionSettingsPage::setRadioButtons(CoreConnectionSettings::NetworkDetectionMode mode)
{
switch (mode) {
}
}
-
CoreConnectionSettings::NetworkDetectionMode CoreConnectionSettingsPage::modeFromRadioButtons() const
{
if (ui.useQNetworkConfigurationManager->isChecked())
Q_OBJECT
public:
- CoreConnectionSettingsPage(QWidget *parent = nullptr);
+ CoreConnectionSettingsPage(QWidget* parent = nullptr);
inline bool hasDefaults() const override { return true; }
inline QString settingsKey() const override { return QString("CoreConnection"); }
};
-
#endif
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "corehighlightsettingspage.h"
+
#include <QHeaderView>
#include <QMessageBox>
#include <QTableWidget>
#include "client.h"
-#include "corehighlightsettingspage.h"
#include "icon.h"
#include "qtui.h"
#include "util.h"
-CoreHighlightSettingsPage::CoreHighlightSettingsPage(QWidget *parent)
+CoreHighlightSettingsPage::CoreHighlightSettingsPage(QWidget* parent)
: SettingsPage(tr("Interface"),
// In Monolithic mode, local highlights are replaced by remote highlights
- Quassel::runMode() == Quassel::Monolithic ?
- tr("Highlights") : tr("Remote Highlights"),
+ Quassel::runMode() == Quassel::Monolithic ? tr("Highlights") : tr("Remote Highlights"),
parent)
{
ui.setupUi(this);
ui.highlightNicksComboBox->addItem(tr("Current Nick"), QVariant(HighlightRuleManager::CurrentNick));
ui.highlightNicksComboBox->addItem(tr("None"), QVariant(HighlightRuleManager::NoNick));
- coreConnectionStateChanged(Client::isConnected()); // need a core connection!
+ coreConnectionStateChanged(Client::isConnected()); // need a core connection!
connect(Client::instance(), &Client::coreConnectionStateChanged, this, &CoreHighlightSettingsPage::coreConnectionStateChanged);
connect(ui.highlightAdd, &QAbstractButton::clicked, this, [this]() { addNewHighlightRow(); });
connect(ui.ignoredTable, &QTableWidget::itemClicked, this, &CoreHighlightSettingsPage::selectIgnoredRow);
// Update the "Case sensitive" checkbox
- connect(ui.highlightNicksComboBox, selectOverload<int>(&QComboBox::currentIndexChanged), this, &CoreHighlightSettingsPage::highlightNicksChanged);
+ connect(ui.highlightNicksComboBox,
+ selectOverload<int>(&QComboBox::currentIndexChanged),
+ this,
+ &CoreHighlightSettingsPage::highlightNicksChanged);
connect(ui.highlightNicksComboBox, selectOverload<int>(&QComboBox::currentIndexChanged), this, &CoreHighlightSettingsPage::widgetHasChanged);
connect(ui.nicksCaseSensitive, &QAbstractButton::clicked, this, &CoreHighlightSettingsPage::widgetHasChanged);
connect(ui.ignoredAdd, &QAbstractButton::clicked, this, &CoreHighlightSettingsPage::widgetHasChanged);
connect(ui.ignoredRemove, &QAbstractButton::clicked, this, &CoreHighlightSettingsPage::widgetHasChanged);
- connect(ui.highlightTable,
- &QTableWidget::itemChanged,
- this,
- &CoreHighlightSettingsPage::highlightTableChanged);
+ connect(ui.highlightTable, &QTableWidget::itemChanged, this, &CoreHighlightSettingsPage::highlightTableChanged);
- connect(ui.ignoredTable,
- &QTableWidget::itemChanged,
- this,
- &CoreHighlightSettingsPage::ignoredTableChanged);
+ connect(ui.ignoredTable, &QTableWidget::itemChanged, this, &CoreHighlightSettingsPage::ignoredTableChanged);
connect(Client::instance(), &Client::connected, this, &CoreHighlightSettingsPage::clientConnected);
if (Quassel::runMode() == Quassel::Monolithic) {
// We're running in Monolithic mode, local highlights are considered legacy
ui.highlightImport->setText(tr("Import Legacy"));
- ui.highlightImport->setToolTip(tr("Import highlight rules configured in <i>%1</i>.")
- .arg(tr("Legacy Highlights").replace(" ", " ")));
+ ui.highlightImport->setToolTip(
+ tr("Import highlight rules configured in <i>%1</i>.").arg(tr("Legacy Highlights").replace(" ", " ")));
// Re-use translations of "Legacy Highlights" as this is a word-for-word reference, forcing
// all spaces to be non-breaking
- } else {
+ }
+ else {
// We're running in client/split mode, local highlights are distinguished from remote
ui.highlightImport->setText(tr("Import Local"));
- ui.highlightImport->setToolTip(tr("Import highlight rules configured in <i>%1</i>.")
- .arg(tr("Local Highlights").replace(" ", " ")));
+ ui.highlightImport->setToolTip(
+ tr("Import highlight rules configured in <i>%1</i>.").arg(tr("Local Highlights").replace(" ", " ")));
// Re-use translations of "Local Highlights" as this is a word-for-word reference, forcing
// all spaces to be non-breaking
}
}
-
void CoreHighlightSettingsPage::coreConnectionStateChanged(bool state)
{
updateCoreSupportStatus(state);
setEnabled(state);
if (state) {
load();
- } else {
+ }
+ else {
revert();
}
}
-
-void CoreHighlightSettingsPage::setupRuleTable(QTableWidget *table) const
+void CoreHighlightSettingsPage::setupRuleTable(QTableWidget* table) const
{
table->verticalHeader()->hide();
table->setShowGrid(false);
table->horizontalHeader()->setSectionResizeMode(CoreHighlightSettingsPage::ChanColumn, QHeaderView::ResizeToContents);
}
-
QString CoreHighlightSettingsPage::getTableTooltip(column tableColumn) const
{
switch (tableColumn) {
}
}
-
-void CoreHighlightSettingsPage::setupTableTooltips(QWidget *enableWidget, QWidget *nameWidget,
- QWidget *regExWidget, QWidget *csWidget,
- QWidget *senderWidget, QWidget *chanWidget) const
+void CoreHighlightSettingsPage::setupTableTooltips(
+ QWidget* enableWidget, QWidget* nameWidget, QWidget* regExWidget, QWidget* csWidget, QWidget* senderWidget, QWidget* chanWidget) const
{
// Make sure everything's valid
Q_ASSERT(enableWidget);
chanWidget->setWhatsThis(chanWidget->toolTip());
}
-
-void CoreHighlightSettingsPage::setupTableTooltips(QTableWidgetItem *enableWidget,
- QTableWidgetItem *nameWidget,
- QTableWidgetItem *regExWidget,
- QTableWidgetItem *csWidget,
- QTableWidgetItem *senderWidget,
- QTableWidgetItem *chanWidget) const
+void CoreHighlightSettingsPage::setupTableTooltips(QTableWidgetItem* enableWidget,
+ QTableWidgetItem* nameWidget,
+ QTableWidgetItem* regExWidget,
+ QTableWidgetItem* csWidget,
+ QTableWidgetItem* senderWidget,
+ QTableWidgetItem* chanWidget) const
{
// Make sure everything's valid
Q_ASSERT(enableWidget);
chanWidget->setWhatsThis(chanWidget->toolTip());
}
-
void CoreHighlightSettingsPage::updateCoreSupportStatus(bool state)
{
// Assume connected state as enforced by the settings page UI
// warning. Don't show the warning needlessly when disconnected.
ui.highlightsConfigWidget->setEnabled(true);
ui.coreUnsupportedWidget->setVisible(false);
- } else {
+ }
+ else {
// Core does not support highlights, show warning and disable highlight configuration
ui.highlightsConfigWidget->setEnabled(false);
ui.coreUnsupportedWidget->setVisible(true);
}
}
-
void CoreHighlightSettingsPage::clientConnected()
{
connect(Client::highlightRuleManager(), &SyncableObject::updated, this, &CoreHighlightSettingsPage::revert);
}
-
void CoreHighlightSettingsPage::revert()
{
if (!hasChanged())
load();
}
-
bool CoreHighlightSettingsPage::hasDefaults() const
{
return true;
}
-
void CoreHighlightSettingsPage::defaults()
{
int highlightNickType = HighlightRuleManager::HighlightNickType::CurrentNick;
widgetHasChanged();
}
-
-void CoreHighlightSettingsPage::addNewHighlightRow(bool enable, int id, const QString &name, bool regex, bool cs,
- const QString &sender, const QString &chanName, bool self)
+void CoreHighlightSettingsPage::addNewHighlightRow(
+ bool enable, int id, const QString& name, bool regex, bool cs, const QString& sender, const QString& chanName, bool self)
{
ui.highlightTable->setRowCount(ui.highlightTable->rowCount() + 1);
id = nextId();
}
- auto *nameItem = new QTableWidgetItem(name);
+ auto* nameItem = new QTableWidgetItem(name);
- auto *regexItem = new QTableWidgetItem("");
+ auto* regexItem = new QTableWidgetItem("");
if (regex)
regexItem->setCheckState(Qt::Checked);
else
regexItem->setCheckState(Qt::Unchecked);
regexItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
- auto *csItem = new QTableWidgetItem("");
+ auto* csItem = new QTableWidgetItem("");
if (cs)
csItem->setCheckState(Qt::Checked);
else
csItem->setCheckState(Qt::Unchecked);
csItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
- auto *enableItem = new QTableWidgetItem("");
+ auto* enableItem = new QTableWidgetItem("");
if (enable)
enableItem->setCheckState(Qt::Checked);
else
enableItem->setCheckState(Qt::Unchecked);
enableItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
- auto *senderItem = new QTableWidgetItem(sender);
+ auto* senderItem = new QTableWidgetItem(sender);
- auto *chanNameItem = new QTableWidgetItem(chanName);
+ auto* chanNameItem = new QTableWidgetItem(chanName);
setupTableTooltips(enableItem, nameItem, regexItem, csItem, senderItem, chanNameItem);
highlightList << HighlightRuleManager::HighlightRule(id, name, regex, cs, enable, false, sender, chanName);
}
-
-void CoreHighlightSettingsPage::addNewIgnoredRow(bool enable, int id, const QString &name, bool regex, bool cs,
- const QString &sender, const QString &chanName, bool self)
+void CoreHighlightSettingsPage::addNewIgnoredRow(
+ bool enable, int id, const QString& name, bool regex, bool cs, const QString& sender, const QString& chanName, bool self)
{
ui.ignoredTable->setRowCount(ui.ignoredTable->rowCount() + 1);
id = nextId();
}
- auto *nameItem = new QTableWidgetItem(name);
+ auto* nameItem = new QTableWidgetItem(name);
- auto *regexItem = new QTableWidgetItem("");
+ auto* regexItem = new QTableWidgetItem("");
if (regex)
regexItem->setCheckState(Qt::Checked);
else
regexItem->setCheckState(Qt::Unchecked);
regexItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
- auto *csItem = new QTableWidgetItem("");
+ auto* csItem = new QTableWidgetItem("");
if (cs)
csItem->setCheckState(Qt::Checked);
else
csItem->setCheckState(Qt::Unchecked);
csItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
- auto *enableItem = new QTableWidgetItem("");
+ auto* enableItem = new QTableWidgetItem("");
if (enable)
enableItem->setCheckState(Qt::Checked);
else
enableItem->setCheckState(Qt::Unchecked);
enableItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
- auto *chanNameItem = new QTableWidgetItem(chanName);
+ auto* chanNameItem = new QTableWidgetItem(chanName);
- auto *senderItem = new QTableWidgetItem(sender);
+ auto* senderItem = new QTableWidgetItem(sender);
setupTableTooltips(enableItem, nameItem, regexItem, csItem, senderItem, chanNameItem);
ignoredList << HighlightRuleManager::HighlightRule(id, name, regex, cs, enable, true, sender, chanName);
}
-
void CoreHighlightSettingsPage::removeSelectedHighlightRows()
{
QList<int> selectedRows;
- QList<QTableWidgetItem *> selectedItemList = ui.highlightTable->selectedItems();
+ QList<QTableWidgetItem*> selectedItemList = ui.highlightTable->selectedItems();
for (auto selectedItem : selectedItemList) {
selectedRows.append(selectedItem->row());
}
}
}
-
void CoreHighlightSettingsPage::removeSelectedIgnoredRows()
{
QList<int> selectedRows;
- QList<QTableWidgetItem *> selectedItemList = ui.ignoredTable->selectedItems();
+ QList<QTableWidgetItem*> selectedItemList = ui.ignoredTable->selectedItems();
for (auto selectedItem : selectedItemList) {
selectedRows.append(selectedItem->row());
}
}
}
-
void CoreHighlightSettingsPage::highlightNicksChanged(const int index)
{
// Only allow toggling "Case sensitive" when a nickname will be highlighted
ui.nicksCaseSensitive->setEnabled(highlightNickType != HighlightRuleManager::NoNick);
}
-
-void CoreHighlightSettingsPage::selectHighlightRow(QTableWidgetItem *item)
+void CoreHighlightSettingsPage::selectHighlightRow(QTableWidgetItem* item)
{
int row = item->row();
bool selected = item->isSelected();
- ui.highlightTable
- ->setRangeSelected(QTableWidgetSelectionRange(row, 0, row, CoreHighlightSettingsPage::ColumnCount - 1),
- selected);
+ ui.highlightTable->setRangeSelected(QTableWidgetSelectionRange(row, 0, row, CoreHighlightSettingsPage::ColumnCount - 1), selected);
}
-
-void CoreHighlightSettingsPage::selectIgnoredRow(QTableWidgetItem *item)
+void CoreHighlightSettingsPage::selectIgnoredRow(QTableWidgetItem* item)
{
int row = item->row();
bool selected = item->isSelected();
- ui.ignoredTable
- ->setRangeSelected(QTableWidgetSelectionRange(row, 0, row, CoreHighlightSettingsPage::ColumnCount - 1),
- selected);
+ ui.ignoredTable->setRangeSelected(QTableWidgetSelectionRange(row, 0, row, CoreHighlightSettingsPage::ColumnCount - 1), selected);
}
-
void CoreHighlightSettingsPage::emptyHighlightTable()
{
// ui.highlight and highlightList should have the same size, but just to make sure.
highlightList.clear();
}
-
void CoreHighlightSettingsPage::emptyIgnoredTable()
{
// ui.highlight and highlightList should have the same size, but just to make sure.
ignoredList.clear();
}
-
-void CoreHighlightSettingsPage::highlightTableChanged(QTableWidgetItem *item)
+void CoreHighlightSettingsPage::highlightTableChanged(QTableWidgetItem* item)
{
if (item->row() + 1 > highlightList.size())
return;
auto highlightRule = highlightList.value(item->row());
-
switch (item->column()) {
- case CoreHighlightSettingsPage::EnableColumn:
- highlightRule.setIsEnabled(item->checkState() == Qt::Checked);
- break;
- case CoreHighlightSettingsPage::NameColumn:
- highlightRule.setContents(item->text());
- break;
- case CoreHighlightSettingsPage::RegExColumn:
- highlightRule.setIsRegEx(item->checkState() == Qt::Checked);
- break;
- case CoreHighlightSettingsPage::CsColumn:
- highlightRule.setIsCaseSensitive(item->checkState() == Qt::Checked);
- break;
- case CoreHighlightSettingsPage::SenderColumn:
- if (!item->text().isEmpty() && item->text().trimmed().isEmpty())
- item->setText("");
- highlightRule.setSender(item->text());
- break;
- case CoreHighlightSettingsPage::ChanColumn:
- if (!item->text().isEmpty() && item->text().trimmed().isEmpty())
- item->setText("");
- highlightRule.setChanName(item->text());
- break;
+ case CoreHighlightSettingsPage::EnableColumn:
+ highlightRule.setIsEnabled(item->checkState() == Qt::Checked);
+ break;
+ case CoreHighlightSettingsPage::NameColumn:
+ highlightRule.setContents(item->text());
+ break;
+ case CoreHighlightSettingsPage::RegExColumn:
+ highlightRule.setIsRegEx(item->checkState() == Qt::Checked);
+ break;
+ case CoreHighlightSettingsPage::CsColumn:
+ highlightRule.setIsCaseSensitive(item->checkState() == Qt::Checked);
+ break;
+ case CoreHighlightSettingsPage::SenderColumn:
+ if (!item->text().isEmpty() && item->text().trimmed().isEmpty())
+ item->setText("");
+ highlightRule.setSender(item->text());
+ break;
+ case CoreHighlightSettingsPage::ChanColumn:
+ if (!item->text().isEmpty() && item->text().trimmed().isEmpty())
+ item->setText("");
+ highlightRule.setChanName(item->text());
+ break;
}
highlightList[item->row()] = highlightRule;
emit widgetHasChanged();
}
-
-void CoreHighlightSettingsPage::ignoredTableChanged(QTableWidgetItem *item)
+void CoreHighlightSettingsPage::ignoredTableChanged(QTableWidgetItem* item)
{
if (item->row() + 1 > ignoredList.size())
return;
auto ignoredRule = ignoredList.value(item->row());
-
switch (item->column()) {
- case CoreHighlightSettingsPage::EnableColumn:
- ignoredRule.setIsEnabled(item->checkState() == Qt::Checked);
- break;
- case CoreHighlightSettingsPage::NameColumn:
- ignoredRule.setContents(item->text());
- break;
- case CoreHighlightSettingsPage::RegExColumn:
- ignoredRule.setIsRegEx(item->checkState() == Qt::Checked);
- break;
- case CoreHighlightSettingsPage::CsColumn:
- ignoredRule.setIsCaseSensitive(item->checkState() == Qt::Checked);
- break;
- case CoreHighlightSettingsPage::SenderColumn:
- if (!item->text().isEmpty() && item->text().trimmed().isEmpty())
- item->setText("");
- ignoredRule.setSender(item->text());
- break;
- case CoreHighlightSettingsPage::ChanColumn:
- if (!item->text().isEmpty() && item->text().trimmed().isEmpty())
- item->setText("");
- ignoredRule.setChanName(item->text());
- break;
+ case CoreHighlightSettingsPage::EnableColumn:
+ ignoredRule.setIsEnabled(item->checkState() == Qt::Checked);
+ break;
+ case CoreHighlightSettingsPage::NameColumn:
+ ignoredRule.setContents(item->text());
+ break;
+ case CoreHighlightSettingsPage::RegExColumn:
+ ignoredRule.setIsRegEx(item->checkState() == Qt::Checked);
+ break;
+ case CoreHighlightSettingsPage::CsColumn:
+ ignoredRule.setIsCaseSensitive(item->checkState() == Qt::Checked);
+ break;
+ case CoreHighlightSettingsPage::SenderColumn:
+ if (!item->text().isEmpty() && item->text().trimmed().isEmpty())
+ item->setText("");
+ ignoredRule.setSender(item->text());
+ break;
+ case CoreHighlightSettingsPage::ChanColumn:
+ if (!item->text().isEmpty() && item->text().trimmed().isEmpty())
+ item->setText("");
+ ignoredRule.setChanName(item->text());
+ break;
}
ignoredList[item->row()] = ignoredRule;
emit widgetHasChanged();
}
-
void CoreHighlightSettingsPage::load()
{
emptyHighlightTable();
auto ruleManager = Client::highlightRuleManager();
if (ruleManager) {
- for (auto &rule : ruleManager->highlightRuleList()) {
+ for (auto& rule : ruleManager->highlightRuleList()) {
if (rule.isInverse()) {
- addNewIgnoredRow(rule.isEnabled(), rule.id(), rule.contents(), rule.isRegEx(),
- rule.isCaseSensitive(), rule.sender(), rule.chanName());
+ addNewIgnoredRow(rule.isEnabled(),
+ rule.id(),
+ rule.contents(),
+ rule.isRegEx(),
+ rule.isCaseSensitive(),
+ rule.sender(),
+ rule.chanName());
}
else {
- addNewHighlightRow(rule.isEnabled(), rule.id(), rule.contents(), rule.isRegEx(),
- rule.isCaseSensitive(), rule.sender(), rule.chanName());
+ addNewHighlightRow(rule.isEnabled(),
+ rule.id(),
+ rule.contents(),
+ rule.isRegEx(),
+ rule.isCaseSensitive(),
+ rule.sender(),
+ rule.chanName());
}
}
setChangedState(false);
_initialized = true;
- } else {
+ }
+ else {
defaults();
}
}
-
void CoreHighlightSettingsPage::save()
{
if (!hasChanged())
clonedManager.fromVariantMap(ruleManager->toVariantMap());
clonedManager.clear();
- for (auto &rule : highlightList) {
- clonedManager.addHighlightRule(rule.id(), rule.contents(), rule.isRegEx(),
- rule.isCaseSensitive(), rule.isEnabled(), false,
- rule.sender(), rule.chanName());
+ for (auto& rule : highlightList) {
+ clonedManager.addHighlightRule(rule.id(),
+ rule.contents(),
+ rule.isRegEx(),
+ rule.isCaseSensitive(),
+ rule.isEnabled(),
+ false,
+ rule.sender(),
+ rule.chanName());
}
- for (auto &rule : ignoredList) {
- clonedManager.addHighlightRule(rule.id(), rule.contents(), rule.isRegEx(),
- rule.isCaseSensitive (), rule.isEnabled(), true,
- rule.sender(), rule.chanName());
+ for (auto& rule : ignoredList) {
+ clonedManager.addHighlightRule(rule.id(),
+ rule.contents(),
+ rule.isRegEx(),
+ rule.isCaseSensitive(),
+ rule.isEnabled(),
+ true,
+ rule.sender(),
+ rule.chanName());
}
auto highlightNickType = ui.highlightNicksComboBox->itemData(ui.highlightNicksComboBox->currentIndex()).value<int>();
load();
}
-
int CoreHighlightSettingsPage::nextId()
{
int max = 0;
return max + 1;
}
-
void CoreHighlightSettingsPage::widgetHasChanged()
{
setChangedState(true);
}
-
void CoreHighlightSettingsPage::on_coreUnsupportedDetails_clicked()
{
// Re-use translations of "Local Highlights" as this is a word-for-word reference, forcing all
// spaces to non-breaking
const QString localHighlightsName = tr("Local Highlights").replace(" ", " ");
- const QString remoteHighlightsMsgText =
- QString("<p><b>%1</b></p></br><p>%2</p></br><p>%3</p>"
- ).arg(tr("Your Quassel core is too old to support remote highlights"),
- tr("You need a Quassel core v0.13.0 or newer to configure remote "
- "highlights."),
- tr("You can still configure highlights for this device only in "
- "<i>%1</i>.").arg(localHighlightsName));
-
- QMessageBox::warning(this,
- tr("Remote Highlights unsupported"),
- remoteHighlightsMsgText);
-}
+ const QString remoteHighlightsMsgText = QString("<p><b>%1</b></p></br><p>%2</p></br><p>%3</p>")
+ .arg(tr("Your Quassel core is too old to support remote highlights"),
+ tr("You need a Quassel core v0.13.0 or newer to configure remote "
+ "highlights."),
+ tr("You can still configure highlights for this device only in "
+ "<i>%1</i>.")
+ .arg(localHighlightsName));
+ QMessageBox::warning(this, tr("Remote Highlights unsupported"), remoteHighlightsMsgText);
+}
void CoreHighlightSettingsPage::importRules()
{
QString localHighlightsName;
if (Quassel::runMode() == Quassel::Monolithic) {
localHighlightsName = tr("Legacy Highlights").replace(" ", " ");
- } else {
+ }
+ else {
localHighlightsName = tr("Local Highlights").replace(" ", " ");
}
if (localHighlightList.count() == 0) {
// No highlight rules exist to import, do nothing
- QMessageBox::information(this,
- tr("No highlights to import"),
- tr("No highlight rules in <i>%1</i>."
- ).arg(localHighlightsName));
+ QMessageBox::information(this, tr("No highlights to import"), tr("No highlight rules in <i>%1</i>.").arg(localHighlightsName));
return;
}
int ret = QMessageBox::question(this,
tr("Import highlights?"),
- tr("Import all highlight rules from <i>%1</i>?"
- ).arg(localHighlightsName),
- QMessageBox::Yes|QMessageBox::No,
+ tr("Import all highlight rules from <i>%1</i>?").arg(localHighlightsName),
+ QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (ret != QMessageBox::Yes) {
auto clonedManager = HighlightRuleManager();
clonedManager.fromVariantMap(Client::highlightRuleManager()->toVariantMap());
- for (const auto &variant : notificationSettings.highlightList()) {
+ for (const auto& variant : notificationSettings.highlightList()) {
auto highlightRule = variant.toMap();
- clonedManager.addHighlightRule(
- clonedManager.nextId(),
- highlightRule["Name"].toString(),
- highlightRule["RegEx"].toBool(),
- highlightRule["CS"].toBool(),
- highlightRule["Enable"].toBool(),
- false,
- "",
- highlightRule["Channel"].toString()
- );
+ clonedManager.addHighlightRule(clonedManager.nextId(),
+ highlightRule["Name"].toString(),
+ highlightRule["RegEx"].toBool(),
+ highlightRule["CS"].toBool(),
+ highlightRule["Enable"].toBool(),
+ false,
+ "",
+ highlightRule["Channel"].toString());
}
Client::highlightRuleManager()->requestUpdate(clonedManager.toVariantMap());
// Give a heads-up that all succeeded
QMessageBox::information(this,
tr("Imported highlights"),
- tr("%1 highlight rules successfully imported."
- ).arg(QString::number(localHighlightList.count())));
+ tr("%1 highlight rules successfully imported.").arg(QString::number(localHighlightList.count())));
}
-
bool CoreHighlightSettingsPage::isSelectable() const
{
return Client::isConnected();
#pragma once
-#include <QVariantList>
#include <QTableWidgetItem>
+#include <QVariantList>
#include "highlightrulemanager.h"
#include "settingspage.h"
Q_OBJECT
public:
- explicit CoreHighlightSettingsPage(QWidget *parent = nullptr);
+ explicit CoreHighlightSettingsPage(QWidget* parent = nullptr);
bool hasDefaults() const override;
private slots:
void coreConnectionStateChanged(bool state);
void widgetHasChanged();
- void addNewHighlightRow(bool enable = true, int id = -1, const QString &name = tr("highlight rule"), bool regex = false,
- bool cs = false, const QString &sender = "", const QString &chanName = "",
+ void addNewHighlightRow(bool enable = true,
+ int id = -1,
+ const QString& name = tr("highlight rule"),
+ bool regex = false,
+ bool cs = false,
+ const QString& sender = "",
+ const QString& chanName = "",
bool self = false);
- void addNewIgnoredRow(bool enable = true, int id = -1, const QString &name = tr("highlight rule"), bool regex = false,
- bool cs = false, const QString &sender = "", const QString &chanName = "", bool self = false);
+ void addNewIgnoredRow(bool enable = true,
+ int id = -1,
+ const QString& name = tr("highlight rule"),
+ bool regex = false,
+ bool cs = false,
+ const QString& sender = "",
+ const QString& chanName = "",
+ bool self = false);
void removeSelectedHighlightRows();
void removeSelectedIgnoredRows();
void highlightNicksChanged(int index);
- void selectHighlightRow(QTableWidgetItem *item);
- void selectIgnoredRow(QTableWidgetItem *item);
- void highlightTableChanged(QTableWidgetItem *item);
- void ignoredTableChanged(QTableWidgetItem *item);
+ void selectHighlightRow(QTableWidgetItem* item);
+ void selectIgnoredRow(QTableWidgetItem* item);
+ void highlightTableChanged(QTableWidgetItem* item);
+ void ignoredTableChanged(QTableWidgetItem* item);
/** Import local Highlight rules into the Core Highlight rules
*
HighlightRuleManager::HighlightRuleList highlightList;
HighlightRuleManager::HighlightRuleList ignoredList;
- enum column {
+ enum column
+ {
EnableColumn = 0,
NameColumn = 1,
RegExColumn = 2,
void emptyHighlightTable();
void emptyIgnoredTable();
- void setupRuleTable(QTableWidget *highlightTable) const;
+ void setupRuleTable(QTableWidget* highlightTable) const;
/**
* Get tooltip for the specified rule table column
* @param senderWidget Sender name
* @param chanWidget Channel name
*/
- void setupTableTooltips(QWidget *enableWidget, QWidget *nameWidget, QWidget *regExWidget,
- QWidget *csWidget, QWidget *senderWidget, QWidget *chanWidget) const;
+ void setupTableTooltips(
+ QWidget* enableWidget, QWidget* nameWidget, QWidget* regExWidget, QWidget* csWidget, QWidget* senderWidget, QWidget* chanWidget) const;
/**
* Setup tooltips and "What's this?" prompts for table entries
* @param senderWidget Sender name
* @param chanWidget Channel name
*/
- void setupTableTooltips(QTableWidgetItem *enableWidget, QTableWidgetItem *nameWidget,
- QTableWidgetItem *regExWidget, QTableWidgetItem *csWidget,
- QTableWidgetItem *senderWidget, QTableWidgetItem *chanWidget) const;
+ void setupTableTooltips(QTableWidgetItem* enableWidget,
+ QTableWidgetItem* nameWidget,
+ QTableWidgetItem* regExWidget,
+ QTableWidgetItem* csWidget,
+ QTableWidgetItem* senderWidget,
+ QTableWidgetItem* chanWidget) const;
/** Update the UI to show core support for highlights
*
#include "clienttransfermanager.h"
#include "util.h"
-DccSettingsPage::DccSettingsPage(QWidget *parent)
+DccSettingsPage::DccSettingsPage(QWidget* parent)
: SettingsPage(tr("IRC"), tr("DCC"), parent)
{
ui.setupUi(this);
setClientConfig(Client::dccConfig());
}
-
bool DccSettingsPage::isClientConfigValid() const
{
return _clientConfig != nullptr;
}
-
-void DccSettingsPage::setClientConfig(DccConfig *config)
+void DccSettingsPage::setClientConfig(DccConfig* config)
{
if (_clientConfig) {
disconnect(_clientConfig, nullptr, this, nullptr);
}
}
-
void DccSettingsPage::onClientConfigChanged()
{
if (Client::isConnected() && Client::dccConfig() && !Client::dccConfig()->isInitialized()) {
}
}
-
bool DccSettingsPage::hasDefaults() const
{
return true;
}
-
void DccSettingsPage::defaults()
{
_localConfig = DccConfig();
widgetHasChanged();
}
-
void DccSettingsPage::load()
{
_localConfig = isClientConfigValid() ? *_clientConfig : DccConfig{};
widgetHasChanged();
}
-
void DccSettingsPage::save()
{
SettingsPage::save();
setChangedState(false);
}
-
QVariant DccSettingsPage::loadAutoWidgetValue(const QString& widgetName)
{
if (widgetName == "dccEnabled")
return {};
}
-
void DccSettingsPage::saveAutoWidgetValue(const QString& widgetName, const QVariant& value)
{
if (widgetName == "dccEnabled")
else if (widgetName == "useFastSend")
_localConfig.setUseFastSend(value.toBool());
else if (widgetName == "outgoingIp") {
- QHostAddress address {QHostAddress::LocalHost};
+ QHostAddress address{QHostAddress::LocalHost};
if (!address.setAddress(value.toString())) {
qWarning() << "Invalid IP address!";
address = QHostAddress{QHostAddress::LocalHost};
}
}
-
void DccSettingsPage::widgetHasChanged()
{
bool same = isClientConfigValid() && (_localConfig == *_clientConfig);
setChangedState(!same);
}
-
void DccSettingsPage::updateWidgetStates()
{
ui.outgoingIp->setEnabled(ui.ipDetectionMode->currentIndex() != 0);
#include "dccconfig.h"
#include "settingspage.h"
+
#include "ui_dccsettingspage.h"
/**
*
* @param[in] parent QObject parent
*/
- DccSettingsPage(QWidget *parent = nullptr);
+ DccSettingsPage(QWidget* parent = nullptr);
/// See base class docs
bool hasDefaults() const override;
*
* @param[in] config The client's config. Must be be valid or a nullptr.
*/
- void setClientConfig(DccConfig *config);
+ void setClientConfig(DccConfig* config);
// See base class docs
- QVariant loadAutoWidgetValue(const QString &widgetName) override;
- void saveAutoWidgetValue(const QString &widgetName, const QVariant &value) override;
+ QVariant loadAutoWidgetValue(const QString& widgetName) override;
+ void saveAutoWidgetValue(const QString& widgetName, const QVariant& value) override;
private slots:
/**
void onClientConfigChanged();
private:
- Ui::DccSettingsPage ui; ///< The UI object
- DccConfig *_clientConfig {nullptr}; ///< Pointer to the client's config (nullptr if not synchronized/available)
- DccConfig _localConfig; ///< Local config reflecting the widget states
+ Ui::DccSettingsPage ui; ///< The UI object
+ DccConfig* _clientConfig{nullptr}; ///< Pointer to the client's config (nullptr if not synchronized/available)
+ DccConfig _localConfig; ///< Local config reflecting the widget states
};
#include "qtui.h"
#include "uisettings.h"
-
-HighlightSettingsPage::HighlightSettingsPage(QWidget *parent)
+HighlightSettingsPage::HighlightSettingsPage(QWidget* parent)
: SettingsPage(tr("Interface"),
// In Monolithic mode, local highlights are replaced by remote highlights
- Quassel::runMode() == Quassel::Monolithic ?
- tr("Legacy Highlights") : tr("Local Highlights"),
+ Quassel::runMode() == Quassel::Monolithic ? tr("Legacy Highlights") : tr("Local Highlights"),
parent)
{
ui.setupUi(this);
ui.highlightTable->verticalHeader()->hide();
ui.highlightTable->setShowGrid(false);
-
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::EnableColumn)->setToolTip(
- tr("Enable/disable this rule"));
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::EnableColumn)->setWhatsThis(
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::EnableColumn)->toolTip());
-
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::NameColumn)->setToolTip(
- tr("Phrase to match"));
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::NameColumn)->setWhatsThis(
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::NameColumn)->toolTip());
-
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::RegExColumn)->setToolTip(
- tr("<b>RegEx</b>: This option determines if the highlight rule and <i>Channel</i> "
- "should be interpreted as <b>regular expressions</b> or just as keywords."));
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::RegExColumn)->setWhatsThis(
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::RegExColumn)->toolTip());
-
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::CsColumn)->setToolTip(
- tr("<b>CS</b>: This option determines if the highlight rule and <i>Channel</i> "
- "should be interpreted <b>case sensitive</b>."));
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::CsColumn)->setWhatsThis(
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::CsColumn)->toolTip());
-
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::ChanColumn)->setToolTip(
- tr("<p><b>Channel</b>: Semicolon separated list of channel/query names, leave "
- "blank to match any name.</p>"
- "<p><i>Example:</i><br />"
- "<i>#quassel*; #foobar; !#quasseldroid</i><br />"
- "would match on <i>#foobar</i> and any channel starting with <i>#quassel</i> "
- "except for <i>#quasseldroid</i><br />"
- "<p>If only inverted names are specified, it will match anything except for "
- "what's specified (implicit wildcard).</p>"
- "<p><i>Example:</i><br />"
- "<i>!#quassel*; !#foobar</i><br />"
- "would match anything except for <i>#foobar</i> or any channel starting with "
- "<i>#quassel</i></p>"));
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::ChanColumn)->setWhatsThis(
- ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::ChanColumn)->toolTip());
+ ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::EnableColumn)->setToolTip(tr("Enable/disable this rule"));
+ ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::EnableColumn)
+ ->setWhatsThis(ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::EnableColumn)->toolTip());
+
+ ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::NameColumn)->setToolTip(tr("Phrase to match"));
+ ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::NameColumn)
+ ->setWhatsThis(ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::NameColumn)->toolTip());
+
+ ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::RegExColumn)
+ ->setToolTip(tr("<b>RegEx</b>: This option determines if the highlight rule and <i>Channel</i> "
+ "should be interpreted as <b>regular expressions</b> or just as keywords."));
+ ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::RegExColumn)
+ ->setWhatsThis(ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::RegExColumn)->toolTip());
+
+ ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::CsColumn)
+ ->setToolTip(tr("<b>CS</b>: This option determines if the highlight rule and <i>Channel</i> "
+ "should be interpreted <b>case sensitive</b>."));
+ ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::CsColumn)
+ ->setWhatsThis(ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::CsColumn)->toolTip());
+
+ ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::ChanColumn)
+ ->setToolTip(tr("<p><b>Channel</b>: Semicolon separated list of channel/query names, leave "
+ "blank to match any name.</p>"
+ "<p><i>Example:</i><br />"
+ "<i>#quassel*; #foobar; !#quasseldroid</i><br />"
+ "would match on <i>#foobar</i> and any channel starting with <i>#quassel</i> "
+ "except for <i>#quasseldroid</i><br />"
+ "<p>If only inverted names are specified, it will match anything except for "
+ "what's specified (implicit wildcard).</p>"
+ "<p><i>Example:</i><br />"
+ "<i>!#quassel*; !#foobar</i><br />"
+ "would match anything except for <i>#foobar</i> or any channel starting with "
+ "<i>#quassel</i></p>"));
+ ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::ChanColumn)
+ ->setWhatsThis(ui.highlightTable->horizontalHeaderItem(HighlightSettingsPage::ChanColumn)->toolTip());
ui.highlightTable->horizontalHeader()->setSectionResizeMode(HighlightSettingsPage::NameColumn, QHeaderView::Stretch);
ui.highlightTable->horizontalHeader()->setSectionResizeMode(HighlightSettingsPage::RegExColumn, QHeaderView::ResizeToContents);
if (Quassel::runMode() == Quassel::Monolithic) {
// We're running in Monolithic mode, core/client version in total sync. Discourage the use
// of local (legacy) highlights as it's identical to setting remote highlights.
- ui.localHighlightsLabel->setText(
- tr("Legacy Highlights are replaced by Highlights"));
- } else {
+ ui.localHighlightsLabel->setText(tr("Legacy Highlights are replaced by Highlights"));
+ }
+ else {
// We're running in client/split mode, allow for splitting the details.
ui.localHighlightsLabel->setText(tr("Local Highlights apply to this device only"));
}
connect(ui.add, &QAbstractButton::clicked, this, [this]() { addNewRow(); });
connect(ui.remove, &QAbstractButton::clicked, this, &HighlightSettingsPage::removeSelectedRows);
- //TODO: search for a better signal (one that emits everytime a selection has been changed for one item)
+ // TODO: search for a better signal (one that emits everytime a selection has been changed for one item)
connect(ui.highlightTable, &QTableWidget::itemClicked, this, &HighlightSettingsPage::selectRow);
connect(ui.highlightAllNicks, &QAbstractButton::clicked, this, &HighlightSettingsPage::widgetHasChanged);
connect(ui.highlightTable, &QTableWidget::itemChanged, this, &HighlightSettingsPage::tableChanged);
}
-
bool HighlightSettingsPage::hasDefaults() const
{
return true;
}
-
void HighlightSettingsPage::defaults()
{
ui.highlightCurrentNick->setChecked(true);
widgetHasChanged();
}
-
void HighlightSettingsPage::addNewRow(QString name, bool regex, bool cs, bool enable, QString chanName, bool self)
{
- ui.highlightTable->setRowCount(ui.highlightTable->rowCount()+1);
+ ui.highlightTable->setRowCount(ui.highlightTable->rowCount() + 1);
- QTableWidgetItem *enableItem = new QTableWidgetItem("");
+ QTableWidgetItem* enableItem = new QTableWidgetItem("");
if (enable)
enableItem->setCheckState(Qt::Checked);
else
enableItem->setCheckState(Qt::Unchecked);
- enableItem->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt::ItemIsSelectable);
+ enableItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
- auto *nameItem = new QTableWidgetItem(name);
+ auto* nameItem = new QTableWidgetItem(name);
- QTableWidgetItem *regexItem = new QTableWidgetItem("");
+ QTableWidgetItem* regexItem = new QTableWidgetItem("");
if (regex)
regexItem->setCheckState(Qt::Checked);
else
regexItem->setCheckState(Qt::Unchecked);
- regexItem->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt::ItemIsSelectable);
+ regexItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
- QTableWidgetItem *csItem = new QTableWidgetItem("");
+ QTableWidgetItem* csItem = new QTableWidgetItem("");
if (cs)
csItem->setCheckState(Qt::Checked);
else
csItem->setCheckState(Qt::Unchecked);
- csItem->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled|Qt::ItemIsSelectable);
+ csItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
- auto *chanNameItem = new QTableWidgetItem(chanName);
+ auto* chanNameItem = new QTableWidgetItem(chanName);
enableItem->setToolTip(tr("Enable/disable this rule"));
nameItem->setToolTip(tr("Phrase to match"));
- regexItem->setToolTip(
- tr("<b>RegEx</b>: This option determines if the highlight rule and <i>Channel</i> "
- "should be interpreted as <b>regular expressions</b> or just as keywords."));
- csItem->setToolTip(
- tr("<b>CS</b>: This option determines if the highlight rule and <i>Channel</i> "
- "should be interpreted <b>case sensitive</b>."));
- chanNameItem->setToolTip(
- tr("<p><b>Channel</b>: Semicolon separated list of channel/query names, leave "
- "blank to match any name.</p>"
- "<p><i>Example:</i><br />"
- "<i>#quassel*; #foobar; !#quasseldroid</i><br />"
- "would match on <i>#foobar</i> and any channel starting with <i>#quassel</i> "
- "except for <i>#quasseldroid</i><br />"
- "<p>If only inverted names are specified, it will match anything except for "
- "what's specified (implicit wildcard).</p>"
- "<p><i>Example:</i><br />"
- "<i>!#quassel*; !#foobar</i><br />"
- "would match anything except for <i>#foobar</i> or any channel starting with "
- "<i>#quassel</i></p>"));
-
- int lastRow = ui.highlightTable->rowCount()-1;
+ regexItem->setToolTip(tr("<b>RegEx</b>: This option determines if the highlight rule and <i>Channel</i> "
+ "should be interpreted as <b>regular expressions</b> or just as keywords."));
+ csItem->setToolTip(tr("<b>CS</b>: This option determines if the highlight rule and <i>Channel</i> "
+ "should be interpreted <b>case sensitive</b>."));
+ chanNameItem->setToolTip(tr("<p><b>Channel</b>: Semicolon separated list of channel/query names, leave "
+ "blank to match any name.</p>"
+ "<p><i>Example:</i><br />"
+ "<i>#quassel*; #foobar; !#quasseldroid</i><br />"
+ "would match on <i>#foobar</i> and any channel starting with <i>#quassel</i> "
+ "except for <i>#quasseldroid</i><br />"
+ "<p>If only inverted names are specified, it will match anything except for "
+ "what's specified (implicit wildcard).</p>"
+ "<p><i>Example:</i><br />"
+ "<i>!#quassel*; !#foobar</i><br />"
+ "would match anything except for <i>#foobar</i> or any channel starting with "
+ "<i>#quassel</i></p>"));
+
+ int lastRow = ui.highlightTable->rowCount() - 1;
ui.highlightTable->setItem(lastRow, HighlightSettingsPage::EnableColumn, enableItem);
ui.highlightTable->setItem(lastRow, HighlightSettingsPage::NameColumn, nameItem);
ui.highlightTable->setItem(lastRow, HighlightSettingsPage::RegExColumn, regexItem);
highlightList.append(highlightRule);
}
-
void HighlightSettingsPage::removeSelectedRows()
{
QList<int> selectedRows;
- QList<QTableWidgetItem *> selectedItemList = ui.highlightTable->selectedItems();
- foreach(QTableWidgetItem *selectedItem, selectedItemList) {
+ QList<QTableWidgetItem*> selectedItemList = ui.highlightTable->selectedItems();
+ foreach (QTableWidgetItem* selectedItem, selectedItemList) {
selectedRows.append(selectedItem->row());
}
qSort(selectedRows.begin(), selectedRows.end(), qGreater<int>());
int lastRow = -1;
- foreach(int row, selectedRows) {
+ foreach (int row, selectedRows) {
if (row != lastRow) {
ui.highlightTable->removeRow(row);
highlightList.removeAt(row);
}
}
-
-void HighlightSettingsPage::selectRow(QTableWidgetItem *item)
+void HighlightSettingsPage::selectRow(QTableWidgetItem* item)
{
int row = item->row();
bool selected = item->isSelected();
- ui.highlightTable->setRangeSelected(QTableWidgetSelectionRange(row, 0, row, HighlightSettingsPage::ColumnCount-1), selected);
+ ui.highlightTable->setRangeSelected(QTableWidgetSelectionRange(row, 0, row, HighlightSettingsPage::ColumnCount - 1), selected);
}
-
void HighlightSettingsPage::emptyTable()
{
// ui.highlight and highlightList should have the same size, but just to make sure.
}
}
-
-void HighlightSettingsPage::tableChanged(QTableWidgetItem *item)
+void HighlightSettingsPage::tableChanged(QTableWidgetItem* item)
{
- if (item->row()+1 > highlightList.size())
+ if (item->row() + 1 > highlightList.size())
return;
QVariantMap highlightRule = highlightList.value(item->row()).toMap();
- switch (item->column())
- {
+ switch (item->column()) {
case HighlightSettingsPage::EnableColumn:
highlightRule["Enable"] = (item->checkState() == Qt::Checked);
break;
emit widgetHasChanged();
}
-
void HighlightSettingsPage::on_localHighlightsDetails_clicked()
{
// Show information specific to client/monolithic differences
if (Quassel::runMode() == Quassel::Monolithic) {
// We're running in Monolithic mode, core/client version in total sync. Discourage the use
// of local (legacy) highlights as it's identical to setting remote highlights.
- QMessageBox::information(
- this,
- tr("Legacy Highlights vs. Highlights"),
- QString("<p><b>%1</b></p></br><p>%2</p></br><p>%3</p>")
- .arg(tr("Legacy Highlights are replaced by Highlights"),
- tr("These highlights will keep working for now, but you should move to "
- "the improved highlight rules when you can."),
- tr("Configure the new style of highlights in "
- "<i>%1</i>.").arg(tr("Highlights"))));
- } else {
+ QMessageBox::information(this,
+ tr("Legacy Highlights vs. Highlights"),
+ QString("<p><b>%1</b></p></br><p>%2</p></br><p>%3</p>")
+ .arg(tr("Legacy Highlights are replaced by Highlights"),
+ tr("These highlights will keep working for now, but you should move to "
+ "the improved highlight rules when you can."),
+ tr("Configure the new style of highlights in "
+ "<i>%1</i>.")
+ .arg(tr("Highlights"))));
+ }
+ else {
// We're running in client/split mode, allow for splitting the details.
- QMessageBox::information(
- this,
- tr("Local Highlights vs. Remote Highlights"),
- QString("<p><b>%1</b></p></br><p>%2</p></br><p>%3</p>")
- .arg(tr("Local Highlights apply to this device only"),
- tr("Highlights configured on this page only apply to your current "
- "device."),
- tr("Configure highlights for all of your devices in "
- "<i>%1</i>.").arg(tr("Remote Highlights").replace(" ", " "))));
+ QMessageBox::information(this,
+ tr("Local Highlights vs. Remote Highlights"),
+ QString("<p><b>%1</b></p></br><p>%2</p></br><p>%3</p>")
+ .arg(tr("Local Highlights apply to this device only"),
+ tr("Highlights configured on this page only apply to your current "
+ "device."),
+ tr("Configure highlights for all of your devices in "
+ "<i>%1</i>.")
+ .arg(tr("Remote Highlights").replace(" ", " "))));
// Re-use translations of "Remote Highlights" as this is a word-for-word reference, forcing
// all spaces to be non-breaking
}
}
-
void HighlightSettingsPage::load()
{
NotificationSettings notificationSettings;
emptyTable();
- foreach(QVariant highlight, notificationSettings.highlightList()) {
+ foreach (QVariant highlight, notificationSettings.highlightList()) {
QVariantMap highlightRule = highlight.toMap();
QString name = highlightRule["Name"].toString();
bool regex = highlightRule["RegEx"].toBool();
addNewRow(name, regex, cs, enable, chanName, true);
}
- switch (notificationSettings.highlightNick())
- {
+ switch (notificationSettings.highlightNick()) {
case NotificationSettings::NoNick:
ui.highlightNoNick->setChecked(true);
break;
setChangedState(false);
}
-
void HighlightSettingsPage::save()
{
NotificationSettings notificationSettings;
setChangedState(false);
}
-
void HighlightSettingsPage::widgetHasChanged()
{
bool changed = testHasChanged();
- if (changed != hasChanged()) setChangedState(changed);
+ if (changed != hasChanged())
+ setChangedState(changed);
}
-
bool HighlightSettingsPage::testHasChanged()
{
NotificationSettings notificationSettings;
#ifndef _HIGHLIGHTSETTINGSPAGE_H_
#define _HIGHLIGHTSETTINGSPAGE_H_
-#include <QVariantList>
#include <QTableWidgetItem>
+#include <QVariantList>
#include "settingspage.h"
+
#include "ui_highlightsettingspage.h"
class HighlightSettingsPage : public SettingsPage
Q_OBJECT
public:
- HighlightSettingsPage(QWidget *parent = nullptr);
+ HighlightSettingsPage(QWidget* parent = nullptr);
bool hasDefaults() const override;
private slots:
void widgetHasChanged();
- void addNewRow(QString name = tr("highlight rule"), bool regex = false, bool cs = false, bool enable = true, QString chanName = "", bool self = false);
+ void addNewRow(QString name = tr("highlight rule"),
+ bool regex = false,
+ bool cs = false,
+ bool enable = true,
+ QString chanName = "",
+ bool self = false);
void removeSelectedRows();
- void selectRow(QTableWidgetItem *item);
- void tableChanged(QTableWidgetItem *item);
+ void selectRow(QTableWidgetItem* item);
+ void tableChanged(QTableWidgetItem* item);
/**
* Event handler for Local Highlights Details button
// regex: bool
// name: QString
// enable: bool
- enum column {
+ enum column
+ {
EnableColumn = 0,
NameColumn = 1,
RegExColumn = 2,
bool testHasChanged();
};
-
#endif
#include "identitiessettingspage.h"
+#include <utility>
+
#include <QInputDialog>
#include <QMessageBox>
-#include <utility>
#include "client.h"
#include "icon.h"
#include "signalproxy.h"
-IdentitiesSettingsPage::IdentitiesSettingsPage(QWidget *parent)
+IdentitiesSettingsPage::IdentitiesSettingsPage(QWidget* parent)
: SettingsPage(tr("IRC"), tr("Identities"), parent)
{
ui.setupUi(this);
ui.addIdentity->setIcon(icon::get("list-add-user"));
ui.deleteIdentity->setIcon(icon::get("list-remove-user"));
- coreConnectionStateChanged(Client::isConnected()); // need a core connection!
+ coreConnectionStateChanged(Client::isConnected()); // need a core connection!
connect(Client::instance(), &Client::coreConnectionStateChanged, this, &IdentitiesSettingsPage::coreConnectionStateChanged);
connect(Client::instance(), &Client::identityCreated, this, &IdentitiesSettingsPage::clientIdentityCreated);
currentId = 0;
}
-
void IdentitiesSettingsPage::coreConnectionStateChanged(bool connected)
{
setEnabled(connected);
}
}
-
#ifdef HAVE_SSL
void IdentitiesSettingsPage::continueUnsecured()
{
_editSsl = true;
- QHash<IdentityId, CertIdentity *>::iterator idIter;
+ QHash<IdentityId, CertIdentity*>::iterator idIter;
for (idIter = identities.begin(); idIter != identities.end(); ++idIter) {
idIter.value()->enableEditSsl();
}
ui.identityEditor->setSslState(IdentityEditWidget::AllowSsl);
}
-
#endif
void IdentitiesSettingsPage::save()
{
setEnabled(false);
- QList<CertIdentity *> toCreate, toUpdate;
+ QList<CertIdentity*> toCreate, toUpdate;
// we need to remove our temporarily created identities.
// these are going to be re-added after the core has propagated them back...
- QHash<IdentityId, CertIdentity *>::iterator i = identities.begin();
+ QHash<IdentityId, CertIdentity*>::iterator i = identities.begin();
while (i != identities.end()) {
if ((*i)->id() < 0) {
- CertIdentity *temp = *i;
+ CertIdentity* temp = *i;
i = identities.erase(i);
toCreate.append(temp);
ui.identityList->removeItem(ui.identityList->findData(temp->id().toInt()));
// canceled -> reload everything to be safe
load();
}
- foreach(Identity *id, toCreate) {
+ foreach (Identity* id, toCreate) {
id->deleteLater();
}
changedIdentities.clear();
setEnabled(true);
}
-
void IdentitiesSettingsPage::load()
{
currentId = 0;
- foreach(Identity *identity, identities.values()) {
+ foreach (Identity* identity, identities.values()) {
identity->deleteLater();
}
identities.clear();
changedIdentities.clear();
ui.identityList->clear();
setWidgetStates();
- foreach(IdentityId id, Client::identityIds()) {
+ foreach (IdentityId id, Client::identityIds()) {
clientIdentityCreated(id);
}
setChangedState(false);
}
-
void IdentitiesSettingsPage::widgetHasChanged()
{
bool changed = testHasChanged();
- if (changed != hasChanged()) setChangedState(changed);
+ if (changed != hasChanged())
+ setChangedState(changed);
}
-
void IdentitiesSettingsPage::setWidgetStates()
{
bool enabled = (ui.identityList->count() > 0);
ui.deleteIdentity->setEnabled(ui.identityList->count() > 1);
}
-
bool IdentitiesSettingsPage::testHasChanged()
{
- if (deletedIdentities.count()) return true;
+ if (deletedIdentities.count())
+ return true;
if (currentId < 0) {
- return true; // new identity
+ return true; // new identity
}
else {
if (currentId != 0) {
CertIdentity temp(currentId, this);
#ifdef HAVE_SSL
// we need to set the cert and key manually, as they aren't synced
- CertIdentity *old = identities[currentId];
+ CertIdentity* old = identities[currentId];
temp.setSslKey(old->sslKey());
temp.setSslCert(old->sslCert());
#endif
}
}
-
bool IdentitiesSettingsPage::aboutToSave()
{
ui.identityEditor->saveToIdentity(identities[currentId]);
QList<int> errors;
- foreach(Identity *id, identities.values()) {
- if (id->identityName().isEmpty()) errors.append(1);
- if (!id->nicks().count()) errors.append(2);
- if (id->realName().isEmpty()) errors.append(3);
- if (id->ident().isEmpty()) errors.append(4);
+ foreach (Identity* id, identities.values()) {
+ if (id->identityName().isEmpty())
+ errors.append(1);
+ if (!id->nicks().count())
+ errors.append(2);
+ if (id->realName().isEmpty())
+ errors.append(3);
+ if (id->ident().isEmpty())
+ errors.append(4);
}
- if (!errors.count()) return true;
+ if (!errors.count())
+ return true;
QString error(tr("<b>The following problems need to be corrected before your changes can be applied:</b><ul>"));
- if (errors.contains(1)) error += tr("<li>All identities need an identity name set</li>");
- if (errors.contains(2)) error += tr("<li>Every identity needs at least one nickname defined</li>");
- if (errors.contains(3)) error += tr("<li>You need to specify a real name for every identity</li>");
- if (errors.contains(4)) error += tr("<li>You need to specify an ident for every identity</li>");
+ if (errors.contains(1))
+ error += tr("<li>All identities need an identity name set</li>");
+ if (errors.contains(2))
+ error += tr("<li>Every identity needs at least one nickname defined</li>");
+ if (errors.contains(3))
+ error += tr("<li>You need to specify a real name for every identity</li>");
+ if (errors.contains(4))
+ error += tr("<li>You need to specify an ident for every identity</li>");
error += tr("</ul>");
QMessageBox::warning(this, tr("One or more identities are invalid"), error);
return false;
}
-
void IdentitiesSettingsPage::clientIdentityCreated(IdentityId id)
{
- auto *identity = new CertIdentity(*Client::identity(id), this);
+ auto* identity = new CertIdentity(*Client::identity(id), this);
#ifdef HAVE_SSL
identity->enableEditSsl(_editSsl);
#endif
connect(Client::identity(id), &SyncableObject::updatedRemotely, this, &IdentitiesSettingsPage::clientIdentityUpdated);
}
-
void IdentitiesSettingsPage::clientIdentityUpdated()
{
- const Identity *clientIdentity = qobject_cast<Identity *>(sender());
+ const Identity* clientIdentity = qobject_cast<Identity*>(sender());
if (!clientIdentity) {
qWarning() << "Invalid identity to update!";
return;
return;
}
- CertIdentity *identity = identities[clientIdentity->id()];
+ CertIdentity* identity = identities[clientIdentity->id()];
if (identity->identityName() != clientIdentity->identityName())
renameIdentity(identity->id(), clientIdentity->identityName());
ui.identityEditor->displayIdentity(identity);
}
-
void IdentitiesSettingsPage::clientIdentityRemoved(IdentityId id)
{
if (identities.contains(id)) {
}
}
-
-void IdentitiesSettingsPage::insertIdentity(CertIdentity *identity)
+void IdentitiesSettingsPage::insertIdentity(CertIdentity* identity)
{
IdentityId id = identity->id();
identities[id] = identity;
widgetHasChanged();
}
-
-void IdentitiesSettingsPage::renameIdentity(IdentityId id, const QString &newName)
+void IdentitiesSettingsPage::renameIdentity(IdentityId id, const QString& newName)
{
- Identity *identity = identities[id];
+ Identity* identity = identities[id];
ui.identityList->setItemText(ui.identityList->findData(identity->id().toInt()), newName);
identity->setIdentityName(newName);
}
-
-void IdentitiesSettingsPage::removeIdentity(Identity *id)
+void IdentitiesSettingsPage::removeIdentity(Identity* id)
{
identities.remove(id->id());
ui.identityList->removeItem(ui.identityList->findData(id->id().toInt()));
changedIdentities.removeAll(id->id());
- if (currentId == id->id()) currentId = 0;
+ if (currentId == id->id())
+ currentId = 0;
id->deleteLater();
setWidgetStates();
widgetHasChanged();
}
-
void IdentitiesSettingsPage::on_identityList_currentIndexChanged(int index)
{
- CertIdentity *previousIdentity = nullptr;
+ CertIdentity* previousIdentity = nullptr;
if (currentId != 0 && identities.contains(currentId))
previousIdentity = identities[currentId];
if (index < 0) {
- //ui.identityList->setEditable(false);
+ // ui.identityList->setEditable(false);
ui.identityEditor->displayIdentity(nullptr, previousIdentity);
currentId = 0;
}
}
}
-
void IdentitiesSettingsPage::on_addIdentity_clicked()
{
CreateIdentityDlg dlg(ui.identityList->model(), this);
// find a free (negative) ID
IdentityId id;
for (id = 1; id <= identities.count(); id++) {
- if (!identities.keys().contains(-id.toInt())) break;
+ if (!identities.keys().contains(-id.toInt()))
+ break;
}
id = -id.toInt();
- auto *newId = new CertIdentity(id, this);
+ auto* newId = new CertIdentity(id, this);
#ifdef HAVE_SSL
newId->enableEditSsl(_editSsl);
#endif
}
}
-
void IdentitiesSettingsPage::on_deleteIdentity_clicked()
{
- Identity *id = identities[currentId];
- int ret = QMessageBox::question(this, tr("Delete Identity?"),
- tr("Do you really want to delete identity \"%1\"?").arg(id->identityName()),
- QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
- if (ret != QMessageBox::Yes) return;
- if (id->id() > 0) deletedIdentities.append(id->id());
+ Identity* id = identities[currentId];
+ int ret = QMessageBox::question(this,
+ tr("Delete Identity?"),
+ tr("Do you really want to delete identity \"%1\"?").arg(id->identityName()),
+ QMessageBox::Yes | QMessageBox::No,
+ QMessageBox::No);
+ if (ret != QMessageBox::Yes)
+ return;
+ if (id->id() > 0)
+ deletedIdentities.append(id->id());
currentId = 0;
removeIdentity(id);
}
-
void IdentitiesSettingsPage::on_renameIdentity_clicked()
{
QString oldName = identities[currentId]->identityName();
bool ok = false;
- QString name = QInputDialog::getText(this, tr("Rename Identity"),
- tr("Please enter a new name for the identity \"%1\"!").arg(oldName),
- QLineEdit::Normal, oldName, &ok);
+ QString name = QInputDialog::getText(this,
+ tr("Rename Identity"),
+ tr("Please enter a new name for the identity \"%1\"!").arg(oldName),
+ QLineEdit::Normal,
+ oldName,
+ &ok);
if (ok && !name.isEmpty()) {
renameIdentity(currentId, name);
widgetHasChanged();
}
}
-
/*****************************************************************************************/
-CreateIdentityDlg::CreateIdentityDlg(QAbstractItemModel *model, QWidget *parent)
+CreateIdentityDlg::CreateIdentityDlg(QAbstractItemModel* model, QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
- ui.identityList->setModel(model); // now we use the identity list of the main page... Trolltech <3
- on_identityName_textChanged(""); // disable ok button :)
+ ui.identityList->setModel(model); // now we use the identity list of the main page... Trolltech <3
+ on_identityName_textChanged(""); // disable ok button :)
}
-
QString CreateIdentityDlg::identityName() const
{
return ui.identityName->text();
}
-
IdentityId CreateIdentityDlg::duplicateId() const
{
- if (!ui.duplicateIdentity->isChecked()) return 0;
+ if (!ui.duplicateIdentity->isChecked())
+ return 0;
if (ui.identityList->currentIndex() >= 0) {
return ui.identityList->itemData(ui.identityList->currentIndex()).toInt();
}
return 0;
}
-
-void CreateIdentityDlg::on_identityName_textChanged(const QString &text)
+void CreateIdentityDlg::on_identityName_textChanged(const QString& text)
{
ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(text.count());
}
-
/*********************************************************************************************/
-SaveIdentitiesDlg::SaveIdentitiesDlg(const QList<CertIdentity *> &toCreate, const QList<CertIdentity *> &toUpdate, const QList<IdentityId> &toRemove, QWidget *parent)
+SaveIdentitiesDlg::SaveIdentitiesDlg(const QList<CertIdentity*>& toCreate,
+ const QList<CertIdentity*>& toUpdate,
+ const QList<IdentityId>& toRemove,
+ QWidget* parent)
: QDialog(parent)
{
ui.setupUi(this);
connect(Client::instance(), &Client::identityCreated, this, &SaveIdentitiesDlg::clientEvent);
connect(Client::instance(), &Client::identityRemoved, this, &SaveIdentitiesDlg::clientEvent);
- foreach(CertIdentity *id, toCreate) {
+ foreach (CertIdentity* id, toCreate) {
Client::createIdentity(*id);
}
- foreach(CertIdentity *id, toUpdate) {
- const Identity *cid = Client::identity(id->id());
+ foreach (CertIdentity* id, toUpdate) {
+ const Identity* cid = Client::identity(id->id());
if (!cid) {
qWarning() << "Invalid client identity!";
numevents--;
id->requestUpdateSslSettings();
#endif
}
- foreach(IdentityId id, toRemove) {
+ foreach (IdentityId id, toRemove) {
Client::removeIdentity(id);
}
}
}
}
-
void SaveIdentitiesDlg::clientEvent()
{
ui.progressBar->setValue(++rcvevents);
- if (rcvevents >= numevents) accept();
+ if (rcvevents >= numevents)
+ accept();
}
-
/*************************************************************************************************/
-NickEditDlg::NickEditDlg(const QString &old, QStringList exist, QWidget *parent)
- : QDialog(parent), oldNick(old), existing(std::move(exist))
+NickEditDlg::NickEditDlg(const QString& old, QStringList exist, QWidget* parent)
+ : QDialog(parent)
+ , oldNick(old)
+ , existing(std::move(exist))
{
ui.setupUi(this);
if (old.isEmpty()) {
// new nick
setWindowTitle(tr("Add Nickname"));
- on_nickEdit_textChanged(""); // disable ok button
+ on_nickEdit_textChanged(""); // disable ok button
}
- else ui.nickEdit->setText(old);
+ else
+ ui.nickEdit->setText(old);
}
-
QString NickEditDlg::nick() const
{
return ui.nickEdit->text();
}
-
-void NickEditDlg::on_nickEdit_textChanged(const QString &text)
+void NickEditDlg::on_nickEdit_textChanged(const QString& text)
{
ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text));
}
#pragma once
#include "clientidentity.h"
-#include "settingspage.h"
-
#include "identityeditwidget.h"
+#include "settingspage.h"
-#include "ui_identitiessettingspage.h"
#include "ui_createidentitydlg.h"
+#include "ui_identitiessettingspage.h"
#include "ui_saveidentitiesdlg.h"
class QAbstractItemModel;
Q_OBJECT
public:
- IdentitiesSettingsPage(QWidget *parent = nullptr);
+ IdentitiesSettingsPage(QWidget* parent = nullptr);
inline bool needsCoreConnection() const override { return true; }
private:
Ui::IdentitiesSettingsPage ui;
- QHash<IdentityId, CertIdentity *> identities;
+ QHash<IdentityId, CertIdentity*> identities;
IdentityId currentId;
- QList<IdentityId> changedIdentities; // for setting the widget changed state
+ QList<IdentityId> changedIdentities; // for setting the widget changed state
QList<IdentityId> deletedIdentities;
bool _editSsl{false};
- void insertIdentity(CertIdentity *identity);
- void removeIdentity(Identity *identity);
- void renameIdentity(IdentityId id, const QString &newName);
+ void insertIdentity(CertIdentity* identity);
+ void removeIdentity(Identity* identity);
+ void renameIdentity(IdentityId id, const QString& newName);
#ifdef HAVE_SSL
- QSslKey keyByFilename(const QString &filename);
- void showKeyState(const QSslKey &key);
- QSslCertificate certByFilename(const QString &filename);
- void showCertState(const QSslCertificate &cert);
+ QSslKey keyByFilename(const QString& filename);
+ void showKeyState(const QSslKey& key);
+ QSslCertificate certByFilename(const QString& filename);
+ void showCertState(const QSslCertificate& cert);
#endif
bool testHasChanged();
};
-
// ==============================
// Various Dialogs
// ==============================
Q_OBJECT
public:
- CreateIdentityDlg(QAbstractItemModel *model, QWidget *parent = nullptr);
+ CreateIdentityDlg(QAbstractItemModel* model, QWidget* parent = nullptr);
QString identityName() const;
IdentityId duplicateId() const;
private slots:
- void on_identityName_textChanged(const QString &text);
+ void on_identityName_textChanged(const QString& text);
private:
Ui::CreateIdentityDlg ui;
};
-
class SaveIdentitiesDlg : public QDialog
{
Q_OBJECT
public:
- SaveIdentitiesDlg(const QList<CertIdentity *> &toCreate, const QList<CertIdentity *> &toUpdate, const QList<IdentityId> &toRemove, QWidget *parent = nullptr);
+ SaveIdentitiesDlg(const QList<CertIdentity*>& toCreate,
+ const QList<CertIdentity*>& toUpdate,
+ const QList<IdentityId>& toRemove,
+ QWidget* parent = nullptr);
private slots:
void clientEvent();
#include <QFileDialog>
#include <QMessageBox>
#include <QMimeData>
-#include <QUrl>
#include <QStandardPaths>
+#include <QUrl>
#include "client.h"
#include "icon.h"
#include "util.h"
-IdentityEditWidget::IdentityEditWidget(QWidget *parent)
+IdentityEditWidget::IdentityEditWidget(QWidget* parent)
: QWidget(parent)
{
ui.setupUi(this);
connect(ui.continueUnsecured, &QAbstractButton::clicked, this, &IdentityEditWidget::requestEditSsl);
// we would need this if we enabled drag and drop in the nicklist...
- //connect(ui.nicknameList, &QListWidget::rowsInserted, this, &IdentityEditWidget::setWidgetStates);
- //connect(ui.nicknameList->model(), &NickListModel::rowsInserted, this, IdentityEditWidget::nicklistHasChanged);
+ // connect(ui.nicknameList, &QListWidget::rowsInserted, this, &IdentityEditWidget::setWidgetStates);
+ // connect(ui.nicknameList->model(), &NickListModel::rowsInserted, this, IdentityEditWidget::nicklistHasChanged);
// disabling unused stuff
ui.autoAwayEnabled->hide();
if (Client::isCoreFeatureEnabled(Quassel::Feature::AwayFormatTimestamp)) {
// Core allows formatting %%timestamp%% messages in away strings. Update tooltips.
QString strFormatTooltip;
- QTextStream formatTooltip( &strFormatTooltip, QIODevice::WriteOnly );
+ QTextStream formatTooltip(&strFormatTooltip, QIODevice::WriteOnly);
formatTooltip << "<qt><style>.bold { font-weight: bold; } "
".italic { font-style: italic; }</style>";
// Function to add a row to the tooltip table
auto addRow = [&](const QString& key, const QString& value, bool condition) {
if (condition) {
- formatTooltip << "<tr><td class='bold' align='right'>"
- << key << "</td><td>" << value << "</td></tr>";
+ formatTooltip << "<tr><td class='bold' align='right'>" << key << "</td><td>" << value << "</td></tr>";
}
};
// Original tooltip goes here
formatTooltip << "<p>%1</p>";
// New timestamp formatting guide here
- formatTooltip << "<p>" << tr("You can add date/time to this message "
- "using the syntax: "
- "<br/>%%<span class='italic'><format></span>%%, where "
- "<span class='italic'><format></span> is:") << "</p>";
+ formatTooltip << "<p>"
+ << tr("You can add date/time to this message "
+ "using the syntax: "
+ "<br/>%%<span class='italic'><format></span>%%, where "
+ "<span class='italic'><format></span> is:")
+ << "</p>";
formatTooltip << "<table cellspacing='5' cellpadding='0'>";
addRow("hh", tr("the hour"), true);
addRow("mm", tr("the minutes"), true);
addRow("t", tr("current timezone"), true);
formatTooltip << "</table>";
formatTooltip << "<p>" << tr("Example: Away since %%hh:mm%% on %%dd.MM%%.") << "</p>";
- formatTooltip << "<p>" << tr("%%%% without anything inside represents %%. Other format "
- "codes are available.") << "</p>";
+ formatTooltip << "<p>"
+ << tr("%%%% without anything inside represents %%. Other format "
+ "codes are available.")
+ << "</p>";
formatTooltip << "</qt>";
// Split up the message to allow re-using translations:
// [Original tool-tip] [Timestamp format message]
ui.awayReason->setToolTip(strFormatTooltip.arg(ui.awayReason->toolTip()));
ui.detachAwayEnabled->setToolTip(strFormatTooltip.arg(ui.detachAwayEnabled->toolTip()));
- } // else: Do nothing, leave the original translated string
+ } // else: Do nothing, leave the original translated string
}
-
void IdentityEditWidget::setWidgetStates()
{
if (ui.nicknameList->selectedItems().count()) {
ui.renameNick->setEnabled(true);
ui.nickUp->setEnabled(ui.nicknameList->row(ui.nicknameList->selectedItems()[0]) > 0);
- ui.nickDown->setEnabled(ui.nicknameList->row(ui.nicknameList->selectedItems()[0]) < ui.nicknameList->count()-1);
+ ui.nickDown->setEnabled(ui.nicknameList->row(ui.nicknameList->selectedItems()[0]) < ui.nicknameList->count() - 1);
}
else {
ui.renameNick->setDisabled(true);
ui.deleteNick->setEnabled(ui.nicknameList->count() > 1);
}
-
-void IdentityEditWidget::displayIdentity(CertIdentity *id, CertIdentity *saveId)
+void IdentityEditWidget::displayIdentity(CertIdentity* id, CertIdentity* saveId)
{
if (saveId) {
saveToIdentity(saveId);
ui.realName->setText(id->realName());
ui.nicknameList->clear();
ui.nicknameList->addItems(id->nicks());
- //for(int i = 0; i < ui.nicknameList->count(); i++) {
+ // for(int i = 0; i < ui.nicknameList->count(); i++) {
// ui.nicknameList->item(i)->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEditable|Qt::ItemIsEnabled);
//}
- if (ui.nicknameList->count()) ui.nicknameList->setCurrentRow(0);
+ if (ui.nicknameList->count())
+ ui.nicknameList->setCurrentRow(0);
ui.awayNick->setText(id->awayNick());
ui.awayReason->setText(id->awayReason());
ui.autoAwayEnabled->setChecked(id->autoAwayEnabled());
#endif
}
-
-void IdentityEditWidget::saveToIdentity(CertIdentity *id)
+void IdentityEditWidget::saveToIdentity(CertIdentity* id)
{
QRegExp linebreaks = QRegExp("[\\r\\n]");
id->setRealName(ui.realName->text());
id->setPartReason(ui.partReason->text().remove(linebreaks));
id->setQuitReason(ui.quitReason->text().remove(linebreaks));
#ifdef HAVE_SSL
- id->setSslKey(QSslKey(ui.keyTypeLabel->property("sslKey").toByteArray(), (QSsl::KeyAlgorithm)(ui.keyTypeLabel->property("sslKeyType").toInt())));
+ id->setSslKey(
+ QSslKey(ui.keyTypeLabel->property("sslKey").toByteArray(), (QSsl::KeyAlgorithm)(ui.keyTypeLabel->property("sslKeyType").toInt())));
id->setSslCert(QSslCertificate(ui.certOrgLabel->property("sslCert").toByteArray()));
#endif
}
-
void IdentityEditWidget::on_addNick_clicked()
{
QStringList existing;
- for (int i = 0; i < ui.nicknameList->count(); i++) existing << ui.nicknameList->item(i)->text();
+ for (int i = 0; i < ui.nicknameList->count(); i++)
+ existing << ui.nicknameList->item(i)->text();
NickEditDlg dlg(QString(), existing, this);
if (dlg.exec() == QDialog::Accepted) {
ui.nicknameList->addItem(dlg.nick());
- ui.nicknameList->setCurrentRow(ui.nicknameList->count()-1);
+ ui.nicknameList->setCurrentRow(ui.nicknameList->count() - 1);
setWidgetStates();
emit widgetHasChanged();
}
}
-
void IdentityEditWidget::on_deleteNick_clicked()
{
// no confirmation, since a nickname is really nothing hard to recreate
if (ui.nicknameList->selectedItems().count()) {
delete ui.nicknameList->takeItem(ui.nicknameList->row(ui.nicknameList->selectedItems()[0]));
- ui.nicknameList->setCurrentRow(qMin(ui.nicknameList->currentRow()+1, ui.nicknameList->count()-1));
+ ui.nicknameList->setCurrentRow(qMin(ui.nicknameList->currentRow() + 1, ui.nicknameList->count() - 1));
setWidgetStates();
emit widgetHasChanged();
}
}
-
void IdentityEditWidget::on_renameNick_clicked()
{
- if (!ui.nicknameList->selectedItems().count()) return;
+ if (!ui.nicknameList->selectedItems().count())
+ return;
QString old = ui.nicknameList->selectedItems()[0]->text();
QStringList existing;
- for (int i = 0; i < ui.nicknameList->count(); i++) existing << ui.nicknameList->item(i)->text();
+ for (int i = 0; i < ui.nicknameList->count(); i++)
+ existing << ui.nicknameList->item(i)->text();
NickEditDlg dlg(old, existing, this);
if (dlg.exec() == QDialog::Accepted) {
ui.nicknameList->selectedItems()[0]->setText(dlg.nick());
}
}
-
void IdentityEditWidget::on_nickUp_clicked()
{
- if (!ui.nicknameList->selectedItems().count()) return;
+ if (!ui.nicknameList->selectedItems().count())
+ return;
int row = ui.nicknameList->row(ui.nicknameList->selectedItems()[0]);
if (row > 0) {
- ui.nicknameList->insertItem(row-1, ui.nicknameList->takeItem(row));
- ui.nicknameList->setCurrentRow(row-1);
+ ui.nicknameList->insertItem(row - 1, ui.nicknameList->takeItem(row));
+ ui.nicknameList->setCurrentRow(row - 1);
setWidgetStates();
emit widgetHasChanged();
}
}
-
void IdentityEditWidget::on_nickDown_clicked()
{
- if (!ui.nicknameList->selectedItems().count()) return;
+ if (!ui.nicknameList->selectedItems().count())
+ return;
int row = ui.nicknameList->row(ui.nicknameList->selectedItems()[0]);
- if (row < ui.nicknameList->count()-1) {
- ui.nicknameList->insertItem(row+1, ui.nicknameList->takeItem(row));
- ui.nicknameList->setCurrentRow(row+1);
+ if (row < ui.nicknameList->count() - 1) {
+ ui.nicknameList->insertItem(row + 1, ui.nicknameList->takeItem(row));
+ ui.nicknameList->setCurrentRow(row + 1);
setWidgetStates();
emit widgetHasChanged();
}
}
-
void IdentityEditWidget::showAdvanced(bool advanced)
{
int idx = ui.tabWidget->indexOf(ui.advancedTab);
}
}
-
void IdentityEditWidget::setSslState(SslState state)
{
switch (state) {
}
}
-
#ifdef HAVE_SSL
-bool IdentityEditWidget::eventFilter(QObject *watched, QEvent *event)
+bool IdentityEditWidget::eventFilter(QObject* watched, QEvent* event)
{
bool isCert = (watched == ui.sslCertGroupBox);
switch (event->type()) {
case QEvent::DragEnter:
- sslDragEnterEvent(static_cast<QDragEnterEvent *>(event));
+ sslDragEnterEvent(static_cast<QDragEnterEvent*>(event));
return true;
case QEvent::Drop:
- sslDropEvent(static_cast<QDropEvent *>(event), isCert);
+ sslDropEvent(static_cast<QDropEvent*>(event), isCert);
return true;
default:
return false;
}
}
-
-void IdentityEditWidget::sslDragEnterEvent(QDragEnterEvent *event)
+void IdentityEditWidget::sslDragEnterEvent(QDragEnterEvent* event)
{
if (event->mimeData()->hasFormat("text/uri-list") || event->mimeData()->hasFormat("text/uri")) {
event->setDropAction(Qt::CopyAction);
}
}
-
-void IdentityEditWidget::sslDropEvent(QDropEvent *event, bool isCert)
+void IdentityEditWidget::sslDropEvent(QDropEvent* event, bool isCert)
{
QByteArray rawUris;
if (event->mimeData()->hasFormat("text/uri-list"))
emit widgetHasChanged();
}
-
void IdentityEditWidget::on_clearOrLoadKeyButton_clicked()
{
QSslKey key;
if (ui.keyTypeLabel->property("sslKey").toByteArray().isEmpty())
- key = keyByFilename(QFileDialog::getOpenFileName(this, tr("Load a Key"), QStandardPaths::writableLocation(QStandardPaths::HomeLocation)));
+ key = keyByFilename(
+ QFileDialog::getOpenFileName(this, tr("Load a Key"), QStandardPaths::writableLocation(QStandardPaths::HomeLocation)));
showKeyState(key);
emit widgetHasChanged();
}
-
-QSslKey IdentityEditWidget::keyByFilename(const QString &filename)
+QSslKey IdentityEditWidget::keyByFilename(const QString& filename)
{
QSslKey key;
goto returnKey;
}
}
- QMessageBox::information(this, tr("Failed to read key"), tr("Failed to read the key file. It is either incompatible or invalid. Note that the key file must not have a passphrase."));
+ QMessageBox::information(
+ this,
+ tr("Failed to read key"),
+ tr("Failed to read the key file. It is either incompatible or invalid. Note that the key file must not have a passphrase."));
returnKey:
- if(!key.isNull() && key.algorithm() == QSsl::KeyAlgorithm::Ec && !Client::isCoreFeatureEnabled(Quassel::Feature::EcdsaCertfpKeys)) {
- QMessageBox::information(this, tr("Core does not support ECDSA keys"), tr("You loaded an ECDSA key, but the core does not support ECDSA keys. Please contact the core administrator."));
+ if (!key.isNull() && key.algorithm() == QSsl::KeyAlgorithm::Ec && !Client::isCoreFeatureEnabled(Quassel::Feature::EcdsaCertfpKeys)) {
+ QMessageBox::
+ information(this,
+ tr("Core does not support ECDSA keys"),
+ tr("You loaded an ECDSA key, but the core does not support ECDSA keys. Please contact the core administrator."));
key.clear();
}
return key;
}
-
-void IdentityEditWidget::showKeyState(const QSslKey &key)
+void IdentityEditWidget::showKeyState(const QSslKey& key)
{
if (key.isNull()) {
ui.keyTypeLabel->setText(tr("No Key loaded"));
ui.keyTypeLabel->setProperty("sslKeyType", (int)key.algorithm());
}
-
void IdentityEditWidget::on_clearOrLoadCertButton_clicked()
{
QSslCertificate cert;
if (ui.certOrgLabel->property("sslCert").toByteArray().isEmpty())
- cert = certByFilename(QFileDialog::getOpenFileName(this, tr("Load a Certificate"), QStandardPaths::writableLocation(QStandardPaths::HomeLocation)));
+ cert = certByFilename(
+ QFileDialog::getOpenFileName(this, tr("Load a Certificate"), QStandardPaths::writableLocation(QStandardPaths::HomeLocation)));
showCertState(cert);
emit widgetHasChanged();
}
-
-QSslCertificate IdentityEditWidget::certByFilename(const QString &filename)
+QSslCertificate IdentityEditWidget::certByFilename(const QString& filename)
{
QSslCertificate cert;
QFile certFile(filename);
return cert;
}
-
-void IdentityEditWidget::showCertState(const QSslCertificate &cert)
+void IdentityEditWidget::showCertState(const QSslCertificate& cert)
{
if (cert.isNull()) {
ui.certOrgLabel->setText(tr("No Certificate loaded"));
ui.certOrgLabel->setProperty("sslCert", cert.toPem());
}
-
-#endif //HAVE_SSL
+#endif // HAVE_SSL
#include "ui_nickeditdlg.h"
#ifdef HAVE_SSL
-#include <QSslCertificate>
-#include <QSslKey>
+# include <QSslCertificate>
+# include <QSslKey>
#endif
#include "clientidentity.h"
Q_OBJECT
public:
- IdentityEditWidget(QWidget *parent = nullptr);
+ IdentityEditWidget(QWidget* parent = nullptr);
- enum SslState {
+ enum SslState
+ {
NoSsl,
UnsecureSsl,
AllowSsl
};
- void displayIdentity(CertIdentity *id, CertIdentity *saveId = nullptr);
- void saveToIdentity(CertIdentity *id);
+ void displayIdentity(CertIdentity* id, CertIdentity* saveId = nullptr);
+ void saveToIdentity(CertIdentity* id);
public slots:
void setSslState(SslState state);
protected:
#ifdef HAVE_SSL
- bool eventFilter(QObject *watched, QEvent *event) override;
+ bool eventFilter(QObject* watched, QEvent* event) override;
#endif
signals:
void setWidgetStates();
#ifdef HAVE_SSL
- void sslDragEnterEvent(QDragEnterEvent *event);
- void sslDropEvent(QDropEvent *event, bool isCert);
+ void sslDragEnterEvent(QDragEnterEvent* event);
+ void sslDropEvent(QDropEvent* event, bool isCert);
#endif
private:
bool _editSsl;
#ifdef HAVE_SSL
- QSslKey keyByFilename(const QString &filename);
- void showKeyState(const QSslKey &key);
- QSslCertificate certByFilename(const QString &filename);
- void showCertState(const QSslCertificate &cert);
+ QSslKey keyByFilename(const QString& filename);
+ void showKeyState(const QSslKey& key);
+ QSslCertificate certByFilename(const QString& filename);
+ void showCertState(const QSslCertificate& cert);
#endif
bool testHasChanged();
};
-
class NickEditDlg : public QDialog
{
Q_OBJECT
public:
- NickEditDlg(const QString &oldnick, QStringList existing = QStringList(), QWidget *parent = nullptr);
+ NickEditDlg(const QString& oldnick, QStringList existing = QStringList(), QWidget* parent = nullptr);
QString nick() const;
private slots:
- void on_nickEdit_textChanged(const QString &);
+ void on_nickEdit_textChanged(const QString&);
private:
Ui::NickEditDlg ui;
QStringList existing;
};
-
-#endif //IDENTITYEDITWIDGET_H
+#endif // IDENTITYEDITWIDGET_H
#include "ignorelistmodel.h"
#include <QDebug>
-#include <QStringList>
#include <QPushButton>
+#include <QStringList>
#include "client.h"
#include "signalproxy.h"
-IgnoreListModel::IgnoreListModel(QObject *parent)
+IgnoreListModel::IgnoreListModel(QObject* parent)
: QAbstractItemModel(parent)
{
// we need this signal for future connects to reset the data;
emit modelReady(false);
}
-
-QVariant IgnoreListModel::data(const QModelIndex &index, int role) const
+QVariant IgnoreListModel::data(const QModelIndex& index, int role) const
{
if (!_modelReady)
return QVariant();
}
}
-
-bool IgnoreListModel::setData(const QModelIndex &index, const QVariant &value, int role)
+bool IgnoreListModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!_modelReady)
return false;
cloneIgnoreListManager()[index.row()].setIsEnabled(newValue.toBool());
return true;
case 1:
- cloneIgnoreListManager()[index.row()].setType(
- (IgnoreListManager::IgnoreType)newValue.toInt());
+ cloneIgnoreListManager()[index.row()].setType((IgnoreListManager::IgnoreType)newValue.toInt());
return true;
case 2:
if (ignoreListManager().contains(newValue.toString())) {
}
}
-
-bool IgnoreListModel::newIgnoreRule(const IgnoreListManager::IgnoreListItem &item)
+bool IgnoreListModel::newIgnoreRule(const IgnoreListManager::IgnoreListItem& item)
{
- IgnoreListManager &manager = cloneIgnoreListManager();
+ IgnoreListManager& manager = cloneIgnoreListManager();
if (manager.contains(item.contents()))
return false;
beginInsertRows(QModelIndex(), rowCount(), rowCount());
// manager.addIgnoreListItem(item);
- manager.addIgnoreListItem(item.type(), item.contents(), item.isRegEx(), item.strictness(),
- item.scope(), item.scopeRule(), item.isEnabled());
+ manager.addIgnoreListItem(item.type(), item.contents(), item.isRegEx(), item.strictness(), item.scope(), item.scopeRule(), item.isEnabled());
endInsertRows();
return true;
}
-
void IgnoreListModel::loadDefaults()
{
/*if(!_modelReady)
endInsertRows();*/
}
-
void IgnoreListModel::removeIgnoreRule(int index)
{
if (index < 0 || index >= rowCount())
return;
- IgnoreListManager &manager = cloneIgnoreListManager();
+ IgnoreListManager& manager = cloneIgnoreListManager();
beginRemoveRows(QModelIndex(), index, index);
manager.removeAt(index);
endRemoveRows();
}
-
-Qt::ItemFlags IgnoreListModel::flags(const QModelIndex &index) const
+Qt::ItemFlags IgnoreListModel::flags(const QModelIndex& index) const
{
if (!index.isValid()) {
return Qt::ItemIsDropEnabled;
}
}
-
QVariant IgnoreListModel::headerData(int section, Qt::Orientation orientation, int role) const
{
QStringList header;
- header << tr("Enabled")
- << tr("Type")
- << tr("Ignore Rule");
+ header << tr("Enabled") << tr("Type") << tr("Ignore Rule");
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return header[section];
return QVariant();
}
-
-QModelIndex IgnoreListModel::index(int row, int column, const QModelIndex &parent) const
+QModelIndex IgnoreListModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
if (row >= rowCount() || column >= columnCount())
return createIndex(row, column);
}
-
-const IgnoreListManager &IgnoreListModel::ignoreListManager() const
+const IgnoreListManager& IgnoreListModel::ignoreListManager() const
{
if (_configChanged)
return _clonedIgnoreListManager;
return *Client::ignoreListManager();
}
-
-IgnoreListManager &IgnoreListModel::ignoreListManager()
+IgnoreListManager& IgnoreListModel::ignoreListManager()
{
if (_configChanged)
return _clonedIgnoreListManager;
return *Client::ignoreListManager();
}
-
-IgnoreListManager &IgnoreListModel::cloneIgnoreListManager()
+IgnoreListManager& IgnoreListModel::cloneIgnoreListManager()
{
if (!_configChanged) {
_clonedIgnoreListManager = *Client::ignoreListManager();
return _clonedIgnoreListManager;
}
-
void IgnoreListModel::revert()
{
if (!_configChanged)
endResetModel();
}
-
void IgnoreListModel::commit()
{
if (!_configChanged)
revert();
}
-
void IgnoreListModel::initDone()
{
_modelReady = true;
emit modelReady(true);
}
-
void IgnoreListModel::clientConnected()
{
connect(Client::ignoreListManager(), &IgnoreListManager::updated, this, &IgnoreListModel::revert);
connect(Client::ignoreListManager(), &SyncableObject::initDone, this, &IgnoreListModel::initDone);
}
-
void IgnoreListModel::clientDisconnected()
{
// clear
emit modelReady(false);
}
-
-const IgnoreListManager::IgnoreListItem &IgnoreListModel::ignoreListItemAt(int row) const
+const IgnoreListManager::IgnoreListItem& IgnoreListModel::ignoreListItemAt(int row) const
{
return ignoreListManager()[row];
}
-
// FIXME use QModelIndex?
-void IgnoreListModel::setIgnoreListItemAt(int row, const IgnoreListManager::IgnoreListItem &item)
+void IgnoreListModel::setIgnoreListItemAt(int row, const IgnoreListManager::IgnoreListItem& item)
{
cloneIgnoreListManager()[row] = item;
emit dataChanged(createIndex(row, 0), createIndex(row, 2));
}
-
-const QModelIndex IgnoreListModel::indexOf(const QString &rule)
+const QModelIndex IgnoreListModel::indexOf(const QString& rule)
{
return createIndex(ignoreListManager().indexOf(rule), 2);
}
Q_OBJECT
public:
- IgnoreListModel(QObject *parent = nullptr);
+ IgnoreListModel(QObject* parent = nullptr);
- QVariant data(const QModelIndex &index, int role) const override;
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
+ QVariant data(const QModelIndex& index, int role) const override;
+ bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override;
- Qt::ItemFlags flags(const QModelIndex &index) 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;
- inline int columnCount(const QModelIndex &parent = QModelIndex()) const override;
+ inline int rowCount(const QModelIndex& parent = QModelIndex()) const override;
+ inline int columnCount(const QModelIndex& parent = QModelIndex()) const override;
inline bool hasConfigChanged() const { return _configChanged; }
inline bool isReady() const { return _modelReady; }
- const IgnoreListManager::IgnoreListItem &ignoreListItemAt(int row) const;
- void setIgnoreListItemAt(int row, const IgnoreListManager::IgnoreListItem &item);
- bool newIgnoreRule(const IgnoreListManager::IgnoreListItem &item);
- const QModelIndex indexOf(const QString &rule);
+ const IgnoreListManager::IgnoreListItem& ignoreListItemAt(int row) const;
+ void setIgnoreListItemAt(int row, const IgnoreListManager::IgnoreListItem& item);
+ bool newIgnoreRule(const IgnoreListManager::IgnoreListItem& item);
+ const QModelIndex indexOf(const QString& rule);
public slots:
void loadDefaults();
bool _configChanged{false};
bool _modelReady{false};
- const IgnoreListManager &ignoreListManager() const;
- IgnoreListManager &ignoreListManager();
- IgnoreListManager &cloneIgnoreListManager();
+ const IgnoreListManager& ignoreListManager() const;
+ IgnoreListManager& ignoreListManager();
+ IgnoreListManager& cloneIgnoreListManager();
private slots:
void clientConnected();
void initDone();
};
-
// Inlines
-int IgnoreListModel::rowCount(const QModelIndex &parent) const
+int IgnoreListModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return isReady() ? ignoreListManager().count() : 0;
}
-
-int IgnoreListModel::columnCount(const QModelIndex &parent) const
+int IgnoreListModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return isReady() ? 3 : 0;
}
-
-#endif //IGNORELISTMODEL_H
+#endif // IGNORELISTMODEL_H
#include "ignorelistsettingspage.h"
+#include <QDebug>
+#include <QEvent>
#include <QHeaderView>
#include <QItemSelectionModel>
+#include <QMessageBox>
#include <QModelIndex>
#include <QPainter>
-#include <QMessageBox>
#include <QString>
-#include <QEvent>
-#include <QDebug>
#include "expressionmatch.h"
#include "icon.h"
#include "util.h"
-IgnoreListSettingsPage::IgnoreListSettingsPage(QWidget *parent)
+IgnoreListSettingsPage::IgnoreListSettingsPage(QWidget* parent)
: SettingsPage(tr("IRC"), tr("Ignore List"), parent)
{
ui.setupUi(this);
enableDialog(_ignoreListModel.isReady());
}
-
IgnoreListSettingsPage::~IgnoreListSettingsPage()
{
delete _delegate;
}
-
void IgnoreListSettingsPage::load()
{
if (_ignoreListModel.hasConfigChanged())
ui.editIgnoreRuleButton->setEnabled(false);
}
-
void IgnoreListSettingsPage::defaults()
{
_ignoreListModel.loadDefaults();
}
-
void IgnoreListSettingsPage::save()
{
if (_ignoreListModel.hasConfigChanged()) {
ui.editIgnoreRuleButton->setEnabled(false);
}
-
void IgnoreListSettingsPage::enableDialog(bool enabled)
{
ui.newIgnoreRuleButton->setEnabled(enabled);
setEnabled(enabled);
}
-
-void IgnoreListSettingsPage::selectionChanged(const QItemSelection &selection, const QItemSelection &)
+void IgnoreListSettingsPage::selectionChanged(const QItemSelection& selection, const QItemSelection&)
{
bool state = !selection.isEmpty();
ui.deleteIgnoreRuleButton->setEnabled(state);
ui.editIgnoreRuleButton->setEnabled(state);
}
-
void IgnoreListSettingsPage::deleteSelectedIgnoreRule()
{
if (!ui.ignoreListView->selectionModel()->hasSelection())
_ignoreListModel.removeIgnoreRule(ui.ignoreListView->selectionModel()->selectedIndexes()[0].row());
}
-
-void IgnoreListSettingsPage::newIgnoreRule(const QString &rule)
+void IgnoreListSettingsPage::newIgnoreRule(const QString& rule)
{
IgnoreListManager::IgnoreListItem newItem = IgnoreListManager::IgnoreListItem();
newItem.setStrictness(IgnoreListManager::SoftStrictness);
enableOkButton = true;
}
- auto *dlg = new IgnoreListEditDlg(newItem, this, enableOkButton);
+ auto* dlg = new IgnoreListEditDlg(newItem, this, enableOkButton);
dlg->enableOkButton(enableOkButton);
while (dlg->exec() == QDialog::Accepted) {
if (!_ignoreListModel.newIgnoreRule(dlg->ignoreListItem())) {
if (QMessageBox::warning(this,
- tr("Rule already exists"),
- tr("There is already a rule\n\"%1\"\nPlease choose another rule.")
- .arg(dlg->ignoreListItem().contents()),
- QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok)
+ tr("Rule already exists"),
+ tr("There is already a rule\n\"%1\"\nPlease choose another rule.").arg(dlg->ignoreListItem().contents()),
+ QMessageBox::Ok | QMessageBox::Cancel,
+ QMessageBox::Ok)
== QMessageBox::Cancel)
break;
dlg->deleteLater();
}
-
void IgnoreListSettingsPage::editSelectedIgnoreRule()
{
if (!ui.ignoreListView->selectionModel()->hasSelection())
}
}
-
-void IgnoreListSettingsPage::editIgnoreRule(const QString &ignoreRule)
+void IgnoreListSettingsPage::editIgnoreRule(const QString& ignoreRule)
{
ui.ignoreListView->selectionModel()->select(_ignoreListModel.indexOf(ignoreRule), QItemSelectionModel::Select);
- if (ui.ignoreListView->selectionModel()->hasSelection()) // && ui.ignoreListView->selectionModel()->selectedIndexes()[0].row() != -1)
+ if (ui.ignoreListView->selectionModel()->hasSelection()) // && ui.ignoreListView->selectionModel()->selectedIndexes()[0].row() != -1)
editSelectedIgnoreRule();
else
newIgnoreRule(ignoreRule);
}
-
/*
IgnoreListDelegate
*/
-void IgnoreListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
+void IgnoreListDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
if (index.column() == 0) {
- QStyle *style = QApplication::style();
+ QStyle* style = QApplication::style();
if (option.state & QStyle::State_Selected)
painter->fillRect(option.rect, option.palette.highlight());
QStyleOptionButton opts;
opts.direction = option.direction;
opts.rect = option.rect;
- opts.rect.moveLeft(option.rect.center().rx()-10);
+ opts.rect.moveLeft(option.rect.center().rx() - 10);
opts.state = option.state;
opts.state |= index.data().toBool() ? QStyle::State_On : QStyle::State_Off;
style->drawControl(QStyle::CE_CheckBox, &opts, painter);
QStyledItemDelegate::paint(painter, option, index);
}
-
// provide interactivity for the checkboxes
-bool IgnoreListDelegate::editorEvent(QEvent *event, QAbstractItemModel *model,
- const QStyleOptionViewItem &option, const QModelIndex &index)
+bool IgnoreListDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index)
{
Q_UNUSED(option)
switch (event->type()) {
}
}
-
/*
IgnoreListEditDlg
*/
-IgnoreListEditDlg::IgnoreListEditDlg(const IgnoreListManager::IgnoreListItem &item, QWidget *parent, bool enabled)
- : QDialog(parent), _ignoreListItem(item), _hasChanged(enabled)
+IgnoreListEditDlg::IgnoreListEditDlg(const IgnoreListManager::IgnoreListItem& item, QWidget* parent, bool enabled)
+ : QDialog(parent)
+ , _ignoreListItem(item)
+ , _hasChanged(enabled)
{
ui.setupUi(this);
setAttribute(Qt::WA_DeleteOnClose, false);
widgetHasChanged();
}
-
void IgnoreListEditDlg::widgetHasChanged()
{
if (ui.messageTypeButton->isChecked())
}
else {
// Trim the resulting MultiWildcard expression
- _clonedIgnoreListItem.setScopeRule(
- ExpressionMatch::trimMultiWildcardWhitespace(
- ui.scopeRuleTextEdit->toPlainText()));
+ _clonedIgnoreListItem.setScopeRule(ExpressionMatch::trimMultiWildcardWhitespace(ui.scopeRuleTextEdit->toPlainText()));
}
_clonedIgnoreListItem.setContents(ui.ignoreRuleLineEdit->text());
ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(_hasChanged);
}
-
void IgnoreListEditDlg::enableOkButton(bool state)
{
ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(state);
#ifndef IGNORELISTSETTINGSPAGE_H
#define IGNORELISTSETTINGSPAGE_H
-#include <QStyledItemDelegate>
#include <QButtonGroup>
+#include <QStyledItemDelegate>
+#include "clientignorelistmanager.h"
+#include "ignorelistmodel.h"
#include "settingspage.h"
-#include "ui_ignorelistsettingspage.h"
+
#include "ui_ignorelisteditdlg.h"
-#include "ignorelistmodel.h"
-#include "clientignorelistmanager.h"
+#include "ui_ignorelistsettingspage.h"
class QEvent;
class QPainter;
Q_OBJECT
public:
- IgnoreListDelegate(QWidget *parent = nullptr) : QStyledItemDelegate(parent) {}
- void paint(QPainter *painter, const QStyleOptionViewItem &option,
- const QModelIndex &index) const override;
- bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option,
- const QModelIndex &index) override;
+ IgnoreListDelegate(QWidget* parent = nullptr)
+ : QStyledItemDelegate(parent)
+ {}
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override;
+ bool editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index) override;
};
-
class IgnoreListEditDlg : public QDialog
{
Q_OBJECT
public:
- IgnoreListEditDlg(const IgnoreListManager::IgnoreListItem &item, QWidget *parent = nullptr, bool enabled = false);
+ IgnoreListEditDlg(const IgnoreListManager::IgnoreListItem& item, QWidget* parent = nullptr, bool enabled = false);
inline IgnoreListManager::IgnoreListItem ignoreListItem() { return _ignoreListItem; }
void enableOkButton(bool state);
QButtonGroup _scopeButtonGroup;
};
-
class IgnoreListSettingsPage : public SettingsPage
{
Q_OBJECT
public:
- IgnoreListSettingsPage(QWidget *parent = nullptr);
+ IgnoreListSettingsPage(QWidget* parent = nullptr);
~IgnoreListSettingsPage() override;
inline bool hasDefaults() const override { return false; }
inline bool needsCoreConnection() const override { return true; }
- void editIgnoreRule(const QString &ignoreRule);
+ void editIgnoreRule(const QString& ignoreRule);
public slots:
void save() override;
void load() override;
void defaults() override;
- void newIgnoreRule(const QString &rule = {});
+ void newIgnoreRule(const QString& rule = {});
private slots:
void enableDialog(bool);
void deleteSelectedIgnoreRule();
void editSelectedIgnoreRule();
- void selectionChanged(const QItemSelection &selection, const QItemSelection &);
+ void selectionChanged(const QItemSelection& selection, const QItemSelection&);
private:
- IgnoreListDelegate *_delegate;
+ IgnoreListDelegate* _delegate;
Ui::IgnoreListSettingsPage ui;
IgnoreListModel _ignoreListModel;
};
-
-#endif //IGNORELISTSETTINGSPAGE_H
+#endif // IGNORELISTSETTINGSPAGE_H
#include "inputwidgetsettingspage.h"
-InputWidgetSettingsPage::InputWidgetSettingsPage(QWidget *parent)
+InputWidgetSettingsPage::InputWidgetSettingsPage(QWidget* parent)
: SettingsPage(tr("Interface"), tr("Input Widget"), parent)
{
ui.setupUi(this);
#define INPUTLINESETTINGSPAGE_H_
#include "settingspage.h"
+
#include "ui_inputwidgetsettingspage.h"
class InputWidgetSettingsPage : public SettingsPage
Q_OBJECT
public:
- InputWidgetSettingsPage(QWidget *parent = nullptr);
+ InputWidgetSettingsPage(QWidget* parent = nullptr);
inline bool hasDefaults() const override { return true; }
inline QString settingsKey() const override { return QString("InputWidget"); }
};
-
#endif
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "itemviewsettingspage.h"
+
#include <QSignalMapper>
-#include "itemviewsettingspage.h"
#include "colorbutton.h"
#include "qtui.h"
#include "qtuistyle.h"
-ItemViewSettingsPage::ItemViewSettingsPage(QWidget *parent)
- : SettingsPage(tr("Interface"), tr("Chat & Nick Lists"), parent),
- _mapper(new QSignalMapper(this))
+ItemViewSettingsPage::ItemViewSettingsPage(QWidget* parent)
+ : SettingsPage(tr("Interface"), tr("Chat & Nick Lists"), parent)
+ , _mapper(new QSignalMapper(this))
{
ui.setupUi(this);
ui.bufferViewPreview->expandAll();
- foreach(ColorButton *button, findChildren<ColorButton *>()) {
+ foreach (ColorButton* button, findChildren<ColorButton*>()) {
connect(button, &ColorButton::colorChanged, _mapper, selectOverload<>(&QSignalMapper::map));
_mapper->setMapping(button, button);
}
initAutoWidgets();
}
-
void ItemViewSettingsPage::save()
{
SettingsPage::save();
QtUi::style()->reload();
}
-
-void ItemViewSettingsPage::updateBufferViewPreview(QWidget *widget)
+void ItemViewSettingsPage::updateBufferViewPreview(QWidget* widget)
{
- auto *button = qobject_cast<ColorButton *>(widget);
+ auto* button = qobject_cast<ColorButton*>(widget);
if (!button)
return;
#define ITEMVIEWSETTINGSPAGE_H_
#include "settingspage.h"
+
#include "ui_itemviewsettingspage.h"
class ColorButton;
Q_OBJECT
public:
- ItemViewSettingsPage(QWidget *parent = nullptr);
+ ItemViewSettingsPage(QWidget* parent = nullptr);
inline bool hasDefaults() const override { return true; }
void save() override;
private slots:
- void updateBufferViewPreview(QWidget *button);
+ void updateBufferViewPreview(QWidget* button);
private:
Ui::ItemViewSettingsPage ui;
- QSignalMapper *_mapper;
- QTreeWidgetItem *_networkItem, *_defaultBufferItem, *_inactiveBufferItem,
- *_activeBufferItem, *_unreadBufferItem, *_highlightedBufferItem;
+ QSignalMapper* _mapper;
+ QTreeWidgetItem *_networkItem, *_defaultBufferItem, *_inactiveBufferItem, *_activeBufferItem, *_unreadBufferItem, *_highlightedBufferItem;
inline QString settingsKey() const override { return QString("ItemViews"); }
};
-
#endif
#include <QApplication>
#include <QDebug>
-#include <QKeyEvent>
#include <QHBoxLayout>
+#include <QKeyEvent>
#include <QMessageBox>
#include <QToolButton>
// This defines the unicode symbols for special keys (kCommandUnicode and friends)
#ifdef Q_OS_MAC
-# include <Carbon/Carbon.h>
+# include <Carbon/Carbon.h>
#endif
#include "action.h"
#include "icon.h"
#include "keysequencewidget.h"
-KeySequenceButton::KeySequenceButton(KeySequenceWidget *d_, QWidget *parent)
- : QPushButton(parent),
- d(d_)
-{
-}
-
+KeySequenceButton::KeySequenceButton(KeySequenceWidget* d_, QWidget* parent)
+ : QPushButton(parent)
+ , d(d_)
+{}
-bool KeySequenceButton::event(QEvent *e)
+bool KeySequenceButton::event(QEvent* e)
{
if (d->isRecording() && e->type() == QEvent::KeyPress) {
- keyPressEvent(static_cast<QKeyEvent *>(e));
+ keyPressEvent(static_cast<QKeyEvent*>(e));
return true;
}
return QPushButton::event(e);
}
-
-void KeySequenceButton::keyPressEvent(QKeyEvent *e)
+void KeySequenceButton::keyPressEvent(QKeyEvent* e)
{
int keyQt = e->key();
if (keyQt == -1) {
// Qt sometimes returns garbage keycodes, I observed -1, if it doesn't know a key.
// We cannot do anything useful with those (several keys have -1, indistinguishable)
// and QKeySequence.toString() will also yield a garbage string.
- QMessageBox::information(this,
- tr("The key you just pressed is not supported by Qt."),
- tr("Unsupported Key"));
+ QMessageBox::information(this, tr("The key you just pressed is not supported by Qt."), tr("Unsupported Key"));
return d->cancelRecording();
}
uint newModifiers = e->modifiers() & (Qt::SHIFT | Qt::CTRL | Qt::ALT | Qt::META);
- //don't have the return or space key appear as first key of the sequence when they
- //were pressed to start editing - catch and them and imitate their effect
+ // don't have the return or space key appear as first key of the sequence when they
+ // were pressed to start editing - catch and them and imitate their effect
if (!d->isRecording() && ((keyQt == Qt::Key_Return || keyQt == Qt::Key_Space))) {
d->startRecording();
d->_modifierKeys = newModifiers;
d->_modifierKeys = newModifiers;
switch (keyQt) {
- case Qt::Key_AltGr: //or else we get unicode salad
+ case Qt::Key_AltGr: // or else we get unicode salad
return;
case Qt::Key_Shift:
case Qt::Key_Control:
case Qt::Key_Alt:
case Qt::Key_Meta:
- case Qt::Key_Menu: //unused (yes, but why?)
+ case Qt::Key_Menu: // unused (yes, but why?)
d->updateShortcutDisplay();
break;
}
}
-
-void KeySequenceButton::keyReleaseEvent(QKeyEvent *e)
+void KeySequenceButton::keyReleaseEvent(QKeyEvent* e)
{
if (e->key() == -1) {
// ignore garbage, see keyPressEvent()
}
}
-
/******************************************************************************/
-KeySequenceWidget::KeySequenceWidget(QWidget *parent)
+KeySequenceWidget::KeySequenceWidget(QWidget* parent)
: QWidget(parent)
{
- auto *layout = new QHBoxLayout(this);
+ auto* layout = new QHBoxLayout(this);
layout->setMargin(0);
_keyButton = new KeySequenceButton(this, this);
_keyButton->setFocusPolicy(Qt::StrongFocus);
_keyButton->setIcon(icon::get("configure"));
- _keyButton->setToolTip(tr("Click on the button, then enter the shortcut like you would in the program.\nExample for Ctrl+a: hold the Ctrl key and press a."));
+ _keyButton->setToolTip(tr(
+ "Click on the button, then enter the shortcut like you would in the program.\nExample for Ctrl+a: hold the Ctrl key and press a."));
layout->addWidget(_keyButton);
_clearButton = new QToolButton(this);
connect(_clearButton, &QAbstractButton::clicked, this, &KeySequenceWidget::clicked);
}
-
-void KeySequenceWidget::setModel(ShortcutsModel *model)
+void KeySequenceWidget::setModel(ShortcutsModel* model)
{
Q_ASSERT(!_shortcutsModel);
_shortcutsModel = model;
}
-
bool KeySequenceWidget::isOkWhenModifierless(int keyQt) const
{
- //this whole function is a hack, but especially the first line of code
+ // this whole function is a hack, but especially the first line of code
if (QKeySequence(keyQt).toString().length() == 1)
return false;
case Qt::Key_Return:
case Qt::Key_Space:
case Qt::Key_Tab:
- case Qt::Key_Backtab: //does this ever happen?
+ case Qt::Key_Backtab: // does this ever happen?
case Qt::Key_Backspace:
case Qt::Key_Delete:
return false;
}
}
-
bool KeySequenceWidget::isShiftAsModifierAllowed(int keyQt) const
{
// Shift only works as a modifier with certain keys. It's not possible
}
}
-
void KeySequenceWidget::updateShortcutDisplay()
{
QString s = _keySequence.toString(QKeySequence::NativeText);
if (_isRecording) {
if (_modifierKeys) {
#ifdef Q_OS_MAC
- if (_modifierKeys & Qt::META) s += QChar(kControlUnicode);
- if (_modifierKeys & Qt::ALT) s += QChar(kOptionUnicode);
- if (_modifierKeys & Qt::SHIFT) s += QChar(kShiftUnicode);
- if (_modifierKeys & Qt::CTRL) s += QChar(kCommandUnicode);
+ if (_modifierKeys & Qt::META)
+ s += QChar(kControlUnicode);
+ if (_modifierKeys & Qt::ALT)
+ s += QChar(kOptionUnicode);
+ if (_modifierKeys & Qt::SHIFT)
+ s += QChar(kShiftUnicode);
+ if (_modifierKeys & Qt::CTRL)
+ s += QChar(kCommandUnicode);
#else
- if (_modifierKeys & Qt::META) s += tr("Meta", "Meta key") + '+';
- if (_modifierKeys & Qt::CTRL) s += tr("Ctrl", "Ctrl key") + '+';
- if (_modifierKeys & Qt::ALT) s += tr("Alt", "Alt key") + '+';
- if (_modifierKeys & Qt::SHIFT) s += tr("Shift", "Shift key") + '+';
+ if (_modifierKeys & Qt::META)
+ s += tr("Meta", "Meta key") + '+';
+ if (_modifierKeys & Qt::CTRL)
+ s += tr("Ctrl", "Ctrl key") + '+';
+ if (_modifierKeys & Qt::ALT)
+ s += tr("Alt", "Alt key") + '+';
+ if (_modifierKeys & Qt::SHIFT)
+ s += tr("Shift", "Shift key") + '+';
#endif
}
else {
_keyButton->setText(s);
}
-
void KeySequenceWidget::startRecording()
{
_modifierKeys = 0;
updateShortcutDisplay();
}
-
void KeySequenceWidget::doneRecording()
{
bool wasRecording = _isRecording;
updateShortcutDisplay();
}
-
void KeySequenceWidget::cancelRecording()
{
_keySequence = _oldKeySequence;
doneRecording();
}
-
-void KeySequenceWidget::setKeySequence(const QKeySequence &seq)
+void KeySequenceWidget::setKeySequence(const QKeySequence& seq)
{
// oldKeySequence holds the key sequence before recording started, if setKeySequence()
// is called while not recording then set oldKeySequence to the existing sequence so
doneRecording();
}
-
void KeySequenceWidget::clear()
{
setKeySequence(QKeySequence());
emit keySequenceChanged(QKeySequence());
}
-
-bool KeySequenceWidget::isKeySequenceAvailable(const QKeySequence &seq)
+bool KeySequenceWidget::isKeySequenceAvailable(const QKeySequence& seq)
{
if (seq.isEmpty())
return true;
continue;
if (!actIdx.data(ShortcutsModel::IsConfigurableRole).toBool()) {
- QMessageBox::warning(this, tr("Shortcut Conflict"),
- tr("The \"%1\" shortcut is already in use, and cannot be configured.\nPlease choose another one.").arg(seq.toString(QKeySequence::NativeText)),
- QMessageBox::Ok);
+ QMessageBox::warning(this,
+ tr("Shortcut Conflict"),
+ tr("The \"%1\" shortcut is already in use, and cannot be configured.\nPlease choose another one.")
+ .arg(seq.toString(QKeySequence::NativeText)),
+ QMessageBox::Ok);
return false;
}
- QMessageBox box(QMessageBox::Warning, tr("Shortcut Conflict"),
- (tr("The \"%1\" shortcut is ambiguous with the shortcut for the following action:")
- + "<br><ul><li>%2</li></ul><br>"
- + tr("Do you want to reassign this shortcut to the selected action?")
- ).arg(seq.toString(QKeySequence::NativeText), actIdx.data().toString()),
- QMessageBox::Cancel, this);
+ QMessageBox box(QMessageBox::Warning,
+ tr("Shortcut Conflict"),
+ (tr("The \"%1\" shortcut is ambiguous with the shortcut for the following action:")
+ + "<br><ul><li>%2</li></ul><br>" + tr("Do you want to reassign this shortcut to the selected action?"))
+ .arg(seq.toString(QKeySequence::NativeText), actIdx.data().toString()),
+ QMessageBox::Cancel,
+ this);
box.addButton(tr("Reassign"), QMessageBox::AcceptRole);
if (box.exec() == QMessageBox::Cancel)
return false;
{
Q_OBJECT
public:
- KeySequenceWidget(QWidget *parent = nullptr);
+ KeySequenceWidget(QWidget* parent = nullptr);
- void setModel(ShortcutsModel *model);
+ void setModel(ShortcutsModel* model);
public slots:
- void setKeySequence(const QKeySequence &seq);
+ void setKeySequence(const QKeySequence& seq);
signals:
/**
* \param conflicting The index of an action that needs to have its shortcut removed. The user has already been
* asked to agree (if he declines, this signal won't be emitted at all).
*/
- void keySequenceChanged(const QKeySequence &seq, const QModelIndex &conflicting = QModelIndex());
+ void keySequenceChanged(const QKeySequence& seq, const QModelIndex& conflicting = QModelIndex());
void clicked();
bool isOkWhenModifierless(int keyQt) const;
bool isShiftAsModifierAllowed(int keyQt) const;
- bool isKeySequenceAvailable(const QKeySequence &seq);
+ bool isKeySequenceAvailable(const QKeySequence& seq);
- ShortcutsModel *_shortcutsModel{nullptr};
+ ShortcutsModel* _shortcutsModel{nullptr};
bool _isRecording{false};
QKeySequence _keySequence, _oldKeySequence;
uint _modifierKeys{0};
QModelIndex _conflictingIndex;
- KeySequenceButton *_keyButton;
- QToolButton *_clearButton;
+ KeySequenceButton* _keyButton;
+ QToolButton* _clearButton;
friend class KeySequenceButton;
};
-
/*****************************************************************************/
class KeySequenceButton : public QPushButton
{
Q_OBJECT
public:
- explicit KeySequenceButton(KeySequenceWidget *d, QWidget *parent = nullptr);
+ explicit KeySequenceButton(KeySequenceWidget* d, QWidget* parent = nullptr);
protected:
- bool event(QEvent *event) override;
- void keyPressEvent(QKeyEvent *event) override;
- void keyReleaseEvent(QKeyEvent *event) override;
+ bool event(QEvent* event) override;
+ void keyPressEvent(QKeyEvent* event) override;
+ void keyReleaseEvent(QKeyEvent* event) override;
private:
- KeySequenceWidget *d;
+ KeySequenceWidget* d;
};
-
-#endif // KEYSEQUENCEWIDGET_H
+#endif // KEYSEQUENCEWIDGET_H
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "networkssettingspage.h"
+
+#include <utility>
+
#include <QHeaderView>
#include <QMessageBox>
#include <QTextCodec>
-#include <utility>
-
-#include "networkssettingspage.h"
#include "client.h"
#include "icon.h"
#include "settingspages/identitiessettingspage.h"
-NetworksSettingsPage::NetworksSettingsPage(QWidget *parent)
+NetworksSettingsPage::NetworksSettingsPage(QWidget* parent)
: SettingsPage(tr("IRC"), tr("Networks"), parent)
{
ui.setupUi(this);
ui.editIdentities->setIcon(icon::get("configure"));
connectedIcon = icon::get("network-connect");
- connectingIcon = icon::get("network-wired"); // FIXME network-connecting
+ connectingIcon = icon::get("network-wired"); // FIXME network-connecting
disconnectedIcon = icon::get("network-disconnect");
// Status icons
infoIcon = icon::get("dialog-information");
warningIcon = icon::get("dialog-warning");
- foreach(int mib, QTextCodec::availableMibs()) {
+ foreach (int mib, QTextCodec::availableMibs()) {
QByteArray codec = QTextCodec::codecForMib(mib)->name();
ui.sendEncoding->addItem(codec);
ui.recvEncoding->addItem(codec);
ui.recvEncoding->model()->sort(0);
ui.serverEncoding->model()->sort(0);
currentId = 0;
- setEnabled(Client::isConnected()); // need a core connection!
+ setEnabled(Client::isConnected()); // need a core connection!
setWidgetStates();
- connectToWidgetsChangedSignals({
- ui.identityList,
- ui.performEdit,
- ui.sasl,
- ui.saslAccount,
- ui.saslPassword,
- ui.autoIdentify,
- ui.autoIdentifyService,
- ui.autoIdentifyPassword,
- ui.useCustomEncodings,
- ui.sendEncoding,
- ui.recvEncoding,
- ui.serverEncoding,
- ui.autoReconnect,
- ui.reconnectInterval,
- ui.reconnectRetries,
- ui.unlimitedRetries,
- ui.rejoinOnReconnect,
- ui.useCustomMessageRate,
- ui.messageRateBurstSize,
- ui.messageRateDelay,
- ui.unlimitedMessageRate
- }, this, &NetworksSettingsPage::widgetHasChanged);
+ connectToWidgetsChangedSignals({ui.identityList, ui.performEdit, ui.sasl,
+ ui.saslAccount, ui.saslPassword, ui.autoIdentify,
+ ui.autoIdentifyService, ui.autoIdentifyPassword, ui.useCustomEncodings,
+ ui.sendEncoding, ui.recvEncoding, ui.serverEncoding,
+ ui.autoReconnect, ui.reconnectInterval, ui.reconnectRetries,
+ ui.unlimitedRetries, ui.rejoinOnReconnect, ui.useCustomMessageRate,
+ ui.messageRateBurstSize, ui.messageRateDelay, ui.unlimitedMessageRate},
+ this,
+ &NetworksSettingsPage::widgetHasChanged);
connect(Client::instance(), &Client::coreConnectionStateChanged, this, &NetworksSettingsPage::coreConnectionStateChanged);
connect(Client::instance(), &Client::networkCreated, this, &NetworksSettingsPage::clientNetworkAdded);
connect(Client::instance(), &Client::identityCreated, this, &NetworksSettingsPage::clientIdentityAdded);
connect(Client::instance(), &Client::identityRemoved, this, &NetworksSettingsPage::clientIdentityRemoved);
- foreach(IdentityId id, Client::identityIds()) {
+ foreach (IdentityId id, Client::identityIds()) {
clientIdentityAdded(id);
}
}
-
void NetworksSettingsPage::save()
{
setEnabled(false);
- if (currentId != 0) saveToNetworkInfo(networkInfos[currentId]);
+ if (currentId != 0)
+ saveToNetworkInfo(networkInfos[currentId]);
QList<NetworkInfo> toCreate, toUpdate;
QList<NetworkId> toRemove;
NetworkId id = (*i).networkId;
if (id < 0) {
toCreate.append(*i);
- //if(id == currentId) currentId = 0;
- //QList<QListWidgetItem *> items = ui.networkList->findItems((*i).networkName, Qt::MatchExactly);
- //if(items.count()) {
+ // if(id == currentId) currentId = 0;
+ // QList<QListWidgetItem *> items = ui.networkList->findItems((*i).networkName, Qt::MatchExactly);
+ // if(items.count()) {
// Q_ASSERT(items[0]->data(Qt::UserRole).value<NetworkId>() == id);
// delete items[0];
//}
- //i = networkInfos.erase(i);
+ // i = networkInfos.erase(i);
++i;
}
else {
++i;
}
}
- foreach(NetworkId id, Client::networkIds()) {
- if (!networkInfos.contains(id)) toRemove.append(id);
+ foreach (NetworkId id, Client::networkIds()) {
+ if (!networkInfos.contains(id))
+ toRemove.append(id);
}
SaveNetworksDlg dlg(toCreate, toUpdate, toRemove, this);
int ret = dlg.exec();
setEnabled(true);
}
-
void NetworksSettingsPage::load()
{
reset();
// Custom rate limiting supported, allow toggling
ui.useCustomMessageRate->setEnabled(true);
// Reset tooltip to default.
- ui.useCustomMessageRate->setToolTip(QString("%1").arg(
- tr("<p>Override default message rate limiting.</p>"
- "<p><b>Setting limits too low may get you disconnected"
- " from the server!</b></p>")));
+ ui.useCustomMessageRate->setToolTip(QString("%1").arg(tr("<p>Override default message rate limiting.</p>"
+ "<p><b>Setting limits too low may get you disconnected"
+ " from the server!</b></p>")));
// If changed, update the message below!
- } else {
+ }
+ else {
// Custom rate limiting not supported, disallow toggling
ui.useCustomMessageRate->setEnabled(false);
// Split up the message to allow re-using translations:
// [Original tool-tip]
// [Bold 'does not support feature' message]
// [Specific version needed and feature details]
- ui.useCustomMessageRate->setToolTip(QString("%1<br/><b>%2</b><br/>%3").arg(
- tr("<p>Override default message rate limiting.</p>"
- "<p><b>Setting limits too low may get you disconnected"
- " from the server!</b></p>"),
- tr("Your Quassel core does not support this feature"),
- tr("You need a Quassel core v0.13.0 or newer in order to "
- "modify message rate limits.")));
+ ui.useCustomMessageRate->setToolTip(QString("%1<br/><b>%2</b><br/>%3")
+ .arg(tr("<p>Override default message rate limiting.</p>"
+ "<p><b>Setting limits too low may get you disconnected"
+ " from the server!</b></p>"),
+ tr("Your Quassel core does not support this feature"),
+ tr("You need a Quassel core v0.13.0 or newer in order to "
+ "modify message rate limits.")));
}
#ifdef HAVE_SSL
// Reset network capability status in case no valid networks get selected (a rare situation)
resetNetworkCapStates();
- foreach(NetworkId netid, Client::networkIds()) {
+ foreach (NetworkId netid, Client::networkIds()) {
clientNetworkAdded(netid);
}
ui.networkList->setCurrentRow(0);
setChangedState(false);
}
-
void NetworksSettingsPage::reset()
{
currentId = 0;
networkInfos.clear();
}
-
bool NetworksSettingsPage::aboutToSave()
{
- if (currentId != 0) saveToNetworkInfo(networkInfos[currentId]);
+ if (currentId != 0)
+ saveToNetworkInfo(networkInfos[currentId]);
QList<int> errors;
- foreach(NetworkInfo info, networkInfos.values()) {
- if (!info.serverList.count()) errors.append(1);
+ foreach (NetworkInfo info, networkInfos.values()) {
+ if (!info.serverList.count())
+ errors.append(1);
}
- if (!errors.count()) return true;
+ if (!errors.count())
+ return true;
QString error(tr("<b>The following problems need to be corrected before your changes can be applied:</b><ul>"));
- if (errors.contains(1)) error += tr("<li>All networks need at least one server defined</li>");
+ if (errors.contains(1))
+ error += tr("<li>All networks need at least one server defined</li>");
error += tr("</ul>");
QMessageBox::warning(this, tr("Invalid Network Settings"), error);
return false;
}
-
void NetworksSettingsPage::widgetHasChanged()
{
- if (_ignoreWidgetChanges) return;
+ if (_ignoreWidgetChanges)
+ return;
bool changed = testHasChanged();
- if (changed != hasChanged()) setChangedState(changed);
+ if (changed != hasChanged())
+ setChangedState(changed);
}
-
bool NetworksSettingsPage::testHasChanged()
{
if (currentId != 0) {
saveToNetworkInfo(networkInfos[currentId]);
}
- if (Client::networkIds().count() != networkInfos.count()) return true;
- foreach(NetworkId id, networkInfos.keys()) {
- if (id < 0) return true;
- if (Client::network(id)->networkInfo() != networkInfos[id]) return true;
+ if (Client::networkIds().count() != networkInfos.count())
+ return true;
+ foreach (NetworkId id, networkInfos.keys()) {
+ if (id < 0)
+ return true;
+ if (Client::network(id)->networkInfo() != networkInfos[id])
+ return true;
}
return false;
}
-
void NetworksSettingsPage::setWidgetStates()
{
// network list
else {
ui.renameNetwork->setEnabled(false);
ui.deleteNetwork->setEnabled(false);
- //ui.connectNow->setEnabled(false);
+ // ui.connectNow->setEnabled(false);
ui.detailsBox->setEnabled(false);
}
// network details
}
}
-
-void NetworksSettingsPage::setItemState(NetworkId id, QListWidgetItem *item)
+void NetworksSettingsPage::setItemState(NetworkId id, QListWidgetItem* item)
{
- if (!item && !(item = networkItem(id))) return;
- const Network *net = Client::network(id);
- if (!net || net->isInitialized()) item->setFlags(item->flags() | Qt::ItemIsEnabled);
- else item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
+ if (!item && !(item = networkItem(id)))
+ return;
+ const Network* net = Client::network(id);
+ if (!net || net->isInitialized())
+ item->setFlags(item->flags() | Qt::ItemIsEnabled);
+ else
+ item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
if (net && net->connectionState() == Network::Initialized) {
item->setIcon(connectedIcon);
}
if (net) {
bool select = false;
// check if we already have another net of this name in the list, and replace it
- QList<QListWidgetItem *> items = ui.networkList->findItems(net->networkName(), Qt::MatchExactly);
+ QList<QListWidgetItem*> items = ui.networkList->findItems(net->networkName(), Qt::MatchExactly);
if (items.count()) {
- foreach(QListWidgetItem *i, items) {
+ foreach (QListWidgetItem* i, items) {
NetworkId oldid = i->data(Qt::UserRole).value<NetworkId>();
- if (oldid > 0) continue; // only locally created nets should be replaced
+ if (oldid > 0)
+ continue; // only locally created nets should be replaced
if (oldid == currentId) {
select = true;
currentId = 0;
}
int row = ui.networkList->row(i);
if (row >= 0) {
- QListWidgetItem *olditem = ui.networkList->takeItem(row);
+ QListWidgetItem* olditem = ui.networkList->takeItem(row);
Q_ASSERT(olditem);
delete olditem;
}
}
}
item->setText(net->networkName());
- if (select) item->setSelected(true);
+ if (select)
+ item->setSelected(true);
}
}
-
void NetworksSettingsPage::resetNetworkCapStates()
{
// Set the status to a blank (invalid) network ID, reseting all UI
setNetworkCapStates(NetworkId());
}
-
void NetworksSettingsPage::setNetworkCapStates(NetworkId id)
{
- const Network *net = Client::network(id);
+ const Network* net = Client::network(id);
if (net && Client::isCoreFeatureEnabled(Quassel::Feature::CapNegotiation)) {
// Capability negotiation is supported, network exists.
// Check if the network is connected. Don't use net->isConnected() as that won't be true
// [SASL]
if (net->saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
setSASLStatus(CapSupportStatus::MaybeSupported);
- } else {
+ }
+ else {
setSASLStatus(CapSupportStatus::MaybeUnsupported);
}
// Add additional capability-dependent interface updates here
- } else {
+ }
+ else {
// Network is disconnected
// [SASL]
setSASLStatus(CapSupportStatus::Disconnected);
// Add additional capability-dependent interface updates here
}
- } else {
+ }
+ else {
// Capability negotiation is not supported and/or network doesn't exist.
// Don't assume anything and reset all capability-dependent interface elements to neutral.
// [SASL]
}
}
-
void NetworksSettingsPage::coreConnectionStateChanged(bool state)
{
this->setEnabled(state);
}
else {
// reset
- //currentId = 0;
+ // currentId = 0;
}
}
-
void NetworksSettingsPage::clientIdentityAdded(IdentityId id)
{
- const Identity *identity = Client::identity(id);
+ const Identity* identity = Client::identity(id);
connect(identity, &SyncableObject::updatedRemotely, this, &NetworksSettingsPage::clientIdentityUpdated);
QString name = identity->identityName();
widgetHasChanged();
}
-
void NetworksSettingsPage::clientIdentityUpdated()
{
- const auto *identity = qobject_cast<const Identity *>(sender());
+ const auto* identity = qobject_cast<const Identity*>(sender());
if (!identity) {
qWarning() << "NetworksSettingsPage: Invalid identity to update!";
return;
}
}
-
void NetworksSettingsPage::clientIdentityRemoved(IdentityId id)
{
IdentityId defaultId = defaultIdentity();
- if (currentId != 0) saveToNetworkInfo(networkInfos[currentId]);
- foreach(NetworkInfo info, networkInfos.values()) {
+ if (currentId != 0)
+ saveToNetworkInfo(networkInfos[currentId]);
+ foreach (NetworkInfo info, networkInfos.values()) {
if (info.identity == id) {
if (info.networkId == currentId)
ui.identityList->setCurrentIndex(0);
info.identity = defaultId;
networkInfos[info.networkId] = info;
- if (info.networkId > 0) Client::updateNetwork(info);
+ if (info.networkId > 0)
+ Client::updateNetwork(info);
}
}
ui.identityList->removeItem(ui.identityList->findData(id.toInt()));
widgetHasChanged();
}
-
-QListWidgetItem *NetworksSettingsPage::networkItem(NetworkId id) const
+QListWidgetItem* NetworksSettingsPage::networkItem(NetworkId id) const
{
for (int i = 0; i < ui.networkList->count(); i++) {
- QListWidgetItem *item = ui.networkList->item(i);
- if (item->data(Qt::UserRole).value<NetworkId>() == id) return item;
+ QListWidgetItem* item = ui.networkList->item(i);
+ if (item->data(Qt::UserRole).value<NetworkId>() == id)
+ return item;
}
return nullptr;
}
-
void NetworksSettingsPage::clientNetworkAdded(NetworkId id)
{
insertNetwork(id);
- //connect(Client::network(id), &Network::updatedRemotely, this, &NetworksSettingsPage::clientNetworkUpdated);
+ // connect(Client::network(id), &Network::updatedRemotely, this, &NetworksSettingsPage::clientNetworkUpdated);
connect(Client::network(id), &Network::configChanged, this, &NetworksSettingsPage::clientNetworkUpdated);
connect(Client::network(id), &Network::connectionStateSet, this, &NetworksSettingsPage::networkConnectionStateChanged);
connect(Client::network(id), &Network::capRemoved, this, &NetworksSettingsPage::clientNetworkCapsUpdated);
}
-
void NetworksSettingsPage::clientNetworkUpdated()
{
- const auto *net = qobject_cast<const Network *>(sender());
+ const auto* net = qobject_cast<const Network*>(sender());
if (!net) {
qWarning() << "Update request for unknown network received!";
return;
}
networkInfos[net->networkId()] = net->networkInfo();
setItemState(net->networkId());
- if (net->networkId() == currentId) displayNetwork(net->networkId());
+ if (net->networkId() == currentId)
+ displayNetwork(net->networkId());
setWidgetStates();
widgetHasChanged();
}
-
void NetworksSettingsPage::clientNetworkRemoved(NetworkId id)
{
- if (!networkInfos.contains(id)) return;
- if (id == currentId) displayNetwork(0);
+ if (!networkInfos.contains(id))
+ return;
+ if (id == currentId)
+ displayNetwork(0);
NetworkInfo info = networkInfos.take(id);
- QList<QListWidgetItem *> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
- foreach(QListWidgetItem *item, items) {
+ QList<QListWidgetItem*> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
+ foreach (QListWidgetItem* item, items) {
if (item->data(Qt::UserRole).value<NetworkId>() == id)
delete ui.networkList->takeItem(ui.networkList->row(item));
}
widgetHasChanged();
}
-
void NetworksSettingsPage::networkConnectionStateChanged(Network::ConnectionState state)
{
Q_UNUSED(state);
- const auto *net = qobject_cast<const Network *>(sender());
- if (!net) return;
+ const auto* net = qobject_cast<const Network*>(sender());
+ if (!net)
+ return;
/*
if(net->networkId() == currentId) {
ui.connectNow->setEnabled(state == Network::Initialized || state == Network::Disconnected);
setWidgetStates();
}
+void NetworksSettingsPage::networkConnectionError(const QString&) {}
-void NetworksSettingsPage::networkConnectionError(const QString &)
-{
-}
-
-
-QListWidgetItem *NetworksSettingsPage::insertNetwork(NetworkId id)
+QListWidgetItem* NetworksSettingsPage::insertNetwork(NetworkId id)
{
NetworkInfo info = Client::network(id)->networkInfo();
networkInfos[id] = info;
return insertNetwork(info);
}
-
-QListWidgetItem *NetworksSettingsPage::insertNetwork(const NetworkInfo &info)
+QListWidgetItem* NetworksSettingsPage::insertNetwork(const NetworkInfo& info)
{
- QListWidgetItem *item = nullptr;
- QList<QListWidgetItem *> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
- if (!items.count()) item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
+ QListWidgetItem* item = nullptr;
+ QList<QListWidgetItem*> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
+ if (!items.count())
+ item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
else {
// we overwrite an existing net if it a) has the same name and b) has a negative ID meaning we created it locally before
// -> then we can be sure that this is the core-side replacement for the net we created
- foreach(QListWidgetItem *i, items) {
+ foreach (QListWidgetItem* i, items) {
NetworkId id = i->data(Qt::UserRole).value<NetworkId>();
- if (id < 0) { item = i; break; }
+ if (id < 0) {
+ item = i;
+ break;
+ }
}
- if (!item) item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
+ if (!item)
+ item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
}
item->setData(Qt::UserRole, QVariant::fromValue<NetworkId>(info.networkId));
setItemState(info.networkId, item);
return item;
}
-
// Called when selecting 'Configure' from the buffer list
void NetworksSettingsPage::bufferList_Open(NetworkId netId)
{
- QListWidgetItem *item = networkItem(netId);
+ QListWidgetItem* item = networkItem(netId);
ui.networkList->setCurrentItem(item, QItemSelectionModel::SelectCurrent);
}
-
void NetworksSettingsPage::displayNetwork(NetworkId id)
{
_ignoreWidgetChanges = true;
ui.identityList->setCurrentIndex(ui.identityList->findData(info.identity.toInt()));
ui.serverList->clear();
- foreach(Network::Server server, info.serverList) {
- QListWidgetItem *item = new QListWidgetItem(QString("%1:%2").arg(server.host).arg(server.port));
+ foreach (Network::Server server, info.serverList) {
+ QListWidgetItem* item = new QListWidgetItem(QString("%1:%2").arg(server.host).arg(server.port));
if (server.useSsl)
item->setIcon(icon::get("document-encrypt"));
ui.serverList->addItem(item);
}
- //setItemState(id);
- //ui.randomServer->setChecked(info.useRandomServer);
+ // setItemState(id);
+ // ui.randomServer->setChecked(info.useRandomServer);
// Update the capability-dependent UI in case capabilities have changed.
setNetworkCapStates(id);
ui.performEdit->setPlainText(info.perform.join("\n"));
currentId = id;
}
-
-void NetworksSettingsPage::saveToNetworkInfo(NetworkInfo &info)
+void NetworksSettingsPage::saveToNetworkInfo(NetworkInfo& info)
{
info.identity = ui.identityList->itemData(ui.identityList->currentIndex()).toInt();
- //info.useRandomServer = ui.randomServer->isChecked();
+ // info.useRandomServer = ui.randomServer->isChecked();
info.perform = ui.performEdit->toPlainText().split("\n");
info.useAutoIdentify = ui.autoIdentify->isChecked();
info.autoIdentifyService = ui.autoIdentifyService->text();
info.unlimitedMessageRate = ui.unlimitedMessageRate->isChecked();
}
-
void NetworksSettingsPage::clientNetworkCapsUpdated()
{
// Grab the updated network
- const auto *net = qobject_cast<const Network *>(sender());
+ const auto* net = qobject_cast<const Network*>(sender());
if (!net) {
qWarning() << "Update request for unknown network received!";
return;
}
}
-
void NetworksSettingsPage::setSASLStatus(const CapSupportStatus saslStatus)
{
if (_saslStatusSelected != saslStatus) {
// Update the user interface
switch (saslStatus) {
- case CapSupportStatus::Unknown:
- // There's no capability negotiation or network doesn't exist. Don't assume
- // anything.
- ui.saslStatusLabel->setText(QString("<i>%1</i>").arg(
- tr("Could not check if supported by network")));
- ui.saslStatusIcon->setPixmap(infoIcon.pixmap(16));
- break;
- case CapSupportStatus::Disconnected:
- // Disconnected from network, no way to check.
- ui.saslStatusLabel->setText(QString("<i>%1</i>").arg(
- tr("Cannot check if supported when disconnected")));
- ui.saslStatusIcon->setPixmap(infoIcon.pixmap(16));
- break;
- case CapSupportStatus::MaybeUnsupported:
- // The network doesn't advertise support for SASL PLAIN. Here be dragons.
- ui.saslStatusLabel->setText(QString("<i>%1</i>").arg(
- tr("Not currently supported by network")));
- ui.saslStatusIcon->setPixmap(warningIcon.pixmap(16));
- break;
- case CapSupportStatus::MaybeSupported:
- // The network advertises support for SASL PLAIN. Encourage using it!
- // Unfortunately we don't know for sure if it's desired or functional.
- ui.saslStatusLabel->setText(QString("<i>%1</i>").arg(tr("Supported by network")));
- ui.saslStatusIcon->setPixmap(infoIcon.pixmap(16));
- break;
+ case CapSupportStatus::Unknown:
+ // There's no capability negotiation or network doesn't exist. Don't assume
+ // anything.
+ ui.saslStatusLabel->setText(QString("<i>%1</i>").arg(tr("Could not check if supported by network")));
+ ui.saslStatusIcon->setPixmap(infoIcon.pixmap(16));
+ break;
+ case CapSupportStatus::Disconnected:
+ // Disconnected from network, no way to check.
+ ui.saslStatusLabel->setText(QString("<i>%1</i>").arg(tr("Cannot check if supported when disconnected")));
+ ui.saslStatusIcon->setPixmap(infoIcon.pixmap(16));
+ break;
+ case CapSupportStatus::MaybeUnsupported:
+ // The network doesn't advertise support for SASL PLAIN. Here be dragons.
+ ui.saslStatusLabel->setText(QString("<i>%1</i>").arg(tr("Not currently supported by network")));
+ ui.saslStatusIcon->setPixmap(warningIcon.pixmap(16));
+ break;
+ case CapSupportStatus::MaybeSupported:
+ // The network advertises support for SASL PLAIN. Encourage using it!
+ // Unfortunately we don't know for sure if it's desired or functional.
+ ui.saslStatusLabel->setText(QString("<i>%1</i>").arg(tr("Supported by network")));
+ ui.saslStatusIcon->setPixmap(infoIcon.pixmap(16));
+ break;
}
}
}
-
#ifdef HAVE_SSL
void NetworksSettingsPage::sslUpdated()
{
if (_cid && !_cid->sslKey().isNull()) {
ui.saslContents->setDisabled(true);
ui.saslExtInfo->setHidden(false);
- } else {
+ }
+ else {
ui.saslContents->setDisabled(false);
// Directly re-enabling causes the widgets to ignore the parent "Use SASL Authentication"
// state to indicate whether or not it's disabled. To workaround this, keep track of
}
#endif
-
/*** Network list ***/
void NetworksSettingsPage::on_networkList_itemSelectionChanged()
setWidgetStates();
}
-
void NetworksSettingsPage::on_addNetwork_clicked()
{
QStringList existing;
- for (int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
+ for (int i = 0; i < ui.networkList->count(); i++)
+ existing << ui.networkList->item(i)->text();
NetworkAddDlg dlg(existing, this);
if (dlg.exec() == QDialog::Accepted) {
NetworkInfo info = dlg.networkInfo();
NetworkId id;
for (id = 1; id <= networkInfos.count(); id++) {
widgetHasChanged();
- if (!networkInfos.keys().contains(-id.toInt())) break;
+ if (!networkInfos.keys().contains(-id.toInt()))
+ break;
}
id = -id.toInt();
info.networkId = id;
info.identity = defaultIdentity();
networkInfos[id] = info;
- QListWidgetItem *item = insertNetwork(info);
+ QListWidgetItem* item = insertNetwork(info);
ui.networkList->setCurrentItem(item);
setWidgetStates();
}
}
-
void NetworksSettingsPage::on_deleteNetwork_clicked()
{
if (ui.networkList->selectedItems().count()) {
NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
- int ret = QMessageBox::question(this, tr("Delete Network?"),
- tr("Do you really want to delete the network \"%1\" and all related settings, including the backlog?").arg(networkInfos[netid].networkName),
- QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
+ int ret
+ = QMessageBox::question(this,
+ tr("Delete Network?"),
+ tr("Do you really want to delete the network \"%1\" and all related settings, including the backlog?")
+ .arg(networkInfos[netid].networkName),
+ QMessageBox::Yes | QMessageBox::No,
+ QMessageBox::No);
if (ret == QMessageBox::Yes) {
currentId = 0;
networkInfos.remove(netid);
delete ui.networkList->takeItem(ui.networkList->row(ui.networkList->selectedItems()[0]));
- ui.networkList->setCurrentRow(qMin(ui.networkList->currentRow()+1, ui.networkList->count()-1));
+ ui.networkList->setCurrentRow(qMin(ui.networkList->currentRow() + 1, ui.networkList->count() - 1));
setWidgetStates();
widgetHasChanged();
}
}
}
-
void NetworksSettingsPage::on_renameNetwork_clicked()
{
- if (!ui.networkList->selectedItems().count()) return;
+ if (!ui.networkList->selectedItems().count())
+ return;
QString old = ui.networkList->selectedItems()[0]->text();
QStringList existing;
- for (int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
+ for (int i = 0; i < ui.networkList->count(); i++)
+ existing << ui.networkList->item(i)->text();
NetworkEditDlg dlg(old, existing, this);
if (dlg.exec() == QDialog::Accepted) {
ui.networkList->selectedItems()[0]->setText(dlg.networkName());
}
}
-
/*
void NetworksSettingsPage::on_connectNow_clicked() {
if(!ui.networkList->selectedItems().count()) return;
setWidgetStates();
}
-
void NetworksSettingsPage::on_addServer_clicked()
{
- if (currentId == 0) return;
+ if (currentId == 0)
+ return;
ServerEditDlg dlg(Network::Server(), this);
if (dlg.exec() == QDialog::Accepted) {
networkInfos[currentId].serverList.append(dlg.serverData());
displayNetwork(currentId);
- ui.serverList->setCurrentRow(ui.serverList->count()-1);
+ ui.serverList->setCurrentRow(ui.serverList->count() - 1);
widgetHasChanged();
}
}
-
void NetworksSettingsPage::on_editServer_clicked()
{
- if (currentId == 0) return;
+ if (currentId == 0)
+ return;
int cur = ui.serverList->currentRow();
ServerEditDlg dlg(networkInfos[currentId].serverList[cur], this);
if (dlg.exec() == QDialog::Accepted) {
}
}
-
void NetworksSettingsPage::on_deleteServer_clicked()
{
- if (currentId == 0) return;
+ if (currentId == 0)
+ return;
int cur = ui.serverList->currentRow();
networkInfos[currentId].serverList.removeAt(cur);
displayNetwork(currentId);
- ui.serverList->setCurrentRow(qMin(cur, ui.serverList->count()-1));
+ ui.serverList->setCurrentRow(qMin(cur, ui.serverList->count() - 1));
widgetHasChanged();
}
-
void NetworksSettingsPage::on_upServer_clicked()
{
int cur = ui.serverList->currentRow();
Network::Server server = networkInfos[currentId].serverList.takeAt(cur);
- networkInfos[currentId].serverList.insert(cur-1, server);
+ networkInfos[currentId].serverList.insert(cur - 1, server);
displayNetwork(currentId);
- ui.serverList->setCurrentRow(cur-1);
+ ui.serverList->setCurrentRow(cur - 1);
widgetHasChanged();
}
-
void NetworksSettingsPage::on_downServer_clicked()
{
int cur = ui.serverList->currentRow();
Network::Server server = networkInfos[currentId].serverList.takeAt(cur);
- networkInfos[currentId].serverList.insert(cur+1, server);
+ networkInfos[currentId].serverList.insert(cur + 1, server);
displayNetwork(currentId);
- ui.serverList->setCurrentRow(cur+1);
+ ui.serverList->setCurrentRow(cur + 1);
widgetHasChanged();
}
-
void NetworksSettingsPage::on_editIdentities_clicked()
{
SettingsPageDlg dlg(new IdentitiesSettingsPage(this), this);
dlg.exec();
}
-
void NetworksSettingsPage::on_saslStatusDetails_clicked()
{
if (ui.networkList->selectedItems().count()) {
NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
- QString &netName = networkInfos[netid].networkName;
+ QString& netName = networkInfos[netid].networkName;
// If these strings are visible, one of the status messages wasn't detected below.
QString saslStatusHeader = "[header unintentionally left blank]";
saslStatusHeader = tr("Could not check if SASL supported by network");
saslStatusExplanation = tr("Quassel could not check if \"%1\" supports SASL. This may "
"be due to unsaved changes or an older Quassel core. You "
- "can still try using SASL.").arg(netName);
+ "can still try using SASL.")
+ .arg(netName);
break;
case CapSupportStatus::Disconnected:
saslStatusHeader = tr("Cannot check if SASL supported when disconnected");
saslStatusExplanation = tr("Quassel cannot check if \"%1\" supports SASL when "
"disconnected. Connect to the network, or try using SASL "
- "anyways.").arg(netName);
+ "anyways.")
+ .arg(netName);
break;
case CapSupportStatus::MaybeUnsupported:
saslStatusHeader = tr("SASL not currently supported by network");
saslStatusExplanation = tr("The network \"%1\" does not currently support SASL. "
- "However, support might be added later on.").arg(netName);
+ "However, support might be added later on.")
+ .arg(netName);
useWarningIcon = true;
break;
case CapSupportStatus::MaybeSupported:
saslStatusHeader = tr("SASL supported by network");
saslStatusExplanation = tr("The network \"%1\" supports SASL. In most cases, you "
- "should use SASL instead of NickServ identification."
- ).arg(netName);
+ "should use SASL instead of NickServ identification.")
+ .arg(netName);
break;
}
// Process this in advance for reusability below
const QString saslStatusMsgTitle = tr("SASL support for \"%1\"").arg(netName);
- const QString saslStatusMsgText =
- QString("<p><b>%1</b></p></br><p>%2</p></br><p><i>%3</i></p>"
- ).arg(saslStatusHeader,
- saslStatusExplanation,
- tr("SASL is a standardized way to log in and identify yourself to "
- "IRC servers."));
+ const QString saslStatusMsgText = QString("<p><b>%1</b></p></br><p>%2</p></br><p><i>%3</i></p>")
+ .arg(saslStatusHeader,
+ saslStatusExplanation,
+ tr("SASL is a standardized way to log in and identify yourself to "
+ "IRC servers."));
if (useWarningIcon) {
// Show as a warning dialog box
QMessageBox::warning(this, saslStatusMsgTitle, saslStatusMsgText);
- } else {
+ }
+ else {
// Show as an information dialog box
QMessageBox::information(this, saslStatusMsgTitle, saslStatusMsgText);
}
}
}
-
IdentityId NetworksSettingsPage::defaultIdentity() const
{
IdentityId defaultId = 0;
QList<IdentityId> ids = Client::identityIds();
- foreach(IdentityId id, ids) {
+ foreach (IdentityId id, ids) {
if (defaultId == 0 || id < defaultId)
defaultId = id;
}
return defaultId;
}
-
/**************************************************************************
-* NetworkAddDlg
-*************************************************************************/
+ * NetworkAddDlg
+ *************************************************************************/
-NetworkAddDlg::NetworkAddDlg(QStringList exist, QWidget *parent) : QDialog(parent), existing(std::move(exist))
+NetworkAddDlg::NetworkAddDlg(QStringList exist, QWidget* parent)
+ : QDialog(parent)
+ , existing(std::move(exist))
{
ui.setupUi(this);
ui.useSSL->setIcon(icon::get("document-encrypt"));
// Synchronize requiring SSL with the use SSL checkbox
ui.sslVerify->setEnabled(ui.useSSL->isChecked());
connect(ui.useSSL, &QAbstractButton::toggled, ui.sslVerify, &QWidget::setEnabled);
- } else {
+ }
+ else {
// Core isn't new enough to allow requiring SSL; disable checkbox and uncheck
ui.sslVerify->setEnabled(false);
ui.sslVerify->setChecked(false);
// [Original tool-tip]
// [Bold 'does not support feature' message]
// [Specific version needed and feature details]
- ui.sslVerify->setToolTip(QString("%1<br/><b>%2</b><br/>%3").arg(
- ui.sslVerify->toolTip(),
- tr("Your Quassel core does not support this feature"),
- tr("You need a Quassel core v0.13.0 or newer in order to "
- "verify connection security.")));
+ ui.sslVerify->setToolTip(QString("%1<br/><b>%2</b><br/>%3")
+ .arg(ui.sslVerify->toolTip(),
+ tr("Your Quassel core does not support this feature"),
+ tr("You need a Quassel core v0.13.0 or newer in order to "
+ "verify connection security.")));
}
// read preset networks
QStringList networks = PresetNetworks::names();
- foreach(QString s, existing)
- networks.removeAll(s);
+ foreach (QString s, existing)
+ networks.removeAll(s);
if (networks.count())
ui.presetList->addItems(networks);
else {
setButtonStates();
}
-
NetworkInfo NetworkAddDlg::networkInfo() const
{
if (ui.useManual->isChecked()) {
NetworkInfo info;
info.networkName = ui.networkName->text().trimmed();
- info.serverList << Network::Server(ui.serverAddress->text().trimmed(), ui.port->value(),
- ui.serverPassword->text(), ui.useSSL->isChecked(),
+ info.serverList << Network::Server(ui.serverAddress->text().trimmed(),
+ ui.port->value(),
+ ui.serverPassword->text(),
+ ui.useSSL->isChecked(),
ui.sslVerify->isChecked());
return info;
}
return PresetNetworks::networkInfo(ui.presetList->currentText());
}
-
void NetworkAddDlg::setButtonStates()
{
bool ok = false;
ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok);
}
-
void NetworkAddDlg::updateSslPort(bool isChecked)
{
// "Use encrypted connection" was toggled, check the state...
if (isChecked && ui.port->value() == Network::PORT_PLAINTEXT) {
// Had been using the plain-text port, use the SSL default
ui.port->setValue(Network::PORT_SSL);
- } else if (!isChecked && ui.port->value() == Network::PORT_SSL) {
+ }
+ else if (!isChecked && ui.port->value() == Network::PORT_SSL) {
// Had been using the SSL port, use the plain-text default
ui.port->setValue(Network::PORT_PLAINTEXT);
}
}
-
/**************************************************************************
* NetworkEditDlg
*************************************************************************/
-NetworkEditDlg::NetworkEditDlg(const QString &old, QStringList exist, QWidget *parent) : QDialog(parent), existing(std::move(exist))
+NetworkEditDlg::NetworkEditDlg(const QString& old, QStringList exist, QWidget* parent)
+ : QDialog(parent)
+ , existing(std::move(exist))
{
ui.setupUi(this);
if (old.isEmpty()) {
// new network
setWindowTitle(tr("Add Network"));
- on_networkEdit_textChanged(""); // disable ok button
+ on_networkEdit_textChanged(""); // disable ok button
}
- else ui.networkEdit->setText(old);
+ else
+ ui.networkEdit->setText(old);
}
-
QString NetworkEditDlg::networkName() const
{
return ui.networkEdit->text().trimmed();
}
-
-void NetworkEditDlg::on_networkEdit_textChanged(const QString &text)
+void NetworkEditDlg::on_networkEdit_textChanged(const QString& text)
{
ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text.trimmed()));
}
-
/**************************************************************************
* ServerEditDlg
*************************************************************************/
-ServerEditDlg::ServerEditDlg(const Network::Server &server, QWidget *parent) : QDialog(parent)
+ServerEditDlg::ServerEditDlg(const Network::Server& server, QWidget* parent)
+ : QDialog(parent)
{
ui.setupUi(this);
ui.useSSL->setIcon(icon::get("document-encrypt"));
// Synchronize requiring SSL with the use SSL checkbox
ui.sslVerify->setEnabled(ui.useSSL->isChecked());
connect(ui.useSSL, &QAbstractButton::toggled, ui.sslVerify, &QWidget::setEnabled);
- } else {
+ }
+ else {
// Core isn't new enough to allow requiring SSL; disable checkbox and uncheck
ui.sslVerify->setEnabled(false);
ui.sslVerify->setChecked(false);
// [Original tool-tip]
// [Bold 'does not support feature' message]
// [Specific version needed and feature details]
- ui.sslVerify->setToolTip(QString("%1<br/><b>%2</b><br/>%3").arg(
- ui.sslVerify->toolTip(),
- tr("Your Quassel core does not support this feature"),
- tr("You need a Quassel core v0.13.0 or newer in order to "
- "verify connection security.")));
+ ui.sslVerify->setToolTip(QString("%1<br/><b>%2</b><br/>%3")
+ .arg(ui.sslVerify->toolTip(),
+ tr("Your Quassel core does not support this feature"),
+ tr("You need a Quassel core v0.13.0 or newer in order to "
+ "verify connection security.")));
}
on_host_textChanged();
}
-
Network::Server ServerEditDlg::serverData() const
{
- Network::Server server(ui.host->text().trimmed(), ui.port->value(), ui.password->text(),
- ui.useSSL->isChecked(), ui.sslVerify->isChecked());
+ Network::Server server(ui.host->text().trimmed(), ui.port->value(), ui.password->text(), ui.useSSL->isChecked(), ui.sslVerify->isChecked());
server.sslVersion = ui.sslVersion->currentIndex();
server.useProxy = ui.useProxy->isChecked();
server.proxyType = ui.proxyType->currentIndex() == 0 ? QNetworkProxy::Socks5Proxy : QNetworkProxy::HttpProxy;
return server;
}
-
void ServerEditDlg::on_host_textChanged()
{
ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(ui.host->text().trimmed().isEmpty());
}
-
void ServerEditDlg::updateSslPort(bool isChecked)
{
// "Use encrypted connection" was toggled, check the state...
if (isChecked && ui.port->value() == Network::PORT_PLAINTEXT) {
// Had been using the plain-text port, use the SSL default
ui.port->setValue(Network::PORT_SSL);
- } else if (!isChecked && ui.port->value() == Network::PORT_SSL) {
+ }
+ else if (!isChecked && ui.port->value() == Network::PORT_SSL) {
// Had been using the SSL port, use the plain-text default
ui.port->setValue(Network::PORT_PLAINTEXT);
}
}
-
/**************************************************************************
* SaveNetworksDlg
*************************************************************************/
-SaveNetworksDlg::SaveNetworksDlg(const QList<NetworkInfo> &toCreate, const QList<NetworkInfo> &toUpdate, const QList<NetworkId> &toRemove, QWidget *parent) : QDialog(parent)
+SaveNetworksDlg::SaveNetworksDlg(const QList<NetworkInfo>& toCreate,
+ const QList<NetworkInfo>& toUpdate,
+ const QList<NetworkId>& toRemove,
+ QWidget* parent)
+ : QDialog(parent)
{
ui.setupUi(this);
connect(Client::instance(), &Client::networkCreated, this, &SaveNetworksDlg::clientEvent);
connect(Client::instance(), &Client::networkRemoved, this, &SaveNetworksDlg::clientEvent);
- foreach(NetworkId id, toRemove) {
+ foreach (NetworkId id, toRemove) {
Client::removeNetwork(id);
}
- foreach(NetworkInfo info, toCreate) {
+ foreach (NetworkInfo info, toCreate) {
Client::createNetwork(info);
}
- foreach(NetworkInfo info, toUpdate) {
- const Network *net = Client::network(info.networkId);
+ foreach (NetworkInfo info, toUpdate) {
+ const Network* net = Client::network(info.networkId);
if (!net) {
qWarning() << "Invalid client network!";
numevents--;
}
}
-
void SaveNetworksDlg::clientEvent()
{
ui.progressBar->setValue(++rcvevents);
- if (rcvevents >= numevents) accept();
+ if (rcvevents >= numevents)
+ accept();
}
#include <QIcon>
+#include "clientidentity.h"
#include "network.h"
#include "settingspage.h"
-#include "clientidentity.h"
-#include "ui_networkssettingspage.h"
#include "ui_networkadddlg.h"
#include "ui_networkeditdlg.h"
-#include "ui_servereditdlg.h"
+#include "ui_networkssettingspage.h"
#include "ui_saveidentitiesdlg.h"
+#include "ui_servereditdlg.h"
class NetworksSettingsPage : public SettingsPage
{
Q_OBJECT
public:
- NetworksSettingsPage(QWidget *parent = nullptr);
+ NetworksSettingsPage(QWidget* parent = nullptr);
inline bool needsCoreConnection() const override { return true; }
void setWidgetStates();
void coreConnectionStateChanged(bool);
void networkConnectionStateChanged(Network::ConnectionState state);
- void networkConnectionError(const QString &msg);
+ void networkConnectionError(const QString& msg);
void displayNetwork(NetworkId);
- void setItemState(NetworkId, QListWidgetItem *item = nullptr);
+ void setItemState(NetworkId, QListWidgetItem* item = nullptr);
/**
* Reset the capability-dependent settings to the default unknown states
/**
* Status of capability support
*/
- enum CapSupportStatus {
+ enum CapSupportStatus
+ {
Unknown, ///< Old core, or otherwise unknown, can't make assumptions
Disconnected, ///< Disconnected from network, can't determine
MaybeUnsupported, ///< Server does not advertise support at this moment
QHash<NetworkId, NetworkInfo> networkInfos;
bool _ignoreWidgetChanges{false};
#ifdef HAVE_SSL
- CertIdentity *_cid{nullptr};
+ CertIdentity* _cid{nullptr};
#endif
QIcon connectedIcon, connectingIcon, disconnectedIcon;
void reset();
bool testHasChanged();
- QListWidgetItem *insertNetwork(NetworkId);
- QListWidgetItem *insertNetwork(const NetworkInfo &info);
- QListWidgetItem *networkItem(NetworkId) const;
- void saveToNetworkInfo(NetworkInfo &);
+ QListWidgetItem* insertNetwork(NetworkId);
+ QListWidgetItem* insertNetwork(const NetworkInfo& info);
+ QListWidgetItem* networkItem(NetworkId) const;
+ void saveToNetworkInfo(NetworkInfo&);
IdentityId defaultIdentity() const;
/**
void setSASLStatus(const CapSupportStatus saslStatus);
};
-
class NetworkAddDlg : public QDialog
{
Q_OBJECT
public:
- NetworkAddDlg(QStringList existing = QStringList(), QWidget *parent = nullptr);
+ NetworkAddDlg(QStringList existing = QStringList(), QWidget* parent = nullptr);
NetworkInfo networkInfo() const;
QStringList existing;
};
-
class NetworkEditDlg : public QDialog
{
Q_OBJECT
public:
- NetworkEditDlg(const QString &old, QStringList existing = QStringList(), QWidget *parent = nullptr);
+ NetworkEditDlg(const QString& old, QStringList existing = QStringList(), QWidget* parent = nullptr);
QString networkName() const;
private slots:
- void on_networkEdit_textChanged(const QString &);
+ void on_networkEdit_textChanged(const QString&);
private:
Ui::NetworkEditDlg ui;
QStringList existing;
};
-
class ServerEditDlg : public QDialog
{
Q_OBJECT
public:
- ServerEditDlg(const Network::Server &server = Network::Server(), QWidget *parent = nullptr);
+ ServerEditDlg(const Network::Server& server = Network::Server(), QWidget* parent = nullptr);
Network::Server serverData() const;
Ui::ServerEditDlg ui;
};
-
class SaveNetworksDlg : public QDialog
{
Q_OBJECT
public:
- SaveNetworksDlg(const QList<NetworkInfo> &toCreate, const QList<NetworkInfo> &toUpdate, const QList<NetworkId> &toRemove, QWidget *parent = nullptr);
+ SaveNetworksDlg(const QList<NetworkInfo>& toCreate,
+ const QList<NetworkInfo>& toUpdate,
+ const QList<NetworkId>& toRemove,
+ QWidget* parent = nullptr);
private slots:
void clientEvent();
int numevents, rcvevents;
};
-
#endif
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include <QVBoxLayout>
-
#include "notificationssettingspage.h"
+#include <QVBoxLayout>
+
#include "qtui.h"
-NotificationsSettingsPage::NotificationsSettingsPage(QWidget *parent)
+NotificationsSettingsPage::NotificationsSettingsPage(QWidget* parent)
: SettingsPage(tr("Interface"), tr("Notifications"), parent)
{
- auto *layout = new QVBoxLayout(this);
- foreach(AbstractNotificationBackend *backend, QtUi::notificationBackends()) {
- SettingsPage *cw = backend->createConfigWidget();
+ auto* layout = new QVBoxLayout(this);
+ foreach (AbstractNotificationBackend* backend, QtUi::notificationBackends()) {
+ SettingsPage* cw = backend->createConfigWidget();
if (cw) {
cw->setParent(this);
_configWidgets.append(cw);
load();
}
-
bool NotificationsSettingsPage::hasDefaults() const
{
return _hasDefaults;
}
-
void NotificationsSettingsPage::defaults()
{
- foreach(SettingsPage *cw, _configWidgets)
- cw->defaults();
+ foreach (SettingsPage* cw, _configWidgets)
+ cw->defaults();
widgetHasChanged();
}
-
void NotificationsSettingsPage::load()
{
- foreach(SettingsPage *cw, _configWidgets)
- cw->load();
+ foreach (SettingsPage* cw, _configWidgets)
+ cw->load();
setChangedState(false);
}
-
void NotificationsSettingsPage::save()
{
- foreach(SettingsPage *cw, _configWidgets)
- cw->save();
+ foreach (SettingsPage* cw, _configWidgets)
+ cw->save();
setChangedState(false);
}
-
void NotificationsSettingsPage::widgetHasChanged()
{
bool changed = false;
- foreach(SettingsPage *cw, _configWidgets) {
+ foreach (SettingsPage* cw, _configWidgets) {
if (cw->hasChanged()) {
changed = true;
break;
}
}
- if (changed != hasChanged()) setChangedState(changed);
+ if (changed != hasChanged())
+ setChangedState(changed);
}
Q_OBJECT
public:
- NotificationsSettingsPage(QWidget *parent = nullptr);
+ NotificationsSettingsPage(QWidget* parent = nullptr);
bool hasDefaults() const override;
void widgetHasChanged();
private:
- QList<SettingsPage *> _configWidgets;
+ QList<SettingsPage*> _configWidgets;
bool _hasDefaults{false};
};
Q_OBJECT
public:
- PreviewBufferView(QWidget *parent = nullptr) : BufferView(parent) {}
+ PreviewBufferView(QWidget* parent = nullptr)
+ : BufferView(parent)
+ {}
protected:
- void keyPressEvent(QKeyEvent *event) override { QTreeView::keyPressEvent(event); }
- void contextMenuEvent(QContextMenuEvent *) override {}
+ void keyPressEvent(QKeyEvent* event) override { QTreeView::keyPressEvent(event); }
+ void contextMenuEvent(QContextMenuEvent*) override {}
};
-
-#endif //PREVIEWBUFFERVIEW_H
+#endif // PREVIEWBUFFERVIEW_H
#include "actioncollection.h"
#include "util.h"
-ShortcutsModel::ShortcutsModel(const QHash<QString, ActionCollection *> &actionCollections, QObject *parent)
- : QAbstractItemModel(parent),
- _changedCount(0)
+ShortcutsModel::ShortcutsModel(const QHash<QString, ActionCollection*>& actionCollections, QObject* parent)
+ : QAbstractItemModel(parent)
+ , _changedCount(0)
{
for (int r = 0; r < actionCollections.values().count(); r++) {
- ActionCollection *coll = actionCollections.values().at(r);
- auto *item = new Item();
+ ActionCollection* coll = actionCollections.values().at(r);
+ auto* item = new Item();
item->row = r;
item->collection = coll;
for (int i = 0; i < coll->actions().count(); i++) {
- auto *action = qobject_cast<Action *>(coll->actions().at(i));
+ auto* action = qobject_cast<Action*>(coll->actions().at(i));
if (!action)
continue;
- auto *actionItem = new Item();
+ auto* actionItem = new Item();
actionItem->parentItem = item;
actionItem->row = i;
actionItem->collection = coll;
}
}
-
ShortcutsModel::~ShortcutsModel()
{
qDeleteAll(_categoryItems);
}
-
-QModelIndex ShortcutsModel::parent(const QModelIndex &child) const
+QModelIndex ShortcutsModel::parent(const QModelIndex& child) const
{
if (!child.isValid())
return {};
- auto *item = static_cast<Item *>(child.internalPointer());
+ auto* item = static_cast<Item*>(child.internalPointer());
Q_ASSERT(item);
if (!item->parentItem)
return createIndex(item->parentItem->row, 0, item->parentItem);
}
-
-QModelIndex ShortcutsModel::index(int row, int column, const QModelIndex &parent) const
+QModelIndex ShortcutsModel::index(int row, int column, const QModelIndex& parent) const
{
if (parent.isValid())
- return createIndex(row, column, static_cast<Item *>(parent.internalPointer())->actionItems.at(row));
+ return createIndex(row, column, static_cast<Item*>(parent.internalPointer())->actionItems.at(row));
// top level category item
return createIndex(row, column, _categoryItems.at(row));
}
-
-int ShortcutsModel::columnCount(const QModelIndex &parent) const
+int ShortcutsModel::columnCount(const QModelIndex& parent) const
{
return 2;
if (!parent.isValid())
return 2;
- auto *item = static_cast<Item *>(parent.internalPointer());
+ auto* item = static_cast<Item*>(parent.internalPointer());
Q_ASSERT(item);
if (!item->parentItem)
return 2;
}
-
-int ShortcutsModel::rowCount(const QModelIndex &parent) const
+int ShortcutsModel::rowCount(const QModelIndex& parent) const
{
if (!parent.isValid())
return _categoryItems.count();
- auto *item = static_cast<Item *>(parent.internalPointer());
+ auto* item = static_cast<Item*>(parent.internalPointer());
Q_ASSERT(item);
if (!item->parentItem)
return 0;
}
-
QVariant ShortcutsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation != Qt::Horizontal || role != Qt::DisplayRole)
}
}
-
-QVariant ShortcutsModel::data(const QModelIndex &index, int role) const
+QVariant ShortcutsModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
- auto *item = static_cast<Item *>(index.internalPointer());
+ auto* item = static_cast<Item*>(index.internalPointer());
Q_ASSERT(item);
if (!item->parentItem) {
}
}
- auto *action = qobject_cast<Action *>(item->action);
+ auto* action = qobject_cast<Action*>(item->action);
Q_ASSERT(action);
switch (role) {
return QVariant();
case ActionRole:
- return QVariant::fromValue<QObject *>(action);
+ return QVariant::fromValue<QObject*>(action);
case DefaultShortcutRole:
return action->shortcut(Action::DefaultShortcut);
}
}
-
-bool ShortcutsModel::setData(const QModelIndex &index, const QVariant &value, int role)
+bool ShortcutsModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (role != ActiveShortcutRole)
return false;
if (!index.parent().isValid())
return false;
- auto *item = static_cast<Item *>(index.internalPointer());
+ auto* item = static_cast<Item*>(index.internalPointer());
Q_ASSERT(item);
QKeySequence newSeq = value.value<QKeySequence>();
return true;
}
-
void ShortcutsModel::load()
{
- foreach(Item *catItem, _categoryItems) {
- foreach(Item *actItem, catItem->actionItems) {
+ foreach (Item* catItem, _categoryItems) {
+ foreach (Item* actItem, catItem->actionItems) {
actItem->shortcut = actItem->action->shortcut(Action::ActiveShortcut);
}
}
- emit dataChanged(index(0, 1), index(rowCount()-1, 1));
+ emit dataChanged(index(0, 1), index(rowCount() - 1, 1));
if (_changedCount != 0) {
_changedCount = 0;
emit changed(false);
}
}
-
void ShortcutsModel::commit()
{
- foreach(Item *catItem, _categoryItems) {
- foreach(Item *actItem, catItem->actionItems) {
+ foreach (Item* catItem, _categoryItems) {
+ foreach (Item* actItem, catItem->actionItems) {
actItem->action->setShortcut(actItem->shortcut, Action::ActiveShortcut);
}
}
}
}
-
void ShortcutsModel::defaults()
{
for (int cat = 0; cat < rowCount(); cat++) {
{
Q_OBJECT
public:
- enum Role {
+ enum Role
+ {
ActionRole = Qt::UserRole,
DefaultShortcutRole,
ActiveShortcutRole,
IsConfigurableRole
};
- ShortcutsModel(const QHash<QString, ActionCollection *> &actionCollections, QObject *parent = nullptr);
+ ShortcutsModel(const QHash<QString, ActionCollection*>& actionCollections, QObject* parent = nullptr);
~ShortcutsModel() override;
- QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
- QModelIndex parent(const QModelIndex &child) const override;
- int columnCount(const QModelIndex &parent = QModelIndex()) const override;
- int rowCount(const QModelIndex &parent = QModelIndex()) const override;
+ QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override;
+ QModelIndex parent(const QModelIndex& child) const override;
+ int columnCount(const QModelIndex& parent = QModelIndex()) const override;
+ int rowCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
- bool setData(const QModelIndex &index, const QVariant &value, int role = ActiveShortcutRole) override;
+ QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
+ bool setData(const QModelIndex& index, const QVariant& value, int role = ActiveShortcutRole) override;
public slots:
//! Load shortcuts from the ActionCollections
void changed(bool changed);
private:
- struct Item {
- inline Item() { parentItem = nullptr; collection = nullptr; action = nullptr; }
+ struct Item
+ {
+ inline Item()
+ {
+ parentItem = nullptr;
+ collection = nullptr;
+ action = nullptr;
+ }
inline ~Item() { qDeleteAll(actionItems); }
int row;
- Item *parentItem;
- ActionCollection *collection;
- Action *action;
+ Item* parentItem;
+ ActionCollection* collection;
+ Action* action;
QKeySequence shortcut;
- QList<Item *> actionItems;
+ QList<Item*> actionItems;
};
- QList<Item *> _categoryItems;
+ QList<Item*> _categoryItems;
int _changedCount;
};
-
-#endif // SHORTCUTSMODEL_H
+#endif // SHORTCUTSMODEL_H
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include <QTimer>
-
#include "shortcutssettingspage.h"
+#include <QTimer>
+
#include "action.h"
#include "actioncollection.h"
#include "qtui.h"
#include "shortcutsmodel.h"
#include "util.h"
-ShortcutsFilter::ShortcutsFilter(QObject *parent) : QSortFilterProxyModel(parent)
+ShortcutsFilter::ShortcutsFilter(QObject* parent)
+ : QSortFilterProxyModel(parent)
{
setDynamicSortFilter(true);
}
-
-void ShortcutsFilter::setFilterString(const QString &filterString)
+void ShortcutsFilter::setFilterString(const QString& filterString)
{
_filterString = filterString;
invalidateFilter();
}
-
-bool ShortcutsFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
+bool ShortcutsFilter::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
if (!source_parent.isValid())
return true;
QModelIndex index = source_parent.model()->index(source_row, 0, source_parent);
Q_ASSERT(index.isValid());
- if (!qobject_cast<Action *>(index.data(ShortcutsModel::ActionRole).value<QObject *>())->isShortcutConfigurable())
+ if (!qobject_cast<Action*>(index.data(ShortcutsModel::ActionRole).value<QObject*>())->isShortcutConfigurable())
return false;
for (int col = 0; col < source_parent.model()->columnCount(source_parent); col++) {
return false;
}
-
/****************************************************************************/
-ShortcutsSettingsPage::ShortcutsSettingsPage(const QHash<QString, ActionCollection *> &actionCollections, QWidget *parent)
- : SettingsPage(tr("Interface"), tr("Shortcuts"), parent),
- _shortcutsModel(new ShortcutsModel(actionCollections, this)),
- _shortcutsFilter(new ShortcutsFilter(this))
+ShortcutsSettingsPage::ShortcutsSettingsPage(const QHash<QString, ActionCollection*>& actionCollections, QWidget* parent)
+ : SettingsPage(tr("Interface"), tr("Shortcuts"), parent)
+ , _shortcutsModel(new ShortcutsModel(actionCollections, this))
+ , _shortcutsFilter(new ShortcutsFilter(this))
{
ui.setupUi(this);
QTimer::singleShot(0, ui.searchEdit, [widget = ui.searchEdit]() { widget->setFocus(); });
}
-
void ShortcutsSettingsPage::setWidgetStates()
{
if (ui.shortcutsView->currentIndex().isValid() && ui.shortcutsView->currentIndex().parent().isValid()) {
}
}
-
-void ShortcutsSettingsPage::on_searchEdit_textChanged(const QString &text)
+void ShortcutsSettingsPage::on_searchEdit_textChanged(const QString& text)
{
_shortcutsFilter->setFilterString(text);
}
-
-void ShortcutsSettingsPage::keySequenceChanged(const QKeySequence &seq, const QModelIndex &conflicting)
+void ShortcutsSettingsPage::keySequenceChanged(const QKeySequence& seq, const QModelIndex& conflicting)
{
if (conflicting.isValid())
_shortcutsModel->setData(conflicting, QKeySequence(), ShortcutsModel::ActiveShortcutRole);
setWidgetStates();
}
-
void ShortcutsSettingsPage::toggledCustomOrDefault()
{
if (!ui.shortcutsView->currentIndex().isValid())
setWidgetStates();
}
-
void ShortcutsSettingsPage::save()
{
_shortcutsModel->commit();
SettingsPage::save();
}
-
void ShortcutsSettingsPage::load()
{
_shortcutsModel->load();
SettingsPage::load();
}
-
void ShortcutsSettingsPage::defaults()
{
_shortcutsModel->defaults();
{
Q_OBJECT
public:
- ShortcutsFilter(QObject *parent = nullptr);
+ ShortcutsFilter(QObject* parent = nullptr);
public slots:
- void setFilterString(const QString &filterString);
+ void setFilterString(const QString& filterString);
protected:
- bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override;
+ bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override;
private:
QString _filterString;
};
-
class ShortcutsSettingsPage : public SettingsPage
{
Q_OBJECT
public:
- ShortcutsSettingsPage(const QHash<QString, ActionCollection *> &actionCollections, QWidget *parent = nullptr);
+ ShortcutsSettingsPage(const QHash<QString, ActionCollection*>& actionCollections, QWidget* parent = nullptr);
inline bool hasDefaults() const override { return true; }
void defaults() override;
private slots:
- void on_searchEdit_textChanged(const QString &text);
- void keySequenceChanged(const QKeySequence &seq, const QModelIndex &conflicting);
+ void on_searchEdit_textChanged(const QString& text);
+ void keySequenceChanged(const QKeySequence& seq, const QModelIndex& conflicting);
void setWidgetStates();
void toggledCustomOrDefault();
private:
Ui::ShortcutsSettingsPage ui;
- ShortcutsModel *_shortcutsModel;
- ShortcutsFilter *_shortcutsFilter;
+ ShortcutsModel* _shortcutsModel;
+ ShortcutsFilter* _shortcutsFilter;
};
-
-#endif // SHORTCUTSSETTINGSPAGE_H
+#endif // SHORTCUTSSETTINGSPAGE_H
#include "qtui.h"
-SonnetSettingsPage::SonnetSettingsPage(QWidget *parent)
+SonnetSettingsPage::SonnetSettingsPage(QWidget* parent)
: SettingsPage(tr("Interface"), tr("Spell Checking"), parent)
{
- auto *layout = new QVBoxLayout(this);
+ auto* layout = new QVBoxLayout(this);
_configWidget = new Sonnet::ConfigWidget(this);
layout->addWidget(_configWidget);
connect(_configWidget, &Sonnet::ConfigWidget::configChanged, this, &SonnetSettingsPage::widgetHasChanged);
}
-
bool SonnetSettingsPage::hasDefaults() const
{
return true;
}
-
void SonnetSettingsPage::defaults()
{
_configWidget->slotDefault();
widgetHasChanged();
}
-
void SonnetSettingsPage::load()
{
SettingsPage::load();
}
-
void SonnetSettingsPage::save()
{
_configWidget->save();
SettingsPage::save();
}
-
void SonnetSettingsPage::widgetHasChanged()
{
if (!hasChanged())
Q_OBJECT
public:
- SonnetSettingsPage(QWidget *parent = nullptr);
+ SonnetSettingsPage(QWidget* parent = nullptr);
bool hasDefaults() const override;
void widgetHasChanged();
private:
- Sonnet::ConfigWidget *_configWidget;
+ Sonnet::ConfigWidget* _configWidget;
};
#include "topicwidgetsettingspage.h"
-TopicWidgetSettingsPage::TopicWidgetSettingsPage(QWidget *parent)
+TopicWidgetSettingsPage::TopicWidgetSettingsPage(QWidget* parent)
: SettingsPage(tr("Interface"), tr("Topic Widget"), parent)
{
ui.setupUi(this);
#define TOPICWIDGETSETTINGSPAGE_H_
#include "settingspage.h"
+
#include "ui_topicwidgetsettingspage.h"
class TopicWidgetSettingsPage : public SettingsPage
Q_OBJECT
public:
- TopicWidgetSettingsPage(QWidget *parent = nullptr);
+ TopicWidgetSettingsPage(QWidget* parent = nullptr);
inline bool hasDefaults() const override { return true; }
inline QString settingsKey() const override { return QString("TopicWidget"); }
};
-
#endif
#include "icon.h"
#include "networkssettingspage.h"
-SimpleNetworkEditor::SimpleNetworkEditor(QWidget *parent)
+SimpleNetworkEditor::SimpleNetworkEditor(QWidget* parent)
: QWidget(parent)
{
ui.setupUi(this);
connect(ui.channelList, &QTextEdit::textChanged, this, &SimpleNetworkEditor::widgetHasChanged);
}
-
void SimpleNetworkEditor::setWidgetStates()
{
if (ui.serverList->selectedItems().count()) {
}
}
-
-void SimpleNetworkEditor::displayNetworkInfo(const NetworkInfo &networkInfo)
+void SimpleNetworkEditor::displayNetworkInfo(const NetworkInfo& networkInfo)
{
_networkInfo = networkInfo;
ui.serverList->clear();
- foreach(Network::Server server, _networkInfo.serverList) {
- QListWidgetItem *item = new QListWidgetItem(QString("%1:%2").arg(server.host).arg(server.port));
+ foreach (Network::Server server, _networkInfo.serverList) {
+ QListWidgetItem* item = new QListWidgetItem(QString("%1:%2").arg(server.host).arg(server.port));
if (server.useSsl)
item->setIcon(icon::get("document-encrypt"));
ui.serverList->addItem(item);
setWidgetStates();
}
-
-void SimpleNetworkEditor::saveToNetworkInfo(NetworkInfo &networkInfo)
+void SimpleNetworkEditor::saveToNetworkInfo(NetworkInfo& networkInfo)
{
_networkInfo.networkName = ui.networkNameEdit->text();
networkInfo = _networkInfo;
}
-
QStringList SimpleNetworkEditor::defaultChannels() const
{
- return ui.channelList->toPlainText().split("\n", QString::SkipEmptyParts);
+ return ui.channelList->toPlainText().split("\n", QString::SkipEmptyParts);
}
-
-void SimpleNetworkEditor::setDefaultChannels(const QStringList &channels)
+void SimpleNetworkEditor::setDefaultChannels(const QStringList& channels)
{
ui.channelList->setPlainText(channels.join("\n"));
}
-
void SimpleNetworkEditor::on_serverList_itemSelectionChanged()
{
setWidgetStates();
}
-
void SimpleNetworkEditor::on_addServer_clicked()
{
ServerEditDlg dlg(Network::Server(), this);
}
}
-
void SimpleNetworkEditor::on_editServer_clicked()
{
int cur = ui.serverList->currentRow();
}
}
-
void SimpleNetworkEditor::on_deleteServer_clicked()
{
int cur = ui.serverList->currentRow();
emit widgetHasChanged();
}
-
void SimpleNetworkEditor::on_upServer_clicked()
{
int cur = ui.serverList->currentRow();
emit widgetHasChanged();
}
-
void SimpleNetworkEditor::on_downServer_clicked()
{
int cur = ui.serverList->currentRow();
#ifndef SIMPLENETWORKEDITOR_H
#define SIMPLENETWORKEDITOR_H
-#include "ui_simplenetworkeditor.h"
-
#include "network.h"
+#include "ui_simplenetworkeditor.h"
+
class SimpleNetworkEditor : public QWidget
{
Q_OBJECT
public:
- SimpleNetworkEditor(QWidget *parent = nullptr);
+ SimpleNetworkEditor(QWidget* parent = nullptr);
- void displayNetworkInfo(const NetworkInfo &networkInfo);
- void saveToNetworkInfo(NetworkInfo &networkInfo);
+ void displayNetworkInfo(const NetworkInfo& networkInfo);
+ void saveToNetworkInfo(NetworkInfo& networkInfo);
QStringList defaultChannels() const;
- void setDefaultChannels(const QStringList &channels);
+ void setDefaultChannels(const QStringList& channels);
signals:
void widgetHasChanged();
NetworkInfo _networkInfo;
};
-
-#endif //SIMPLENETWORKEDITOR_H
+#endif // SIMPLENETWORKEDITOR_H
#include <iostream>
-#include <QtGui>
-#include <QtGlobal>
#include <QMetaObject>
+#include <QtGlobal>
+#include <QtGui>
-#include <libsnore/snore.h>
#include <libsnore/notification/notification.h>
+#include <libsnore/snore.h>
#include "client.h"
#include "icon.h"
#include "networkmodel.h"
-#include "systraynotificationbackend.h"
#include "qtui.h"
+#include "systraynotificationbackend.h"
-
-SnoreNotificationBackend::SnoreNotificationBackend (QObject *parent)
+SnoreNotificationBackend::SnoreNotificationBackend(QObject* parent)
: AbstractNotificationBackend(parent)
, m_icon(icon::get("quassel"))
{
-
Snore::SnoreCore::instance().loadPlugins(
#ifndef HAVE_KDE
- Snore::SnorePlugin::Backend |
+ Snore::SnorePlugin::Backend |
#endif
- Snore::SnorePlugin::SecondaryBackend | Snore::SnorePlugin::Settings);
+ Snore::SnorePlugin::SecondaryBackend | Snore::SnorePlugin::Settings);
m_application = Snore::Application("Quassel", m_icon);
- m_application.hints().setValue("windows-app-id","QuasselProject.QuasselIRC");
+ m_application.hints().setValue("windows-app-id", "QuasselProject.QuasselIRC");
m_application.hints().setValue("pushover-token", "arNtsi983QSZUqU3KAZrFLKHGFPkdL");
connect(&Snore::SnoreCore::instance(), &Snore::SnoreCore::actionInvoked, this, &SnoreNotificationBackend::actionInvoked);
-
m_alert = Snore::Alert(tr("Private Message"), m_icon);
m_application.addAlert(m_alert);
Snore::SnoreCore::instance().setDefaultApplication(m_application);
Snore::SnoreCore::instance().deregisterApplication(m_application);
}
-void SnoreNotificationBackend::notify(const Notification &n)
+void SnoreNotificationBackend::notify(const Notification& n)
{
#ifndef HAVE_KDE
if (m_systrayBackend != nullptr) {
return;
}
#endif
- QString title = QString("%1 - %2").arg(Client::networkModel()->networkName(n.bufferId), Client::networkModel()->bufferName(n.bufferId));
+ QString title = QString("%1 - %2").arg(Client::networkModel()->networkName(n.bufferId), Client::networkModel()->bufferName(n.bufferId));
QString message = QString("<%1> %2").arg(n.sender, n.message);
Snore::Notification noti(m_application, m_alert, title, message, m_icon);
noti.hints().setValue("QUASSEL_ID", n.notificationId);
}
#endif
Snore::Notification n = Snore::SnoreCore::instance().getActiveNotificationByID(m_notificationIds.take(notificationId));
- if (n.isValid()) { // Don't close the notification if it no longer exists.
+ if (n.isValid()) { // Don't close the notification if it no longer exists.
Snore::SnoreCore::instance().requestCloseNotification(n, Snore::Notification::Closed);
}
}
emit activated(n.hints().value("QUASSEL_ID").toUInt());
}
-SettingsPage *SnoreNotificationBackend::createConfigWidget()const
+SettingsPage* SnoreNotificationBackend::createConfigWidget() const
{
return new ConfigWidget();
}
-
-void SnoreNotificationBackend::setTraybackend(const QVariant &b)
+void SnoreNotificationBackend::setTraybackend(const QVariant& b)
{
#ifndef HAVE_KDE
if (!b.toBool()) {
m_systrayBackend = new SystrayNotificationBackend(this);
QtUi::registerNotificationBackend(m_systrayBackend);
}
- } else {
+ }
+ else {
if (m_systrayBackend != nullptr) {
QtUi::unregisterNotificationBackend(m_systrayBackend);
m_systrayBackend->deleteLater();
if (!Snore::SnoreCore::instance().aplications().contains(m_application.name())) {
Snore::SnoreCore::instance().registerApplication(m_application);
}
- } else {
+ }
+ else {
if (Snore::SnoreCore::instance().aplications().contains(m_application.name())) {
Snore::SnoreCore::instance().deregisterApplication(m_application);
}
/***************************************************************************/
-SnoreNotificationBackend::ConfigWidget::ConfigWidget(QWidget *parent)
- :SettingsPage("Internal", "SnoreNotification", parent)
+SnoreNotificationBackend::ConfigWidget::ConfigWidget(QWidget* parent)
+ : SettingsPage("Internal", "SnoreNotification", parent)
{
ui.setupUi(this);
connect(ui.useSnoreCheckBox, &QCheckBox::toggled, this, &ConfigWidget::useSnoreChanged);
ui.useSnoreCheckBox->setChecked(enabled);
ui.widget->setEnabled(enabled);
setChangedState(false);
- QMetaObject::invokeMethod(this, "changed", Qt::QueuedConnection);//hack to make apply and accept button work for snore settings widget
+ QMetaObject::invokeMethod(this, "changed", Qt::QueuedConnection); // hack to make apply and accept button work for snore settings widget
}
void SnoreNotificationBackend::ConfigWidget::save()
ui.widget->setEnabled(b);
setChangedState(true);
}
-
-
#ifndef SNORENOTIFICATIONBACKEND_H_
#define SNORENOTIFICATIONBACKEND_H_
-#include "abstractnotificationbackend.h"
+#include <libsnore/notification/notification.h>
+#include <libsnore/snore.h>
+#include "abstractnotificationbackend.h"
#include "settingspage.h"
#include "ui_snorentificationconfigwidget.h"
-#include <libsnore/snore.h>
-#include <libsnore/notification/notification.h>
-
class SystrayNotificationBackend;
-class SnoreNotificationBackend : public AbstractNotificationBackend {
+class SnoreNotificationBackend : public AbstractNotificationBackend
+{
Q_OBJECT
public:
- SnoreNotificationBackend (QObject *parent);
+ SnoreNotificationBackend(QObject* parent);
~SnoreNotificationBackend();
- void notify(const Notification &);
+ void notify(const Notification&);
void close(uint notificationId);
- virtual SettingsPage *createConfigWidget() const;
+ virtual SettingsPage* createConfigWidget() const;
public slots:
void actionInvoked(Snore::Notification);
private slots:
- void setTraybackend(const QVariant &b);
+ void setTraybackend(const QVariant& b);
private:
-
class ConfigWidget;
#ifndef HAVE_KDE
- SystrayNotificationBackend * m_systrayBackend = nullptr;
+ SystrayNotificationBackend* m_systrayBackend = nullptr;
#endif
QHash<uint, uint> m_notificationIds;
Snore::Icon m_icon;
Snore::Alert m_alert;
};
-class SnoreNotificationBackend::ConfigWidget : public SettingsPage {
+class SnoreNotificationBackend::ConfigWidget : public SettingsPage
+{
Q_OBJECT
public:
- ConfigWidget(QWidget *parent = 0);
+ ConfigWidget(QWidget* parent = 0);
bool hasDefaults() const;
void defaults();
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "sslinfodlg.h"
+
#include <QDateTime>
#include <QHostAddress>
#include <QSslCipher>
#include <QSslSocket>
-#include "sslinfodlg.h"
#include "util.h"
// ========================================
// SslInfoDlg
// ========================================
-SslInfoDlg::SslInfoDlg(const QSslSocket *socket, QWidget *parent)
- : QDialog(parent),
- _socket(socket)
+SslInfoDlg::SslInfoDlg(const QSslSocket* socket, QWidget* parent)
+ : QDialog(parent)
+ , _socket(socket)
{
ui.setupUi(this);
ui.protocol->setText(cipher.protocolString());
connect(ui.certificateChain, selectOverload<int>(&QComboBox::currentIndexChanged), this, &SslInfoDlg::setCurrentCert);
- foreach(const QSslCertificate &cert, socket->peerCertificateChain()) {
+ foreach (const QSslCertificate& cert, socket->peerCertificateChain()) {
ui.certificateChain->addItem(subjectInfo(cert, QSslCertificate::CommonName));
}
}
-
void SslInfoDlg::setCurrentCert(int index)
{
QSslCertificate cert = socket()->peerCertificateChain().at(index);
ui.trusted->setText(tr("Yes"));
else {
QString errorString = tr("No, for the following reasons:<ul>");
- foreach(const QSslError &error, socket()->sslErrors())
- errorString += "<li>" + error.errorString() + "</li>";
+ foreach (const QSslError& error, socket()->sslErrors())
+ errorString += "<li>" + error.errorString() + "</li>";
errorString += "</ul>";
ui.trusted->setText(errorString);
}
- ui.validity->setText(tr("%1 to %2").arg(cert.effectiveDate().date().toString(Qt::ISODate), cert.expiryDate().date().toString(Qt::ISODate)));
+ ui.validity->setText(
+ tr("%1 to %2").arg(cert.effectiveDate().date().toString(Qt::ISODate), cert.expiryDate().date().toString(Qt::ISODate)));
ui.md5Digest->setText(prettyDigest(cert.digest(QCryptographicHash::Md5)));
ui.sha1Digest->setText(prettyDigest(cert.digest(QCryptographicHash::Sha1)));
ui.sha256Digest->setText(prettyDigest(cert.digest(QCryptographicHash::Sha256)));
}
// in Qt5, subjectInfo returns a QStringList(); turn this into a comma-separated string instead
-QString SslInfoDlg::subjectInfo(const QSslCertificate &cert, QSslCertificate::SubjectInfo subjectInfo) const
+QString SslInfoDlg::subjectInfo(const QSslCertificate& cert, QSslCertificate::SubjectInfo subjectInfo) const
{
return cert.subjectInfo(subjectInfo).join(", ");
}
-
// same here
-QString SslInfoDlg::issuerInfo(const QSslCertificate &cert, QSslCertificate::SubjectInfo subjectInfo) const
+QString SslInfoDlg::issuerInfo(const QSslCertificate& cert, QSslCertificate::SubjectInfo subjectInfo) const
{
return cert.issuerInfo(subjectInfo).join(", ");
}
Q_OBJECT
public:
- SslInfoDlg(const QSslSocket *socket, QWidget *parent = nullptr);
- inline const QSslSocket *socket() const { return _socket; }
+ SslInfoDlg(const QSslSocket* socket, QWidget* parent = nullptr);
+ inline const QSslSocket* socket() const { return _socket; }
private slots:
void setCurrentCert(int index);
private:
// simplify handling the API changes between Qt4 and Qt5 (QString -> QStringList)
- QString subjectInfo(const QSslCertificate &cert, QSslCertificate::SubjectInfo subjectInfo) const;
- QString issuerInfo(const QSslCertificate &cert, QSslCertificate::SubjectInfo subjectInfo) const;
+ QString subjectInfo(const QSslCertificate& cert, QSslCertificate::SubjectInfo subjectInfo) const;
+ QString issuerInfo(const QSslCertificate& cert, QSslCertificate::SubjectInfo subjectInfo) const;
private:
Ui::SslInfoDlg ui;
- const QSslSocket *_socket;
+ const QSslSocket* _socket;
};
-
#endif
#ifdef HAVE_DBUS
-#include "statusnotifieritem.h"
+# include "statusnotifieritem.h"
-#include <QApplication>
-#include <QDir>
-#include <QFile>
-#include <QIcon>
-#include <QMenu>
-#include <QMouseEvent>
-#include <QTextDocument>
+# include <QApplication>
+# include <QDir>
+# include <QFile>
+# include <QIcon>
+# include <QMenu>
+# include <QMouseEvent>
+# include <QTextDocument>
-#include "icon.h"
-#include "qtui.h"
-#include "quassel.h"
-#include "statusnotifieritemdbus.h"
+# include "icon.h"
+# include "qtui.h"
+# include "quassel.h"
+# include "statusnotifieritemdbus.h"
-constexpr int kProtocolVersion {0};
+constexpr int kProtocolVersion{0};
-const QString kSniWatcherService {QLatin1String{"org.kde.StatusNotifierWatcher"}};
-const QString kSniWatcherPath {QLatin1String{"/StatusNotifierWatcher"}};
-const QString kSniPath {QLatin1String{"/StatusNotifierItem"}};
-const QString kXdgNotificationsService {QLatin1String{"org.freedesktop.Notifications"}};
-const QString kXdgNotificationsPath {QLatin1String{"/org/freedesktop/Notifications"}};
-const QString kMenuObjectPath {QLatin1String{"/MenuBar"}};
+const QString kSniWatcherService{QLatin1String{"org.kde.StatusNotifierWatcher"}};
+const QString kSniWatcherPath{QLatin1String{"/StatusNotifierWatcher"}};
+const QString kSniPath{QLatin1String{"/StatusNotifierItem"}};
+const QString kXdgNotificationsService{QLatin1String{"org.freedesktop.Notifications"}};
+const QString kXdgNotificationsPath{QLatin1String{"/org/freedesktop/Notifications"}};
+const QString kMenuObjectPath{QLatin1String{"/MenuBar"}};
-#ifdef HAVE_DBUSMENU
-# include "dbusmenuexporter.h"
+# ifdef HAVE_DBUSMENU
+# include "dbusmenuexporter.h"
/**
* Specialization to provide access to icon names
class QuasselDBusMenuExporter : public DBusMenuExporter
{
public:
- QuasselDBusMenuExporter(const QString &dbusObjectPath, QMenu *menu, const QDBusConnection &dbusConnection)
+ QuasselDBusMenuExporter(const QString& dbusObjectPath, QMenu* menu, const QDBusConnection& dbusConnection)
: DBusMenuExporter(dbusObjectPath, menu, dbusConnection)
{}
protected:
- QString iconNameForAction(QAction *action) override // TODO Qt 4.7: fixme when we have converted our iconloader
+ QString iconNameForAction(QAction* action) override // TODO Qt 4.7: fixme when we have converted our iconloader
{
QIcon icon(action->icon());
return icon.isNull() ? QString() : icon.name();
}
};
-#endif /* HAVE_DBUSMENU */
+# endif /* HAVE_DBUSMENU */
-StatusNotifierItem::StatusNotifierItem(QWidget *parent)
+StatusNotifierItem::StatusNotifierItem(QWidget* parent)
: StatusNotifierItemParent(parent)
, _iconThemeDir{QDir::tempPath() + QLatin1String{"/quassel-sni-XXXXXX"}}
{
connect(this, &StatusNotifierItem::toolTipChanged, _statusNotifierItemDBus, &StatusNotifierItemDBus::NewToolTip);
// Service watcher to keep track of the StatusNotifierWatcher service
- _serviceWatcher = new QDBusServiceWatcher(kSniWatcherService,
- QDBusConnection::sessionBus(),
- QDBusServiceWatcher::WatchForOwnerChange,
- this);
+ _serviceWatcher = new QDBusServiceWatcher(kSniWatcherService, QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForOwnerChange, this);
connect(_serviceWatcher, &QDBusServiceWatcher::serviceOwnerChanged, this, &StatusNotifierItem::serviceChange);
// Client instance for StatusNotifierWatcher
- _statusNotifierWatcher = new org::kde::StatusNotifierWatcher(kSniWatcherService,
- kSniWatcherPath,
- QDBusConnection::sessionBus(),
- this);
- connect(_statusNotifierWatcher, &OrgKdeStatusNotifierWatcherInterface::StatusNotifierHostRegistered, this, &StatusNotifierItem::checkForRegisteredHosts);
- connect(_statusNotifierWatcher, &OrgKdeStatusNotifierWatcherInterface::StatusNotifierHostUnregistered, this, &StatusNotifierItem::checkForRegisteredHosts);
+ _statusNotifierWatcher = new org::kde::StatusNotifierWatcher(kSniWatcherService, kSniWatcherPath, QDBusConnection::sessionBus(), this);
+ connect(_statusNotifierWatcher,
+ &OrgKdeStatusNotifierWatcherInterface::StatusNotifierHostRegistered,
+ this,
+ &StatusNotifierItem::checkForRegisteredHosts);
+ connect(_statusNotifierWatcher,
+ &OrgKdeStatusNotifierWatcherInterface::StatusNotifierHostUnregistered,
+ this,
+ &StatusNotifierItem::checkForRegisteredHosts);
// Client instance for notifications
_notificationsClient = new org::freedesktop::Notifications(kXdgNotificationsService,
_notificationsClientSupportsActions = desktopCapabilities.contains("actions");
}
-#ifdef HAVE_DBUSMENU
- new QuasselDBusMenuExporter(menuObjectPath(), trayMenu(), _statusNotifierItemDBus->dbusConnection()); // will be added as menu child
-#endif
+# ifdef HAVE_DBUSMENU
+ new QuasselDBusMenuExporter(menuObjectPath(), trayMenu(), _statusNotifierItemDBus->dbusConnection()); // will be added as menu child
+# endif
}
-
-void StatusNotifierItem::serviceChange(const QString &name, const QString &oldOwner, const QString &newOwner)
+void StatusNotifierItem::serviceChange(const QString& name, const QString& oldOwner, const QString& newOwner)
{
Q_UNUSED(name);
if (newOwner.isEmpty()) {
- //unregistered
+ // unregistered
setMode(Mode::Legacy);
}
else if (oldOwner.isEmpty()) {
- //registered
+ // registered
setMode(Mode::StatusNotifier);
}
}
-
void StatusNotifierItem::registerToWatcher()
{
if (_statusNotifierWatcher->isValid() && _statusNotifierWatcher->property("ProtocolVersion").toInt() == kProtocolVersion) {
- auto registerMethod = QDBusMessage::createMethodCall(kSniWatcherService, kSniWatcherPath, kSniWatcherService,
+ auto registerMethod = QDBusMessage::createMethodCall(kSniWatcherService,
+ kSniWatcherPath,
+ kSniWatcherService,
QLatin1String{"RegisterStatusNotifierItem"});
registerMethod.setArguments(QVariantList() << _statusNotifierItemDBus->service());
- _statusNotifierItemDBus->dbusConnection().callWithCallback(registerMethod, this, SLOT(checkForRegisteredHosts()), SLOT(onDBusError(QDBusError)));
+ _statusNotifierItemDBus->dbusConnection().callWithCallback(registerMethod,
+ this,
+ SLOT(checkForRegisteredHosts()),
+ SLOT(onDBusError(QDBusError)));
}
else {
setMode(Mode::Legacy);
}
}
-
void StatusNotifierItem::checkForRegisteredHosts()
{
if (!_statusNotifierWatcher || !_statusNotifierWatcher->property("IsStatusNotifierHostRegistered").toBool()) {
}
}
-
-void StatusNotifierItem::onDBusError(const QDBusError &error)
+void StatusNotifierItem::onDBusError(const QDBusError& error)
{
qWarning() << "StatusNotifierItem encountered a D-Bus error:" << error;
setMode(Mode::Legacy);
}
-
void StatusNotifierItem::refreshIcons()
{
if (!_iconThemePath.isEmpty()) {
QDir baseDir{_iconThemePath + "/hicolor"};
baseDir.removeRecursively();
- for (auto &&trayState : { State::Active, State::Passive, State::NeedsAttention }) {
+ for (auto&& trayState : {State::Active, State::Passive, State::NeedsAttention}) {
auto iconName = SystemTray::iconName(trayState);
QIcon icon = icon::get(iconName);
if (!icon.isNull()) {
- for (auto &&size : icon.availableSizes()) {
+ for (auto&& size : icon.availableSizes()) {
auto pixDir = QString{"%1/%2x%3/status"}.arg(baseDir.absolutePath()).arg(size.width()).arg(size.height());
QDir{}.mkpath(pixDir);
if (!icon.pixmap(size).save(pixDir + "/" + iconName + ".png")) {
// No theme icon found; use fallback from resources
auto iconDir = QString{"%1/24x24/status"}.arg(baseDir.absolutePath());
QDir{}.mkpath(iconDir);
- if (!QFile::copy(QString{":/icons/hicolor/24x24/status/%1.svg"}.arg(iconName),
- QString{"%1/%2.svg"}.arg(iconDir, iconName))) {
+ if (!QFile::copy(QString{":/icons/hicolor/24x24/status/%1.svg"}.arg(iconName), QString{"%1/%2.svg"}.arg(iconDir, iconName))) {
qWarning() << "Could not access fallback tray icon" << iconName;
continue;
}
}
}
-
bool StatusNotifierItem::isSystemTrayAvailable() const
{
if (mode() == Mode::StatusNotifier) {
return StatusNotifierItemParent::isSystemTrayAvailable();
}
-
void StatusNotifierItem::onModeChanged(Mode mode)
{
if (mode == Mode::StatusNotifier) {
}
}
-
void StatusNotifierItem::onStateChanged(State state)
{
if (mode() == Mode::StatusNotifier) {
}
}
-
void StatusNotifierItem::onVisibilityChanged(bool isVisible)
{
if (mode() == Mode::StatusNotifier) {
}
}
-
QString StatusNotifierItem::title() const
{
return QString("Quassel IRC");
}
-
QString StatusNotifierItem::iconName() const
{
return currentIconName();
}
-
QString StatusNotifierItem::attentionIconName() const
{
return currentAttentionIconName();
}
-
QString StatusNotifierItem::toolTipIconName() const
{
return "quassel";
}
-
QString StatusNotifierItem::iconThemePath() const
{
return _iconThemePath;
}
-
QString StatusNotifierItem::menuObjectPath() const
{
return kMenuObjectPath;
}
-
-void StatusNotifierItem::activated(const QPoint &pos)
+void StatusNotifierItem::activated(const QPoint& pos)
{
Q_UNUSED(pos)
activate(Trigger);
}
-
-bool StatusNotifierItem::eventFilter(QObject *watched, QEvent *event)
+bool StatusNotifierItem::eventFilter(QObject* watched, QEvent* event)
{
if (mode() == StatusNotifier) {
if (watched == trayMenu() && event->type() == QEvent::HoverLeave) {
return StatusNotifierItemParent::eventFilter(watched, event);
}
-
-void StatusNotifierItem::showMessage(const QString &title, const QString &message_, SystemTray::MessageIcon icon, int timeout, uint notificationId)
+void StatusNotifierItem::showMessage(const QString& title, const QString& message_, SystemTray::MessageIcon icon, int timeout, uint notificationId)
{
QString message = message_;
if (_notificationsClient->isValid()) {
QStringList actions;
if (_notificationsClientSupportsActions)
- actions << "activate" << "View";
+ actions << "activate"
+ << "View";
// we always queue notifications right now
QDBusReply<uint> reply = _notificationsClient->Notify(title, 0, "quassel", title, message, actions, QVariantMap(), timeout);
StatusNotifierItemParent::showMessage(title, message, icon, timeout, notificationId);
}
-
void StatusNotifierItem::closeMessage(uint notificationId)
{
- for (auto &&dbusid : _notificationsIdMap.keys()) {
+ for (auto&& dbusid : _notificationsIdMap.keys()) {
if (_notificationsIdMap.value(dbusid) == notificationId) {
_notificationsIdMap.remove(dbusid);
_notificationsClient->CloseNotification(dbusid);
StatusNotifierItemParent::closeMessage(notificationId);
}
-
void StatusNotifierItem::notificationClosed(uint dbusid, uint reason)
{
Q_UNUSED(reason)
emit messageClosed(_notificationsIdMap.take(dbusid));
}
-
-void StatusNotifierItem::notificationInvoked(uint dbusid, const QString &action)
+void StatusNotifierItem::notificationInvoked(uint dbusid, const QString& action)
{
Q_UNUSED(action)
emit messageClicked(_notificationsIdMap.value(dbusid, 0));
}
-
#endif
#ifdef HAVE_DBUS
-#include <QDBusError>
-#include <QHash>
-#include <QString>
-#include <QTemporaryDir>
-
-#include "notificationsclient.h"
-#include "systemtray.h"
-#include "statusnotifierwatcher.h"
-
-#ifdef QT_NO_SYSTEMTRAYICON
-# define StatusNotifierItemParent SystemTray
-#else
-# define StatusNotifierItemParent LegacySystemTray
-# include "legacysystemtray.h"
-#endif
+# include <QDBusError>
+# include <QHash>
+# include <QString>
+# include <QTemporaryDir>
+
+# include "notificationsclient.h"
+# include "statusnotifierwatcher.h"
+# include "systemtray.h"
+
+# ifdef QT_NO_SYSTEMTRAYICON
+# define StatusNotifierItemParent SystemTray
+# else
+# define StatusNotifierItemParent LegacySystemTray
+# include "legacysystemtray.h"
+# endif
class QDBusServiceWatcher;
Q_OBJECT
public:
- explicit StatusNotifierItem(QWidget *parent);
+ explicit StatusNotifierItem(QWidget* parent);
bool isSystemTrayAvailable() const override;
public slots:
- void showMessage(const QString &title, const QString &message, MessageIcon icon = Information, int msTimeout = 10000, uint notificationId = 0) override;
+ void showMessage(const QString& title,
+ const QString& message,
+ MessageIcon icon = Information,
+ int msTimeout = 10000,
+ uint notificationId = 0) override;
void closeMessage(uint notificationId) override;
protected:
QString iconThemePath() const;
QString menuObjectPath() const;
- bool eventFilter(QObject *watched, QEvent *event) override;
+ bool eventFilter(QObject* watched, QEvent* event) override;
private slots:
- void activated(const QPoint &pos);
- void serviceChange(const QString &name, const QString &oldOwner, const QString &newOwner);
+ void activated(const QPoint& pos);
+ void serviceChange(const QString& name, const QString& oldOwner, const QString& newOwner);
void checkForRegisteredHosts();
- void onDBusError(const QDBusError &error);
+ void onDBusError(const QDBusError& error);
void notificationClosed(uint id, uint reason);
- void notificationInvoked(uint id, const QString &action);
+ void notificationInvoked(uint id, const QString& action);
void refreshIcons();
private:
void registerToWatcher();
- QDBusServiceWatcher *_serviceWatcher{nullptr};
- StatusNotifierItemDBus *_statusNotifierItemDBus{nullptr};
- org::kde::StatusNotifierWatcher *_statusNotifierWatcher{nullptr};
- org::freedesktop::Notifications *_notificationsClient{nullptr};
+ QDBusServiceWatcher* _serviceWatcher{nullptr};
+ StatusNotifierItemDBus* _statusNotifierItemDBus{nullptr};
+ org::kde::StatusNotifierWatcher* _statusNotifierWatcher{nullptr};
+ org::freedesktop::Notifications* _notificationsClient{nullptr};
bool _notificationsClientSupportsMarkup{false};
bool _notificationsClientSupportsActions{false};
quint32 _lastNotificationsDBusId{0};
- QHash<uint, uint> _notificationsIdMap; ///< Maps our own notification ID to the D-Bus one
+ QHash<uint, uint> _notificationsIdMap; ///< Maps our own notification ID to the D-Bus one
QString _iconThemePath;
QString _menuObjectPath;
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
-#include "mainwin.h"
-#include "qtui.h"
#include "statusnotifieritemdbus.h"
-#include "statusnotifieritem.h"
#include <QApplication>
#include <QDBusConnection>
#include <QMenu>
#include <QPixmap>
-#include "statusnotifierwatcher.h"
+#include "mainwin.h"
+#include "qtui.h"
+#include "statusnotifieritem.h"
#include "statusnotifieritemadaptor.h"
+#include "statusnotifierwatcher.h"
#ifdef Q_OS_WIN64
__inline int toInt(WId wid)
return (int)wid;
}
-
#endif
// Marshall the ImageStruct data into a D-BUS argument
-const QDBusArgument &operator<<(QDBusArgument &argument, const DBusImageStruct &icon)
+const QDBusArgument& operator<<(QDBusArgument& argument, const DBusImageStruct& icon)
{
argument.beginStructure();
argument << icon.width;
return argument;
}
-
// Retrieve the ImageStruct data from the D-BUS argument
-const QDBusArgument &operator>>(const QDBusArgument &argument, DBusImageStruct &icon)
+const QDBusArgument& operator>>(const QDBusArgument& argument, DBusImageStruct& icon)
{
qint32 width;
qint32 height;
return argument;
}
-
// Marshall the ImageVector data into a D-BUS argument
-const QDBusArgument &operator<<(QDBusArgument &argument, const DBusImageVector &iconVector)
+const QDBusArgument& operator<<(QDBusArgument& argument, const DBusImageVector& iconVector)
{
argument.beginArray(qMetaTypeId<DBusImageStruct>());
- for (const auto &i : iconVector) {
+ for (const auto& i : iconVector) {
argument << i;
}
argument.endArray();
return argument;
}
-
// Retrieve the ImageVector data from the D-BUS argument
-const QDBusArgument &operator>>(const QDBusArgument &argument, DBusImageVector &iconVector)
+const QDBusArgument& operator>>(const QDBusArgument& argument, DBusImageVector& iconVector)
{
argument.beginArray();
iconVector.clear();
return argument;
}
-
// Marshall the ToolTipStruct data into a D-BUS argument
-const QDBusArgument &operator<<(QDBusArgument &argument, const DBusToolTipStruct &toolTip)
+const QDBusArgument& operator<<(QDBusArgument& argument, const DBusToolTipStruct& toolTip)
{
argument.beginStructure();
argument << toolTip.icon;
return argument;
}
-
// Retrieve the ToolTipStruct data from the D-BUS argument
-const QDBusArgument &operator>>(const QDBusArgument &argument, DBusToolTipStruct &toolTip)
+const QDBusArgument& operator>>(const QDBusArgument& argument, DBusToolTipStruct& toolTip)
{
QString icon;
DBusImageVector image;
return argument;
}
-
int StatusNotifierItemDBus::s_serviceCount = 0;
-StatusNotifierItemDBus::StatusNotifierItemDBus(StatusNotifierItem *parent)
- : QObject(parent),
- m_statusNotifierItem(parent),
- m_dbus(QDBusConnection::connectToBus(QDBusConnection::SessionBus,
- QString("org.kde.StatusNotifierItem-%1-%2").arg(QCoreApplication::applicationPid()).arg(++s_serviceCount)))
+StatusNotifierItemDBus::StatusNotifierItemDBus(StatusNotifierItem* parent)
+ : QObject(parent)
+ , m_statusNotifierItem(parent)
+ , m_dbus(
+ QDBusConnection::connectToBus(QDBusConnection::SessionBus,
+ QString("org.kde.StatusNotifierItem-%1-%2").arg(QCoreApplication::applicationPid()).arg(++s_serviceCount)))
{
new StatusNotifierItemAdaptor(this);
}
-
StatusNotifierItemDBus::~StatusNotifierItemDBus()
{
unregisterTrayIcon();
}
-
QDBusConnection StatusNotifierItemDBus::dbusConnection() const
{
return m_dbus;
}
-
// FIXME: prevent double registrations, also test this on platforms != KDE
//
void StatusNotifierItemDBus::registerTrayIcon()
m_dbus.registerObject("/StatusNotifierItem", this);
}
-
// FIXME: see above
void StatusNotifierItemDBus::unregisterTrayIcon()
{
}
}
-
QString StatusNotifierItemDBus::service() const
{
return m_dbus.baseService();
}
-
-//DBUS slots
-//Values and calls have been adapted to Quassel
+// DBUS slots
+// Values and calls have been adapted to Quassel
QString StatusNotifierItemDBus::Category() const
{
- return QString("Communications"); // no need to make this configurable for Quassel
+ return QString("Communications"); // no need to make this configurable for Quassel
}
-
QString StatusNotifierItemDBus::Title() const
{
return m_statusNotifierItem->title();
}
-
QString StatusNotifierItemDBus::Id() const
{
return QString("QuasselIRC");
}
-
QString StatusNotifierItemDBus::Status() const
{
- return m_statusNotifierItem->metaObject()->enumerator(m_statusNotifierItem->metaObject()->indexOfEnumerator("State")).valueToKey(m_statusNotifierItem->state());
+ return m_statusNotifierItem->metaObject()
+ ->enumerator(m_statusNotifierItem->metaObject()->indexOfEnumerator("State"))
+ .valueToKey(m_statusNotifierItem->state());
}
-
int StatusNotifierItemDBus::WindowId() const
{
return toInt(QtUi::mainWindow()->winId());
}
-
-//Icon
-//We don't need to support serialized icon data in Quassel
+// Icon
+// We don't need to support serialized icon data in Quassel
QString StatusNotifierItemDBus::IconName() const
{
return m_statusNotifierItem->iconName();
}
-
DBusImageVector StatusNotifierItemDBus::IconPixmap() const
{
return DBusImageVector();
}
-
QString StatusNotifierItemDBus::OverlayIconName() const
{
return QString();
}
-
DBusImageVector StatusNotifierItemDBus::OverlayIconPixmap() const
{
return DBusImageVector();
}
-
-//Requesting attention icon and movie
+// Requesting attention icon and movie
QString StatusNotifierItemDBus::AttentionIconName() const
{
return m_statusNotifierItem->attentionIconName();
}
-
DBusImageVector StatusNotifierItemDBus::AttentionIconPixmap() const
{
return DBusImageVector();
}
-
QString StatusNotifierItemDBus::AttentionMovieName() const
{
return QString();
}
-
-//ToolTip
+// ToolTip
DBusToolTipStruct StatusNotifierItemDBus::ToolTip() const
{
return toolTip;
}
-
QString StatusNotifierItemDBus::IconThemePath() const
{
return m_statusNotifierItem->iconThemePath();
}
-
-//Menu
+// Menu
QDBusObjectPath StatusNotifierItemDBus::Menu() const
{
return QDBusObjectPath(m_statusNotifierItem->menuObjectPath());
}
-
-//Interaction
+// Interaction
void StatusNotifierItemDBus::ContextMenu(int x, int y)
{
return;
}
- //TODO: nicer placement, possible?
+ // TODO: nicer placement, possible?
if (!m_statusNotifierItem->trayMenu()->isVisible()) {
m_statusNotifierItem->trayMenu()->popup(QPoint(x, y));
}
}
}
-
void StatusNotifierItemDBus::Activate(int x, int y)
{
m_statusNotifierItem->activated(QPoint(x, y));
}
-
void StatusNotifierItemDBus::SecondaryActivate(int x, int y)
{
Q_UNUSED(x)
// emit m_statusNotifierItem->secondaryActivateRequested(QPoint(x,y));
}
-
-void StatusNotifierItemDBus::Scroll(int delta, const QString &orientation)
+void StatusNotifierItemDBus::Scroll(int delta, const QString& orientation)
{
Q_UNUSED(delta)
Q_UNUSED(orientation)
#ifndef STATUSNOTIFIERITEMDBUS_H_
#define STATUSNOTIFIERITEMDBUS_H_
-#include <QObject>
-#include <QString>
#include <QDBusArgument>
#include <QDBusConnection>
+#include <QObject>
#include <QPixmap>
+#include <QString>
-//Custom message type for DBus
-struct DBusImageStruct {
+// Custom message type for DBus
+struct DBusImageStruct
+{
int width;
int height;
QByteArray data;
using DBusImageVector = QVector<DBusImageStruct>;
-struct DBusToolTipStruct {
+struct DBusToolTipStruct
+{
QString icon;
DBusImageVector image;
QString title;
Q_PROPERTY(QDBusObjectPath Menu READ Menu)
friend class StatusNotifierItem;
+
public:
- StatusNotifierItemDBus(StatusNotifierItem *parent);
+ StatusNotifierItemDBus(StatusNotifierItem* parent);
~StatusNotifierItemDBus() override;
/**
QDBusObjectPath Menu() const;
public slots:
- //interaction
+ // interaction
/**
* Shows the context menu associated to this item
* at the desired screen position
/**
* Inform this item that the mouse wheel was used on its representation
*/
- void Scroll(int delta, const QString &orientation);
+ void Scroll(int delta, const QString& orientation);
signals:
/**
* Signal the new status when it has been changed
* @see Status
*/
- void NewStatus(const QString &status);
+ void NewStatus(const QString& status);
private:
- StatusNotifierItem *m_statusNotifierItem;
+ StatusNotifierItem* m_statusNotifierItem;
QDBusConnection m_dbus;
static int s_serviceCount;
};
-
-const QDBusArgument &operator<<(QDBusArgument &argument, const DBusImageStruct &icon);
-const QDBusArgument &operator>>(const QDBusArgument &argument, DBusImageStruct &icon);
+const QDBusArgument& operator<<(QDBusArgument& argument, const DBusImageStruct& icon);
+const QDBusArgument& operator>>(const QDBusArgument& argument, DBusImageStruct& icon);
Q_DECLARE_METATYPE(DBusImageStruct)
-const QDBusArgument &operator<<(QDBusArgument &argument, const DBusImageVector &iconVector);
-const QDBusArgument &operator>>(const QDBusArgument &argument, DBusImageVector &iconVector);
+const QDBusArgument& operator<<(QDBusArgument& argument, const DBusImageVector& iconVector);
+const QDBusArgument& operator>>(const QDBusArgument& argument, DBusImageVector& iconVector);
Q_DECLARE_METATYPE(DBusImageVector)
-const QDBusArgument &operator<<(QDBusArgument &argument, const DBusToolTipStruct &toolTip);
-const QDBusArgument &operator>>(const QDBusArgument &argument, DBusToolTipStruct &toolTip);
+const QDBusArgument& operator<<(QDBusArgument& argument, const DBusToolTipStruct& toolTip);
+const QDBusArgument& operator>>(const QDBusArgument& argument, DBusToolTipStruct& toolTip);
Q_DECLARE_METATYPE(DBusToolTipStruct)
#include "icon.h"
#include "qtui.h"
-SystemTray::SystemTray(QWidget *parent)
- : QObject(parent),
- _associatedWidget(parent)
+SystemTray::SystemTray(QWidget* parent)
+ : QObject(parent)
+ , _associatedWidget(parent)
{
Q_ASSERT(parent);
NotificationSettings{}.initAndNotify("Systray/Animate", this, &SystemTray::enableBlinkChanged, false);
UiStyleSettings{}.initAndNotify("Icons/InvertTray", this, &SystemTray::invertTrayIconChanged, false);
- ActionCollection *coll = QtUi::actionCollection("General");
+ ActionCollection* coll = QtUi::actionCollection("General");
_minimizeRestoreAction = new Action(tr("&Minimize"), this, this, &SystemTray::minimizeRestore);
_trayMenu = new QMenu(associatedWidget());
connect(&_blinkTimer, &QTimer::timeout, this, &SystemTray::onBlinkTimeout);
}
-
SystemTray::~SystemTray()
{
_trayMenu->deleteLater();
}
-
-QWidget *SystemTray::associatedWidget() const
+QWidget* SystemTray::associatedWidget() const
{
return _associatedWidget;
}
-
bool SystemTray::isSystemTrayAvailable() const
{
return false;
}
-
bool SystemTray::isVisible() const
{
return _isVisible;
}
-
void SystemTray::setVisible(bool visible)
{
if (visible != _isVisible) {
}
}
-
SystemTray::Mode SystemTray::mode() const
{
return _mode;
}
-
void SystemTray::setMode(Mode mode)
{
if (mode != _mode) {
}
}
-
SystemTray::State SystemTray::state() const
{
return _state;
}
-
void SystemTray::setState(State state)
{
if (_state != state) {
}
}
-
QString SystemTray::iconName(State state) const
{
QString name;
return name;
}
-
QString SystemTray::currentIconName() const
{
if (state() == State::NeedsAttention) {
}
}
-
QString SystemTray::currentAttentionIconName() const
{
if (state() == State::NeedsAttention && _attentionBehavior == AttentionBehavior::Blink && !_blinkState) {
return iconName(State::NeedsAttention);
}
-
bool SystemTray::isAlerted() const
{
return state() == State::NeedsAttention;
}
-
void SystemTray::setAlert(bool alerted)
{
if (alerted) {
}
}
-
void SystemTray::onBlinkTimeout()
{
_blinkState = !_blinkState;
emit currentIconNameChanged();
}
-
-QMenu *SystemTray::trayMenu() const
+QMenu* SystemTray::trayMenu() const
{
return _trayMenu;
}
-
void SystemTray::trayMenuAboutToShow()
{
if (GraphicalUi::isMainWidgetVisible())
_minimizeRestoreAction->setText(tr("&Restore"));
}
-
-void SystemTray::enableChangeColorChanged(const QVariant &v)
+void SystemTray::enableChangeColorChanged(const QVariant& v)
{
if (v.toBool()) {
_attentionBehavior = AttentionBehavior::ChangeColor;
emit currentIconNameChanged();
}
-
-void SystemTray::enableBlinkChanged(const QVariant &v)
+void SystemTray::enableBlinkChanged(const QVariant& v)
{
if (v.toBool()) {
_attentionBehavior = AttentionBehavior::Blink;
emit currentIconNameChanged();
}
-
-void SystemTray::invertTrayIconChanged(const QVariant &v)
+void SystemTray::invertTrayIconChanged(const QVariant& v)
{
_trayIconInverted = v.toBool();
emit iconsChanged();
}
-
QString SystemTray::toolTipTitle() const
{
return _toolTipTitle;
}
-
QString SystemTray::toolTipSubTitle() const
{
return _toolTipSubTitle;
}
-
-void SystemTray::setToolTip(const QString &title, const QString &subtitle)
+void SystemTray::setToolTip(const QString& title, const QString& subtitle)
{
_toolTipTitle = title;
_toolTipSubTitle = subtitle;
emit toolTipChanged(title, subtitle);
}
-
-void SystemTray::showMessage(const QString &title, const QString &message, MessageIcon icon, int millisecondsTimeoutHint, uint id)
+void SystemTray::showMessage(const QString& title, const QString& message, MessageIcon icon, int millisecondsTimeoutHint, uint id)
{
Q_UNUSED(title)
Q_UNUSED(message)
Q_UNUSED(id)
}
-
void SystemTray::closeMessage(uint notificationId)
{
Q_UNUSED(notificationId)
}
-
void SystemTray::activate(SystemTray::ActivationReason reason)
{
emit activated(reason);
}
-
void SystemTray::minimizeRestore()
{
GraphicalUi::toggleMainWidget();
Q_ENUMS(State Mode MessageIcon ActivationReason)
public:
- enum State {
+ enum State
+ {
Passive,
Active,
NeedsAttention
};
- enum Mode {
+ enum Mode
+ {
Invalid,
Legacy,
StatusNotifier
};
// same as in QSystemTrayIcon
- enum MessageIcon {
+ enum MessageIcon
+ {
NoIcon,
Information,
Warning,
};
// same as in QSystemTrayIcon
- enum ActivationReason {
+ enum ActivationReason
+ {
Unknown,
Context,
DoubleClick,
MiddleClick
};
- enum class AttentionBehavior {
+ enum class AttentionBehavior
+ {
DoNothing,
ChangeColor,
Blink
};
- explicit SystemTray(QWidget *parent);
+ explicit SystemTray(QWidget* parent);
~SystemTray() override;
Mode mode() const;
virtual bool isSystemTrayAvailable() const;
- QWidget *associatedWidget() const;
+ QWidget* associatedWidget() const;
public slots:
void setVisible(bool visible = true);
void setState(State);
void setAlert(bool alerted);
- void setToolTip(const QString &title, const QString &subtitle);
- virtual void showMessage(const QString &title, const QString &message, MessageIcon icon = Information, int msTimeout = 10000, uint notificationId = 0);
+ void setToolTip(const QString& title, const QString& subtitle);
+ virtual void showMessage(
+ const QString& title, const QString& message, MessageIcon icon = Information, int msTimeout = 10000, uint notificationId = 0);
virtual void closeMessage(uint notificationId);
signals:
void visibilityChanged(bool isVisible);
void iconsChanged();
void currentIconNameChanged();
- void toolTipChanged(const QString &title, const QString &subtitle);
+ void toolTipChanged(const QString& title, const QString& subtitle);
void activated(SystemTray::ActivationReason);
void messageClicked(uint notificationId);
QString toolTipTitle() const;
QString toolTipSubTitle() const;
- QMenu *trayMenu() const;
+ QMenu* trayMenu() const;
QString iconName(State state) const;
QString currentIconName() const;
private slots:
void minimizeRestore();
void trayMenuAboutToShow();
- void invertTrayIconChanged(const QVariant &);
- void enableChangeColorChanged(const QVariant &);
- void enableBlinkChanged(const QVariant &);
+ void invertTrayIconChanged(const QVariant&);
+ void enableChangeColorChanged(const QVariant&);
+ void enableBlinkChanged(const QVariant&);
void onBlinkTimeout();
QString _toolTipTitle;
QString _toolTipSubTitle;
- QMenu *_trayMenu{nullptr};
- QWidget *_associatedWidget{nullptr};
- Action *_minimizeRestoreAction{nullptr};
+ QMenu* _trayMenu{nullptr};
+ QWidget* _associatedWidget{nullptr};
+ Action* _minimizeRestoreAction{nullptr};
};
#include "qtui.h"
#include "systemtray.h"
-SystrayAnimationNotificationBackend::SystrayAnimationNotificationBackend(QObject *parent)
+SystrayAnimationNotificationBackend::SystrayAnimationNotificationBackend(QObject* parent)
: AbstractNotificationBackend(parent)
{
NotificationSettings notificationSettings;
notificationSettings.initAndNotify("Systray/Alert", this, &SystrayAnimationNotificationBackend::alertChanged, true);
}
-
-void SystrayAnimationNotificationBackend::notify(const Notification &n)
+void SystrayAnimationNotificationBackend::notify(const Notification& n)
{
if (n.type != Highlight && n.type != PrivMsg)
return;
QtUi::mainWindow()->systemTray()->setAlert(true);
}
-
void SystrayAnimationNotificationBackend::close(uint notificationId)
{
Q_UNUSED(notificationId)
QtUi::mainWindow()->systemTray()->setAlert(false);
}
-
-void SystrayAnimationNotificationBackend::alertChanged(const QVariant &v)
+void SystrayAnimationNotificationBackend::alertChanged(const QVariant& v)
{
_alert = v.toBool();
}
-
-SettingsPage *SystrayAnimationNotificationBackend::createConfigWidget() const
+SettingsPage* SystrayAnimationNotificationBackend::createConfigWidget() const
{
return new ConfigWidget();
}
-
/***************************************************************************/
-SystrayAnimationNotificationBackend::ConfigWidget::ConfigWidget(QWidget *parent) : SettingsPage("Internal", "SystrayAnimation", parent)
+SystrayAnimationNotificationBackend::ConfigWidget::ConfigWidget(QWidget* parent)
+ : SettingsPage("Internal", "SystrayAnimation", parent)
{
ui.setupUi(this);
ui.enableAlert->setIcon(icon::get("dialog-information"));
initAutoWidgets();
}
-
QString SystrayAnimationNotificationBackend::ConfigWidget::settingsKey() const
{
return "Notification";
}
-
-QVariant SystrayAnimationNotificationBackend::ConfigWidget::loadAutoWidgetValue(const QString &widgetName)
+QVariant SystrayAnimationNotificationBackend::ConfigWidget::loadAutoWidgetValue(const QString& widgetName)
{
if (widgetName == "attentionBehavior") {
NotificationSettings s;
return SettingsPage::loadAutoWidgetValue(widgetName);
}
-
-void SystrayAnimationNotificationBackend::ConfigWidget::saveAutoWidgetValue(const QString &widgetName, const QVariant &value)
+void SystrayAnimationNotificationBackend::ConfigWidget::saveAutoWidgetValue(const QString& widgetName, const QVariant& value)
{
if (widgetName == "attentionBehavior") {
NotificationSettings s;
Q_OBJECT
public:
- SystrayAnimationNotificationBackend(QObject *parent = nullptr);
+ SystrayAnimationNotificationBackend(QObject* parent = nullptr);
- void notify(const Notification &) override;
+ void notify(const Notification&) override;
void close(uint notificationId) override;
- SettingsPage *createConfigWidget() const override;
+ SettingsPage* createConfigWidget() const override;
private slots:
- void alertChanged(const QVariant &);
+ void alertChanged(const QVariant&);
private:
bool _alert{false};
class ConfigWidget;
};
-
class SystrayAnimationNotificationBackend::ConfigWidget : public SettingsPage
{
Q_OBJECT
public:
- ConfigWidget(QWidget *parent = nullptr);
+ ConfigWidget(QWidget* parent = nullptr);
QString settingsKey() const override;
private:
- QVariant loadAutoWidgetValue(const QString &widgetName) override;
- void saveAutoWidgetValue(const QString &widgetName, const QVariant &value) override;
+ QVariant loadAutoWidgetValue(const QString& widgetName) override;
+ void saveAutoWidgetValue(const QString& widgetName, const QVariant& value) override;
private:
Ui::SystrayAnimationConfigWidget ui;
#include "qtui.h"
#include "systemtray.h"
-SystrayNotificationBackend::SystrayNotificationBackend(QObject *parent)
+SystrayNotificationBackend::SystrayNotificationBackend(QObject* parent)
: AbstractNotificationBackend(parent)
{
NotificationSettings notificationSettings;
notificationSettings.initAndNotify("Systray/ShowBubble", this, &SystrayNotificationBackend::showBubbleChanged, true);
- connect(QtUi::mainWindow()->systemTray(), &SystemTray::messageClicked,
- this, selectOverload<uint>(&SystrayNotificationBackend::onNotificationActivated));
- connect(QtUi::mainWindow()->systemTray(), &SystemTray::activated,
- this, selectOverload<SystemTray::ActivationReason>(&SystrayNotificationBackend::onNotificationActivated));
+ connect(QtUi::mainWindow()->systemTray(),
+ &SystemTray::messageClicked,
+ this,
+ selectOverload<uint>(&SystrayNotificationBackend::onNotificationActivated));
+ connect(QtUi::mainWindow()->systemTray(),
+ &SystemTray::activated,
+ this,
+ selectOverload<SystemTray::ActivationReason>(&SystrayNotificationBackend::onNotificationActivated));
QApplication::instance()->installEventFilter(this);
updateToolTip();
}
-
-void SystrayNotificationBackend::notify(const Notification &n)
+void SystrayNotificationBackend::notify(const Notification& n)
{
if (n.type != Highlight && n.type != PrivMsg)
return;
updateToolTip();
}
-
void SystrayNotificationBackend::close(uint notificationId)
{
QList<Notification>::iterator i = _notifications.begin();
updateToolTip();
}
-
void SystrayNotificationBackend::onNotificationActivated(uint notificationId)
{
if (!_blockActivation) {
emit activated(notificationId);
break;
}
- ++i;
+ ++i;
}
}
}
-
void SystrayNotificationBackend::onNotificationActivated(SystemTray::ActivationReason reason)
{
if (reason == SystemTray::Trigger) {
}
}
-
// moving the mouse or releasing the button means that we're not dealing with a double activation
-bool SystrayNotificationBackend::eventFilter(QObject *obj, QEvent *event)
+bool SystrayNotificationBackend::eventFilter(QObject* obj, QEvent* event)
{
if (event->type() == QEvent::MouseMove || event->type() == QEvent::MouseButtonRelease) {
_blockActivation = false;
return AbstractNotificationBackend::eventFilter(obj, event);
}
-
-void SystrayNotificationBackend::showBubbleChanged(const QVariant &v)
+void SystrayNotificationBackend::showBubbleChanged(const QVariant& v)
{
_showBubble = v.toBool();
}
-
void SystrayNotificationBackend::updateToolTip()
{
QtUi::mainWindow()->systemTray()->setToolTip("Quassel IRC",
- _notifications.count() ? tr("%n pending highlight(s)", "", _notifications.count()) : QString());
+ _notifications.count() ? tr("%n pending highlight(s)", "", _notifications.count())
+ : QString());
}
-
-SettingsPage *SystrayNotificationBackend::createConfigWidget() const
+SettingsPage* SystrayNotificationBackend::createConfigWidget() const
{
return new ConfigWidget();
}
-
/***************************************************************************/
-SystrayNotificationBackend::ConfigWidget::ConfigWidget(QWidget *parent) : SettingsPage("Internal", "SystrayNotification", parent)
+SystrayNotificationBackend::ConfigWidget::ConfigWidget(QWidget* parent)
+ : SettingsPage("Internal", "SystrayNotification", parent)
{
_showBubbleBox = new QCheckBox(tr("Show a message in a popup"));
_showBubbleBox->setIcon(icon::get("dialog-information"));
connect(_showBubbleBox, &QAbstractButton::toggled, this, &ConfigWidget::widgetChanged);
- auto *layout = new QHBoxLayout(this);
+ auto* layout = new QHBoxLayout(this);
layout->addWidget(_showBubbleBox);
}
-
void SystrayNotificationBackend::ConfigWidget::widgetChanged()
{
bool changed = (_showBubble != _showBubbleBox->isChecked());
setChangedState(changed);
}
-
bool SystrayNotificationBackend::ConfigWidget::hasDefaults() const
{
return true;
}
-
void SystrayNotificationBackend::ConfigWidget::defaults()
{
_showBubbleBox->setChecked(false);
widgetChanged();
}
-
void SystrayNotificationBackend::ConfigWidget::load()
{
NotificationSettings s;
setChangedState(false);
}
-
void SystrayNotificationBackend::ConfigWidget::save()
{
NotificationSettings s;
Q_OBJECT
public:
- SystrayNotificationBackend(QObject *parent = nullptr);
+ SystrayNotificationBackend(QObject* parent = nullptr);
- void notify(const Notification &) override;
+ void notify(const Notification&) override;
void close(uint notificationId) override;
- SettingsPage *createConfigWidget() const override;
+ SettingsPage* createConfigWidget() const override;
protected:
- bool eventFilter(QObject *obj, QEvent *event) override;
+ bool eventFilter(QObject* obj, QEvent* event) override;
private slots:
void onNotificationActivated(uint notificationId);
void onNotificationActivated(SystemTray::ActivationReason);
- void showBubbleChanged(const QVariant &);
+ void showBubbleChanged(const QVariant&);
void updateToolTip();
private:
bool _blockActivation{false};
};
-
class SystrayNotificationBackend::ConfigWidget : public SettingsPage
{
Q_OBJECT
public:
- ConfigWidget(QWidget *parent = nullptr);
+ ConfigWidget(QWidget* parent = nullptr);
void save() override;
void load() override;
bool hasDefaults() const override;
void widgetChanged();
private:
- QCheckBox *_showBubbleBox;
+ QCheckBox* _showBubbleBox;
bool _showBubble;
};
#include "mainwin.h"
#include "qtui.h"
-TaskbarNotificationBackend::TaskbarNotificationBackend(QObject *parent)
+TaskbarNotificationBackend::TaskbarNotificationBackend(QObject* parent)
: AbstractNotificationBackend(parent)
{
NotificationSettings notificationSettings;
notificationSettings.notify("Taskbar/Timeout", this, &TaskbarNotificationBackend::timeoutChanged);
}
-
-void TaskbarNotificationBackend::notify(const Notification ¬ification)
+void TaskbarNotificationBackend::notify(const Notification& notification)
{
if (_enabled && (notification.type == Highlight || notification.type == PrivMsg)) {
QApplication::alert(QtUi::mainWindow(), _timeout);
}
}
-
void TaskbarNotificationBackend::close(uint notificationId)
{
Q_UNUSED(notificationId);
}
-
-void TaskbarNotificationBackend::enabledChanged(const QVariant &v)
+void TaskbarNotificationBackend::enabledChanged(const QVariant& v)
{
_enabled = v.toBool();
}
-
-void TaskbarNotificationBackend::timeoutChanged(const QVariant &v)
+void TaskbarNotificationBackend::timeoutChanged(const QVariant& v)
{
_timeout = v.toInt();
}
-
-SettingsPage *TaskbarNotificationBackend::createConfigWidget() const
+SettingsPage* TaskbarNotificationBackend::createConfigWidget() const
{
return new ConfigWidget();
}
-
/***************************************************************************/
-TaskbarNotificationBackend::ConfigWidget::ConfigWidget(QWidget *parent) : SettingsPage("Internal", "TaskbarNotification", parent)
+TaskbarNotificationBackend::ConfigWidget::ConfigWidget(QWidget* parent)
+ : SettingsPage("Internal", "TaskbarNotification", parent)
{
- auto *layout = new QHBoxLayout(this);
+ auto* layout = new QHBoxLayout(this);
#ifdef Q_OS_MAC
layout->addWidget(enabledBox = new QCheckBox(tr("Activate dock entry, timeout:"), this));
#else
connect(timeoutBox, selectOverload<int>(&QSpinBox::valueChanged), this, &ConfigWidget::widgetChanged);
}
-
void TaskbarNotificationBackend::ConfigWidget::widgetChanged()
{
- bool changed = (enabled != enabledBox->isChecked() || timeout/1000 != timeoutBox->value());
- if (changed != hasChanged()) setChangedState(changed);
+ bool changed = (enabled != enabledBox->isChecked() || timeout / 1000 != timeoutBox->value());
+ if (changed != hasChanged())
+ setChangedState(changed);
}
-
bool TaskbarNotificationBackend::ConfigWidget::hasDefaults() const
{
return true;
}
-
void TaskbarNotificationBackend::ConfigWidget::defaults()
{
enabledBox->setChecked(true);
widgetChanged();
}
-
void TaskbarNotificationBackend::ConfigWidget::load()
{
NotificationSettings s;
timeout = s.value("Taskbar/Timeout", 0).toInt();
enabledBox->setChecked(enabled);
- timeoutBox->setValue(timeout/1000);
+ timeoutBox->setValue(timeout / 1000);
setChangedState(false);
}
-
void TaskbarNotificationBackend::ConfigWidget::save()
{
NotificationSettings s;
#define TASKBARNOTIFICATIONBACKEND_H_
#include "abstractnotificationbackend.h"
-
#include "settingspage.h"
class QCheckBox;
Q_OBJECT
public:
- TaskbarNotificationBackend(QObject *parent = nullptr);
+ TaskbarNotificationBackend(QObject* parent = nullptr);
- void notify(const Notification &) override;
+ void notify(const Notification&) override;
void close(uint notificationId) override;
- SettingsPage *createConfigWidget() const override;
+ SettingsPage* createConfigWidget() const override;
private slots:
- void enabledChanged(const QVariant &);
- void timeoutChanged(const QVariant &);
+ void enabledChanged(const QVariant&);
+ void timeoutChanged(const QVariant&);
private:
class ConfigWidget;
int _timeout;
};
-
class TaskbarNotificationBackend::ConfigWidget : public SettingsPage
{
Q_OBJECT
public:
- ConfigWidget(QWidget *parent = nullptr);
+ ConfigWidget(QWidget* parent = nullptr);
void save() override;
void load() override;
bool hasDefaults() const override;
void widgetChanged();
private:
- QCheckBox *enabledBox;
- QSpinBox *timeoutBox;
+ QCheckBox* enabledBox;
+ QSpinBox* timeoutBox;
bool enabled;
int timeout;
};
-
#endif
#include "client.h"
#include "mainwin.h"
-TitleSetter::TitleSetter(MainWin *parent)
- : AbstractItemView(parent),
- _mainWin(parent)
-{
-}
-
+TitleSetter::TitleSetter(MainWin* parent)
+ : AbstractItemView(parent)
+ , _mainWin(parent)
+{}
-void TitleSetter::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
+void TitleSetter::currentChanged(const QModelIndex& current, const QModelIndex& previous)
{
Q_UNUSED(previous);
changeWindowTitle(current.sibling(current.row(), 0));
}
-
-void TitleSetter::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
+void TitleSetter::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
QItemSelectionRange changedArea(topLeft, bottomRight);
QModelIndex currentTopicIndex = selectionModel()->currentIndex().sibling(selectionModel()->currentIndex().row(), 0);
changeWindowTitle(currentTopicIndex);
}
-
-void TitleSetter::changeWindowTitle(const QModelIndex &index)
+void TitleSetter::changeWindowTitle(const QModelIndex& index)
{
BufferId id = index.data(NetworkModel::BufferIdRole).value<BufferId>();
if (!id.isValid())
Q_OBJECT
public:
- TitleSetter(MainWin *parent);
+ TitleSetter(MainWin* parent);
protected slots:
- void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) override;
- void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) override;
+ void currentChanged(const QModelIndex& current, const QModelIndex& previous) override;
+ void dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight) override;
private:
- MainWin *_mainWin;
- void changeWindowTitle(const QModelIndex &index);
+ MainWin* _mainWin;
+ void changeWindowTitle(const QModelIndex& index);
};
-
#endif
#include "topicwidget.h"
#include "client.h"
+#include "graphicalui.h"
#include "icon.h"
#include "networkmodel.h"
#include "uisettings.h"
-#include "graphicalui.h"
#include "uistyle.h"
#include "util.h"
-TopicWidget::TopicWidget(QWidget *parent)
+TopicWidget::TopicWidget(QWidget* parent)
: AbstractItemView(parent)
{
ui.setupUi(this);
_readonly = false;
}
-
-void TopicWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
+void TopicWidget::currentChanged(const QModelIndex& current, const QModelIndex& previous)
{
Q_UNUSED(previous);
setTopic(current);
}
-
-void TopicWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
+void TopicWidget::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
QItemSelectionRange changedArea(topLeft, bottomRight);
QModelIndex currentTopicIndex = selectionModel()->currentIndex().sibling(selectionModel()->currentIndex().row(), 1);
setTopic(selectionModel()->currentIndex());
}
-void TopicWidget::setUseCustomFont(const QVariant &v)
+void TopicWidget::setUseCustomFont(const QVariant& v)
{
if (v.toBool()) {
UiStyleSettings fs("Fonts");
setCustomFont(QFont());
}
-
-void TopicWidget::setCustomFont(const QVariant &v)
+void TopicWidget::setCustomFont(const QVariant& v)
{
UiStyleSettings fs("Fonts");
if (!fs.value("UseCustomTopicWidgetFont", false).toBool())
setCustomFont(v.value<QFont>());
}
-
-void TopicWidget::setCustomFont(const QFont &f)
+void TopicWidget::setCustomFont(const QFont& f)
{
QFont font = f;
if (font.family().isEmpty())
ui.topicLabel->setCustomFont(font);
}
-
-void TopicWidget::setTopic(const QModelIndex &index)
+void TopicWidget::setTopic(const QModelIndex& index)
{
QString newtopic;
bool readonly = true;
BufferId id = index.data(NetworkModel::BufferIdRole).value<BufferId>();
if (id.isValid()) {
QModelIndex index0 = index.sibling(index.row(), 0);
- const Network *network = Client::network(Client::networkModel()->networkId(id));
+ const Network* network = Client::network(Client::networkModel()->networkId(id));
switch (Client::networkModel()->bufferType(id)) {
case BufferInfo::StatusBuffer:
if (network) {
newtopic = QString("%1 (%2) | %3 | %4")
- .arg(network->networkName().toHtmlEscaped())
- .arg(network->currentServer().toHtmlEscaped())
- .arg(tr("Users: %1").arg(network->ircUsers().count()))
- .arg(tr("Lag: %1 msecs").arg(network->latency()));
+ .arg(network->networkName().toHtmlEscaped())
+ .arg(network->currentServer().toHtmlEscaped())
+ .arg(tr("Users: %1").arg(network->ircUsers().count()))
+ .arg(tr("Lag: %1 msecs").arg(network->latency()));
}
else {
newtopic = index0.data(Qt::DisplayRole).toString();
readonly = false;
break;
- case BufferInfo::QueryBuffer:
- {
+ case BufferInfo::QueryBuffer: {
QString nickname = index0.data(Qt::DisplayRole).toString();
if (network) {
- const IrcUser *user = network->ircUser(nickname);
+ const IrcUser* user = network->ircUser(nickname);
if (user) {
- newtopic = QString("%1%2%3 | %4@%5").arg(nickname)
- .arg(user->userModes().isEmpty() ? QString() : QString(" (+%1)").arg(user->userModes()))
- .arg(user->realName().isEmpty() ? QString() : QString(" | %1").arg(user->realName()))
- .arg(user->user())
- .arg(user->host());
+ newtopic = QString("%1%2%3 | %4@%5")
+ .arg(nickname)
+ .arg(user->userModes().isEmpty() ? QString() : QString(" (+%1)").arg(user->userModes()))
+ .arg(user->realName().isEmpty() ? QString() : QString(" | %1").arg(user->realName()))
+ .arg(user->user())
+ .arg(user->host());
}
- else { // no such user
+ else { // no such user
newtopic = nickname;
}
}
- else { // no valid Network-Obj.
+ else { // no valid Network-Obj.
newtopic = nickname;
}
break;
switchPlain();
}
-
-void TopicWidget::setReadOnly(const bool &readonly)
+void TopicWidget::setReadOnly(const bool& readonly)
{
if (_readonly == readonly)
return;
_readonly = readonly;
}
-
void TopicWidget::updateResizeMode()
{
StyledLabel::ResizeMode mode = StyledLabel::NoResize;
ui.topicLabel->setResizeMode(mode);
}
-
-void TopicWidget::clickableActivated(const Clickable &click)
+void TopicWidget::clickableActivated(const Clickable& click)
{
NetworkId networkId = selectionModel()->currentIndex().data(NetworkModel::NetworkIdRole).value<NetworkId>();
- UiStyle::StyledString sstr = GraphicalUi::uiStyle()->styleString(GraphicalUi::uiStyle()->mircToInternal(_topic), UiStyle::FormatType::PlainMsg);
+ UiStyle::StyledString sstr = GraphicalUi::uiStyle()->styleString(GraphicalUi::uiStyle()->mircToInternal(_topic),
+ UiStyle::FormatType::PlainMsg);
click.activate(networkId, sstr.plainText);
}
-
void TopicWidget::on_topicLineEdit_textEntered()
{
QModelIndex currentIdx = currentIndex();
switchPlain();
}
-
void TopicWidget::on_topicEditButton_clicked()
{
switchEditable();
}
-
void TopicWidget::switchEditable()
{
ui.stackedWidget->setCurrentIndex(1);
updateGeometry();
}
-
void TopicWidget::switchPlain()
{
ui.stackedWidget->setCurrentIndex(0);
emit switchedPlain();
}
-
// filter for the input widget to switch back to normal mode
-bool TopicWidget::eventFilter(QObject *obj, QEvent *event)
+bool TopicWidget::eventFilter(QObject* obj, QEvent* event)
{
if (event->type() == QEvent::FocusOut && !_mouseEntered) {
switchPlain();
if (event->type() != QEvent::KeyRelease)
return QObject::eventFilter(obj, event);
- auto *keyEvent = static_cast<QKeyEvent *>(event);
+ auto* keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == Qt::Key_Escape) {
switchPlain();
Q_OBJECT
public:
- TopicWidget(QWidget *parent = nullptr);
+ TopicWidget(QWidget* parent = nullptr);
- void setTopic(const QModelIndex &index);
- void setCustomFont(const QFont &);
- void setReadOnly(const bool &readonly);
+ void setTopic(const QModelIndex& index);
+ void setCustomFont(const QFont&);
+ void setReadOnly(const bool& readonly);
- bool eventFilter(QObject *obj, QEvent *event) override;
+ bool eventFilter(QObject* obj, QEvent* event) override;
inline bool isReadOnly() const { return _readonly; }
signals:
void switchedPlain();
protected slots:
- void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) override;
- void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) override;
+ void currentChanged(const QModelIndex& current, const QModelIndex& previous) override;
+ void dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight) override;
private slots:
void on_topicLineEdit_textEntered();
void on_topicEditButton_clicked();
void switchEditable();
void switchPlain();
- void clickableActivated(const Clickable &);
+ void clickableActivated(const Clickable&);
void updateResizeMode();
- void setCustomFont(const QVariant &);
- void setUseCustomFont(const QVariant &);
+ void setCustomFont(const QVariant&);
+ void setUseCustomFont(const QVariant&);
private:
QString sanitizeTopic(const QString& topic);
bool _readonly;
};
-
#endif
#include "verticaldock.h"
-#include <qdrawutil.h>
+#include <QDebug>
#include <QLayout>
#include <QPainter>
+#include <qdrawutil.h>
-#include <QDebug>
-
-VerticalDockTitle::VerticalDockTitle(QDockWidget *parent)
+VerticalDockTitle::VerticalDockTitle(QDockWidget* parent)
: QWidget(parent)
-{
-}
-
+{}
QSize VerticalDockTitle::sizeHint() const
{
return {8, 15};
}
-
QSize VerticalDockTitle::minimumSizeHint() const
{
return {8, 10};
}
-
-void VerticalDockTitle::paintEvent(QPaintEvent *event)
+void VerticalDockTitle::paintEvent(QPaintEvent* event)
{
Q_UNUSED(event);
if (rect().isValid() && rect().height() > minimumSizeHint().height()) {
for (int i = 0; i < 2; i++) {
- QPoint topLeft = rect().topLeft() + QPoint(3 + i*2, 2);
- QPoint bottomRight = rect().topLeft() + QPoint(3 + i*2, rect().height() - 2);
+ QPoint topLeft = rect().topLeft() + QPoint(3 + i * 2, 2);
+ QPoint bottomRight = rect().topLeft() + QPoint(3 + i * 2, rect().height() - 2);
qDrawShadeLine(&painter, topLeft, bottomRight, palette());
}
}
}
-
// ==============================
// Vertical Dock
// ==============================
-VerticalDock::VerticalDock(const QString &title, QWidget *parent, Qt::WindowFlags flags)
+VerticalDock::VerticalDock(const QString& title, QWidget* parent, Qt::WindowFlags flags)
: QDockWidget(title, parent, flags)
{
setDefaultTitleWidget();
}
-
-VerticalDock::VerticalDock(QWidget *parent, Qt::WindowFlags flags)
+VerticalDock::VerticalDock(QWidget* parent, Qt::WindowFlags flags)
: QDockWidget(parent, flags)
{
setDefaultTitleWidget();
setContentsMargins(0, 0, 0, 0);
}
-
void VerticalDock::setDefaultTitleWidget()
{
- QWidget *oldDockTitle = titleBarWidget();
- QWidget *newDockTitle = new VerticalDockTitle(this);
+ QWidget* oldDockTitle = titleBarWidget();
+ QWidget* newDockTitle = new VerticalDockTitle(this);
setAllowedAreas(Qt::TopDockWidgetArea | Qt::BottomDockWidgetArea);
setFeatures(features() | QDockWidget::DockWidgetVerticalTitleBar);
oldDockTitle->deleteLater();
}
-
void VerticalDock::showTitle(bool show)
{
- QWidget *oldDockTitle = titleBarWidget();
- QWidget *newDockTitle = nullptr;
+ QWidget* oldDockTitle = titleBarWidget();
+ QWidget* newDockTitle = nullptr;
if (show)
newDockTitle = new VerticalDockTitle(this);
Q_OBJECT
public:
- VerticalDockTitle(QDockWidget *parent);
+ VerticalDockTitle(QDockWidget* parent);
QSize sizeHint() const override;
QSize minimumSizeHint() const override;
void show(bool show_);
protected:
- void paintEvent(QPaintEvent *event) override;
+ void paintEvent(QPaintEvent* event) override;
private:
bool _show;
};
-
class EmptyDockTitle : public QWidget
{
Q_OBJECT
public:
- inline EmptyDockTitle(QDockWidget *parent) : QWidget(parent) {}
+ inline EmptyDockTitle(QDockWidget* parent)
+ : QWidget(parent)
+ {}
inline QSize sizeHint() const override { return {0, 0}; }
};
-
class VerticalDock : public QDockWidget
{
Q_OBJECT
public:
- VerticalDock(const QString &title, QWidget *parent = nullptr, Qt::WindowFlags flags = nullptr);
- VerticalDock(QWidget *parent = nullptr, Qt::WindowFlags flags = nullptr);
+ VerticalDock(const QString& title, QWidget* parent = nullptr, Qt::WindowFlags flags = nullptr);
+ VerticalDock(QWidget* parent = nullptr, Qt::WindowFlags flags = nullptr);
void showTitle(bool show);
void setDefaultTitleWidget();
};
-
-#endif // VERTICALDOCKTITLE_H
+#endif // VERTICALDOCKTITLE_H
#include "webpreviewitem.h"
#ifdef HAVE_WEBENGINE
-#include <QWebEngineView>
-#include <QWebEngineSettings>
+# include <QWebEngineSettings>
+# include <QWebEngineView>
#elif defined HAVE_WEBKIT
-#include <QWebView>
-#include <QWebSettings>
+# include <QWebSettings>
+# include <QWebView>
#endif
#if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
-#include <QGraphicsProxyWidget>
-#include <QPainter>
+# include <QGraphicsProxyWidget>
+# include <QPainter>
-
-#ifdef HAVE_WEBENGINE
+# ifdef HAVE_WEBENGINE
// QGraphicsProxyWidget does not stay synced with QWebEngineView, therefore we modify QWebEngineView
// and manually trigger an update of the proxyItem on UpdateRequest Event. See: http://stackoverflow.com/a/30920209
// and http://lists.qt-project.org/pipermail/development/2016-March/025280.html (At least in Qt5.6)
-class CustomWebView : public QWebEngineView {
-
+class CustomWebView : public QWebEngineView
+{
private:
- QGraphicsProxyWidget *proxyItem;
+ QGraphicsProxyWidget* proxyItem;
+
public:
- CustomWebView(QGraphicsProxyWidget *pItem) {
- proxyItem = pItem;
- }
- bool event(QEvent *event) override {
- if (event->type() == QEvent::UpdateRequest)
- {
+ CustomWebView(QGraphicsProxyWidget* pItem) { proxyItem = pItem; }
+ bool event(QEvent* event) override
+ {
+ if (event->type() == QEvent::UpdateRequest) {
proxyItem->update();
}
return QWebEngineView::event(event);
}
};
-#endif
+# endif
-WebPreviewItem::WebPreviewItem(const QUrl &url)
- : QGraphicsItem(nullptr), // needs to be a top level item as we otherwise cannot guarantee that it's on top of other chatlines
+WebPreviewItem::WebPreviewItem(const QUrl& url)
+ : QGraphicsItem(nullptr)
+ , // needs to be a top level item as we otherwise cannot guarantee that it's on top of other chatlines
_boundingRect(0, 0, 400, 300)
{
qreal frameWidth = 5;
- QGraphicsProxyWidget *proxyItem = new QGraphicsProxyWidget(this);
-#ifdef HAVE_WEBENGINE
- QWebEngineView *webView = new CustomWebView(proxyItem);
+ QGraphicsProxyWidget* proxyItem = new QGraphicsProxyWidget(this);
+# ifdef HAVE_WEBENGINE
+ QWebEngineView* webView = new CustomWebView(proxyItem);
webView->settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, false);
-#elif defined HAVE_WEBKIT
- QWebView *webView = new QWebView;
+# elif defined HAVE_WEBKIT
+ QWebView* webView = new QWebView;
webView->settings()->setAttribute(QWebSettings::JavascriptEnabled, false);
-#endif
+# endif
webView->load(url);
webView->setDisabled(true);
webView->resize(1000, 750);
setZValue(30);
}
-
-void WebPreviewItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
+void WebPreviewItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)
{
- Q_UNUSED(option); Q_UNUSED(widget);
+ Q_UNUSED(option);
+ Q_UNUSED(widget);
painter->setClipRect(boundingRect());
painter->setPen(QPen(Qt::black, 5));
painter->setBrush(Qt::black);
painter->drawRoundedRect(boundingRect(), 10, 10);
}
-
-#endif //#ifdef HAVE_WEBKIT || HAVE_WEBENGINE
+#endif //#ifdef HAVE_WEBKIT || HAVE_WEBENGINE
#if defined HAVE_WEBKIT || defined HAVE_WEBENGINE
-#include <QGraphicsItem>
+# include <QGraphicsItem>
class WebPreviewItem : public QGraphicsItem
{
public:
- WebPreviewItem(const QUrl &url);
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override;
+ WebPreviewItem(const QUrl& url);
+ void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override;
inline QRectF boundingRect() const override { return _boundingRect; }
private:
QRectF _boundingRect;
};
+#endif //#ifdef HAVE_WEBKIT || HAVE_WEBENGINE
-#endif //#ifdef HAVE_WEBKIT || HAVE_WEBENGINE
-
-#endif //WEBPREVIEWITEM_H
+#endif // WEBPREVIEWITEM_H
#include "test-main-export.h"
-#include <gmock/gmock.h>
-
#include <QCoreApplication>
-TEST_MAIN_EXPORT int main(int argc, char **argv)
+#include <gmock/gmock.h>
+
+TEST_MAIN_EXPORT int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
QCoreApplication app(argc, argv);
#pragma once
-#include <gmock/gmock.h>
-
#include "test-main-export.h"
+
+#include <gmock/gmock.h>
#include "aboutdata.h"
-#include <QImage>
#include <utility>
-#include "quassel.h"
+#include <QImage>
+#include "quassel.h"
AboutPerson::AboutPerson(QString name, QString nick, QString task, QString emailAddress, QLocale::Language translatedLanguage)
: _name(std::move(name))
, _task(std::move(task))
, _emailAddress(std::move(emailAddress))
, _language(translatedLanguage)
-{
-
-}
-
+{}
QString AboutPerson::name() const
{
return _name;
}
-
QString AboutPerson::nick() const
{
return _nick;
}
-
QString AboutPerson::task() const
{
return _task;
}
-
QString AboutPerson::emailAddress() const
{
return _emailAddress;
}
-
QLocale::Language AboutPerson::translatedLanguage() const
{
return _language;
}
-
QString AboutPerson::prettyName() const
{
if (!name().isEmpty() && !nick().isEmpty())
return name();
}
-
/**************************************************************************************************/
-
-AboutData::AboutData(QObject *parent)
+AboutData::AboutData(QObject* parent)
: QObject(parent)
-{
-
-}
-
+{}
QList<AboutPerson> AboutData::authors() const
{
return _authors;
}
-
QList<AboutPerson> AboutData::credits() const
{
return _credits;
}
-
-AboutData &AboutData::addAuthor(const AboutPerson &author)
+AboutData& AboutData::addAuthor(const AboutPerson& author)
{
_authors.append(author);
return *this;
}
-
-AboutData &AboutData::addAuthors(std::initializer_list<AboutPerson> authors)
+AboutData& AboutData::addAuthors(std::initializer_list<AboutPerson> authors)
{
_authors.append(authors);
return *this;
}
-
-AboutData &AboutData::addCredit(const AboutPerson &credit)
+AboutData& AboutData::addCredit(const AboutPerson& credit)
{
_credits.append(credit);
return *this;
}
-
-AboutData &AboutData::addCredits(std::initializer_list<AboutPerson> credits)
+AboutData& AboutData::addCredits(std::initializer_list<AboutPerson> credits)
{
_credits.append(credits);
return *this;
KAboutData AboutData::kAboutData() const
{
- KAboutData aboutData(
- Quassel::buildInfo().applicationName,
- tr("Quassel IRC"),
- Quassel::buildInfo().plainVersionString
- );
+ KAboutData aboutData(Quassel::buildInfo().applicationName, tr("Quassel IRC"), Quassel::buildInfo().plainVersionString);
aboutData.addLicense(KAboutLicense::GPL_V2);
aboutData.addLicense(KAboutLicense::GPL_V3);
aboutData.setShortDescription(tr("A modern, distributed IRC client"));
aboutData.setBugAddress("https://bugs.quassel-irc.org/projects/quassel-irc/issues/new");
aboutData.setOrganizationDomain(Quassel::buildInfo().organizationDomain.toUtf8());
- for (const auto &person : authors()) {
+ for (const auto& person : authors()) {
aboutData.addAuthor(person.prettyName(), person.task(), person.emailAddress());
}
- for (const auto &person : credits()) {
+ for (const auto& person : credits()) {
aboutData.addCredit(person.prettyName(), person.task(), person.emailAddress());
}
#endif
-
/**************************************************************************************************/
/*
* do want to credit everyone who has contributed to Quassel development.
*/
-void AboutData::setQuasselPersons(AboutData *aboutData)
+void AboutData::setQuasselPersons(AboutData* aboutData)
{
aboutData->addAuthors({
- { "Manuel Nickschas", "Sputnick", tr("Project founder, lead developer"), "sputnick@quassel-irc.org" },
- { "Marcus Eggenberger", "EgS", tr("Project motivator, lead developer"), "egs@quassel-irc.org" },
- { "Alexander von Renteln", "phon", tr("Former lead developer"), "phon@quassel-irc.org" },
- { "Daniel Albers", "al", tr("Master of Translation, many fixes and enhancements, Travis support") },
- { "Sebastian Goth", "seezer", tr("Many features, fixes and improvements") },
- { "Bas Pape", "Tucos", tr("Many fixes and improvements, bug and patch triaging, community support") },
- { "Shane Synan", "digitalcircuit", tr("IRCv3 support, documentation, many other improvements, testing, outstanding PRs") },
- { "Janne Koschinski", "justJanne", tr("Quasseldroid, architecture, (mobile) performance, many other improvements and fixes, testing") },
+ {"Manuel Nickschas", "Sputnick", tr("Project founder, lead developer"), "sputnick@quassel-irc.org"},
+ {"Marcus Eggenberger", "EgS", tr("Project motivator, lead developer"), "egs@quassel-irc.org"},
+ {"Alexander von Renteln", "phon", tr("Former lead developer"), "phon@quassel-irc.org"},
+ {"Daniel Albers", "al", tr("Master of Translation, many fixes and enhancements, Travis support")},
+ {"Sebastian Goth", "seezer", tr("Many features, fixes and improvements")},
+ {"Bas Pape", "Tucos", tr("Many fixes and improvements, bug and patch triaging, community support")},
+ {"Shane Synan", "digitalcircuit", tr("IRCv3 support, documentation, many other improvements, testing, outstanding PRs")},
+ {"Janne Koschinski", "justJanne", tr("Quasseldroid, architecture, (mobile) performance, many other improvements and fixes, testing")},
});
- aboutData->addCredits({
- { "A. V. Lukyanov", "", tr("OSX UI improvements") },
- { "Adam Harwood", "2kah", tr("Chatview improvements") },
- { "Adam Tulinius", "adamt", tr("Early beta tester and bughunter, Danish translation"), "", QLocale::Danish },
- { "Adolfo Jayme Barrientos", "", tr("Spanish translation"), "", QLocale::Spanish },
- { "Adriaan de Groot", "", tr("Build system fixes") },
- { "Alex Ingram", "", tr("Database performance improvements") },
- { "Alexander Stein", "", tr("Tray icon fix") },
- { "Alf Gaida", "agaida", tr("Language improvements") },
- { "Allan Jude", "", tr("Documentation improvements") },
- { "André Marcelo Alvarenga", "", tr("Brazilian translation"), "", QLocale::Portuguese },
- { "Andrej Mernik", "", tr("Slovenian translation"), "", QLocale::Slovenian },
- { "Andrew Brown", "", tr("Fixes") },
- { "Arthur Țițeică", "roentgen", tr("Romanian translation"), "", QLocale::Romanian },
- { "A S Alam", "", tr("Punjabi translation"), "", QLocale::Punjabi },
- { "Atte Virtanen", "", tr("Finnish translation"), "", QLocale::Finnish },
- { "Aurélien Gâteau", "agateau", tr("Message indicator support") },
- { "Awad Mackie", "firesock", tr("Chatview improvements") },
- { "Armin K", "", tr("Build system fix") },
- { "", "Ayonix", tr("Build system fix") },
- { "Benjamin Zeller", "zbenjamin", tr("Windows build system fixes") },
- { "Ben Rosser", "", tr("AppData metadata, LDAP support") },
- { "Bernhard Scheirle", "", tr("Nicer tooltips, spell check and other improvements") },
- { "Bruno Brigras", "", tr("Crash fixes") },
- { "Bruno Patri", "", tr("French translation"), "", QLocale::French },
- { "Cédric Valmary", "", tr("Occitan translation"), "", QLocale::Occitan },
- { "Celeste Paul", "seele", tr("Usability review") },
- { "Chris Fuenty", "stitch", tr("SASL support") },
- { "Chris Holland", "Shade / Zren", tr("Various improvements") },
- { "Chris Le Sueur", "Fish-Face", tr("Various fixes and improvements") },
- { "Chris Moeller", "kode54", tr("Various fixes and improvements") },
- { "Christian Schwarz", "", tr("Settings fixes") },
- { "", "Condex", tr("Galician translation"), "", QLocale::Galician },
- { "", "cordata", tr("Esperanto translation"), "", QLocale::Esperanto },
- { "Daniel E. Moctezuma", "", tr("Japanese translation"), "", QLocale::Japanese },
- { "Daniel Meltzer", "hydrogen", tr("Various fixes and improvements") },
- { "Daniel Pielmeier", "billie", tr("Gentoo maintainer") },
- { "Daniel Schaal", "", tr("Certificate handling improvements") },
- { "Daniel Silverstone", "", tr("Fixes") },
- { "Daniel Steinmetz", "son", tr("Early beta tester and bughunter (on Vista™!)") },
- { "David Planella", "", tr("Translation system fixes") },
- { "David Roden", "Bombe", tr("Fixes") },
- { "David Sansome", "", tr("OSX Notification Center support") },
- { "Demiray Muhterem", "", tr("Turkish translation"), "", QLocale::Turkish },
- { "Deniz Türkoglu", "", tr("Mac fixes") },
- { "Dennis Schridde", "devurandom", tr("D-Bus notifications") },
- { "", "derpella", tr("Polish translation"), "", QLocale::Polish },
- { "Diego Pettenò", "Flameeyes", tr("Build system improvements") },
- { "Dirk Rettschlag", "MarcLandis", tr("Formatting support and other input line improvements, many other fixes") },
- { "", "Dorian", tr("French translation"), "", QLocale::French },
- { "Drew Patridge", "LinuxDolt", tr("BluesTheme stylesheet") },
- { "Edward Hades", "", tr("Russian translation"), "", QLocale::Russian },
- { "Fabiano Francesconi", "elbryan", tr("Italian translation"), "", QLocale::Italian },
- { "Felix Geyer", "debfx", tr("Certificate handling improvements") },
- { "Felix Kaechele", "", tr("German translation"), "", QLocale::German },
- { "Florent Castelli", "", tr("Sanitize topic handling, twitch.tv support") },
- { "Frederik M.J. Vestre", "freqmod", tr("Norwegian translation"), "", QLocale::Norwegian },
- { "Gábor Németh", "ELITE_x", tr("Hungarian translation"), "", QLocale::Hungarian },
- { "Gryllida A", "gry", tr("IRC parser improvements") },
- { "György Balló", "", tr("Fixes") },
- { "H. İbrahim Güngör", "igungor", tr("Turkish translation"), "", QLocale::Turkish },
- { "Hannah von Reth", "TheOneRing", tr("Windows build support and Appveyor maintenance, snorenotify backend") },
- { "Harald Fernengel", "harryF", tr("Initial Qt5 support") },
- { "Harald Sitter", "apachelogger", tr("{Ku|U}buntu packager, motivator, promoter") },
- { "Hendrik Leppkes", "nevcairiel", tr("Various features and improvements") },
- { "Henning Rohlfs", "honk", tr("Various fixes") },
- { "J-P Nurmi", "", tr("Various fixes") },
- { "Jaak Ristioja", "", tr("Bugfixes") },
- { "Jan Alexander Steffens", "heftig", tr("Fixes") },
- { "Jaroslav Lichtblau", "", tr("Czech translation"), "", QLocale::Czech },
- { "Jason Joyce", "", tr("Python improvements") },
- { "Jason Lynch", "", tr("Bugfixes") },
- { "Javier Llorente", "", tr("Proxy improvements, Spanish translation"), "", QLocale::Spanish },
- { "Jens Arnold", "amiconn", tr("Postgres migration fixes") },
- { "Jens True", "", tr("Danish translation"), "", QLocale::Danish },
- { "Jerome Leclanche", "Adys", tr("Context menu fixes") },
- { "Jesper Thomschütz", "", tr("Various fixes") },
- { "Jiri Grönroos", "", tr("Finnish translation"), "", QLocale::Finnish },
- { "Joe Hansen", "", tr("Danish translation"), "", QLocale::Danish },
- { "Johannes Huber", "johu", tr("Many fixes and improvements, bug triaging") },
- { "John Hand", "nox", tr("Original \"All-Seeing Eye\" logo") },
- { "Jonas Heese", "Dante", tr("Project founder, various improvements") },
- { "Jonathan Farnham", "", tr("Spanish translation"), "", QLocale::Spanish },
- { "Joshua T Corbin", "tvakah", tr("Various fixes") },
- { "Jovan Jojkić", "", tr("Serbian translation"), "", QLocale::Serbian },
- { "Jure Repinc", "JLP", tr("Slovenian translation"), "", QLocale::Slovenian },
- { "Jussi Schultink", "jussi01", tr("Tireless tester, {Ku|U}buntu tester and lobbyist, liters of delicious Finnish alcohol") },
- { "K. Ernest Lee", "iFire", tr("Qt5 porting help, Travis CI setup") },
- { "Kevin Funk", "KRF", tr("German translation"), "", QLocale::German },
- { "Kimmo Huoman", "kipe", tr("Buffer merge improvements") },
- { "Konstantin Bläsi", "", tr("Fixes") },
- { "Kostas Koudaras", "", tr("Greek translation"), "", QLocale::Greek },
- { "", "Larso", tr("Finnish translation"), "", QLocale::Finnish },
- { "Lasse Liehu", "", tr("Finnish translation"), "", QLocale::Finnish },
- { "Leo Franchi", "", tr("OSX improvements") },
- { "Liudas Alisauskas", "", tr("Lithuanian translation"), "", QLocale::Lithuanian },
- { "Luke Faraone", "", tr("Documentation fixes") },
- { "Maia Kozheva", "", tr("Russian translation"), "", QLocale::Russian },
- { "Manuel Hoffmann", "contradictioned", tr("German translation"), "", QLocale::German },
- { "Marcin Jabrzyk", "", tr("Improvements") },
- { "Marco Genise", "kaffeedoktor", tr("Ideas, hacking, initial motivation") },
- { "Marco Paolone", "Quizzlo", tr("Italian translation"), "", QLocale::Italian },
- { "Martin Mayer", "m4yer", tr("German translation"), "", QLocale::German },
- { "Martin Sandsmark", "sandsmark", tr("Many fixes and improvements, Sonnet support, QuasselDroid") },
- { "Matt Schatz", "genius3000", tr("Various fixes") },
- { "Matthias Coy", "pennywise", tr("German translation"), "", QLocale::German },
- { "Mattia Basaglia", "", tr("Fixes") },
- { "Michael Groh", "brot", tr("German translation, fixes"), "", QLocale::German },
- { "Michael Kedzierski", "ycros", tr("Mac fixes") },
- { "Michael Marley", "mamarley", tr("Many fixes and improvements; Ubuntu PPAs") },
- { "Miguel Anxo Bouzada", "", tr("Galician translation"), "", QLocale::Galician },
- { "Miguel Revilla", "", tr("Spanish translation"), "", QLocale::Spanish },
- { "Nuno Pinheiro", "", tr("Tons of Oxygen icons including the Quassel logo") },
- { "Patrick Lauer", "bonsaikitten", tr("Gentoo maintainer") },
- { "Paul Klumpp", "Haudrauf", tr("Initial design and main window layout") },
- { "Pavel Volkovitskiy", "int", tr("Early beta tester and bughunter") },
- { "Pedro Araujo", "", tr("Brazilian translation"), "", QLocale::Portuguese },
- { "Per Nielsen", "", tr("Danish translation"), "", QLocale::Danish },
- { "Pete Beardmore", "elbeardmorez", tr("Linewrap for input line") },
- { "Petr Bena", "", tr("Performance improvements and cleanups") },
- { "", "phuzion", tr("Various fixes") },
- { "Pierre-Hugues Husson", "", tr("/print command") },
- { "Pierre Schweitzer", "", tr("Performance improvements") },
- { "Rafael Belmonte", "EagleScreen", tr("Spanish translation"), "", QLocale::Spanish },
- { "Raju Devidas Vindane", "", tr("Hindi and Marathi translations"), "", QLocale::Hindi },
- { "Ramanathan Sivagurunathan", "", tr("Bugfixes") },
- { "Raul Salinas-Monteagudo", "", tr("Fixes") },
- { "Regis Perrin", "ZRegis", tr("French translation"), "", QLocale::French },
- { "Rolf Eike Beer", "DerDakon", tr("Build system improvements") },
- { "Rolf Michael Bislin", "romibi", tr("Windows build support, automated OSX builds in Travis, various improvements") },
- { "Roscoe van Wyk", "", tr("Bugfixes") },
- { "Rüdiger Sonderfeld", "ruediger", tr("Emacs keybindings") },
- { "Ryan Bales", "selabnayr", tr("Improvements") },
- { "Sai Nane", "esainane", tr("Various fixes") },
- { "", "salnx", tr("Highlight configuration improvements") },
- { "Scott Kitterman", "ScottK", tr("Debian/Kubuntu packager, (packaging/build system) bughunter") },
- { "Sebastian Meyer", "", tr("Bugfixes, German translation"), "", QLocale::German },
- { "Sebastien Fricker", "", tr("Audio backend improvements") },
- { "Sergiu Bivol", "", tr("Romanian translation"), "", QLocale::Romanian },
- { "", "sfionov", tr("Russian translation"), "", QLocale::Russian },
- { "Shengjing Zhu", "", tr("Chinese translation"), "", QLocale::Chinese },
- { "Simon Philips", "", tr("Dutch translation"), "", QLocale::Dutch },
- { "Sjors Gielen", "dazjorz", tr("Bugfixes") },
- { "Stefanos Sofroniou", "", tr("Greek translation"), "", QLocale::Greek },
- { "Stella Rouzi", "differentreality", tr("Greek translation"), "", QLocale::Greek },
- { "Sungjin Kang", "", tr("Korean translation"), "", QLocale::Korean },
- { "Sven Anderson", "", tr("Database performance improvements") },
- { "Svetlana Tkachenko", "gry", tr("Alias improvements") },
- { "Tae-Hoon Kwon", "", tr("Korean translation"), "", QLocale::Korean },
- { "Terje Andersen", "tan", tr("Norwegian translation, documentation") },
- { "Theo Chatzimichos", "tampakrap", tr("Greek translation"), "", QLocale::Greek },
- { "Theofilos Intzoglou", "", tr("Greek translation"), "", QLocale::Greek },
- { "Thomas Hogh", "Datafreak", tr("Former Windows builder") },
- { "Thomas Müller", "", tr("Fixes, Debian packaging") },
- { "Tim Schumacher", "xAFFE", tr("Fixes and feedback") },
- { "Tinjo Kohen", "", tr("Esperanto translation"), "", QLocale::Esperanto },
- { "Tobias Frei", "ToBeFree", tr("German translation"), "", QLocale::German },
- { "Tomáš Chvátal", "scarabeus", tr("Czech translation"), "", QLocale::Czech },
- { "Veeti Paananen", "", tr("Certificate handling improvements") },
- { "Viktor Suprun", "", tr("Russian translation"), "", QLocale::Russian },
- { "Vít Pelčák", "", tr("Czech translation"), "", QLocale::Czech },
- { "Volkan Gezer", "", tr("Turkish translation"), "", QLocale::Turkish },
- { "Weng Xuetian", "wengxt", tr("Build system fix") },
- { "Willem Jan Palenstijn", "", tr("Fixes") },
- { "Yaohan Chen", "hagabaka", tr("Network detection improvements") },
- { "Yuri Chornoivan", "", tr("Ukrainian translation"), "", QLocale::Ukrainian },
- { "Zé", "", tr("Portuguese translation"), "", QLocale::Portuguese },
- { "", "zeugma", tr("Turkish translation"), "", QLocale::Turkish }
- });
+ aboutData->addCredits(
+ {{"A. V. Lukyanov", "", tr("OSX UI improvements")},
+ {"Adam Harwood", "2kah", tr("Chatview improvements")},
+ {"Adam Tulinius", "adamt", tr("Early beta tester and bughunter, Danish translation"), "", QLocale::Danish},
+ {"Adolfo Jayme Barrientos", "", tr("Spanish translation"), "", QLocale::Spanish},
+ {"Adriaan de Groot", "", tr("Build system fixes")},
+ {"Alex Ingram", "", tr("Database performance improvements")},
+ {"Alexander Stein", "", tr("Tray icon fix")},
+ {"Alf Gaida", "agaida", tr("Language improvements")},
+ {"Allan Jude", "", tr("Documentation improvements")},
+ {"André Marcelo Alvarenga", "", tr("Brazilian translation"), "", QLocale::Portuguese},
+ {"Andrej Mernik", "", tr("Slovenian translation"), "", QLocale::Slovenian},
+ {"Andrew Brown", "", tr("Fixes")},
+ {"Arthur Țițeică", "roentgen", tr("Romanian translation"), "", QLocale::Romanian},
+ {"A S Alam", "", tr("Punjabi translation"), "", QLocale::Punjabi},
+ {"Atte Virtanen", "", tr("Finnish translation"), "", QLocale::Finnish},
+ {"Aurélien Gâteau", "agateau", tr("Message indicator support")},
+ {"Awad Mackie", "firesock", tr("Chatview improvements")},
+ {"Armin K", "", tr("Build system fix")},
+ {"", "Ayonix", tr("Build system fix")},
+ {"Benjamin Zeller", "zbenjamin", tr("Windows build system fixes")},
+ {"Ben Rosser", "", tr("AppData metadata, LDAP support")},
+ {"Bernhard Scheirle", "", tr("Nicer tooltips, spell check and other improvements")},
+ {"Bruno Brigras", "", tr("Crash fixes")},
+ {"Bruno Patri", "", tr("French translation"), "", QLocale::French},
+ {"Cédric Valmary", "", tr("Occitan translation"), "", QLocale::Occitan},
+ {"Celeste Paul", "seele", tr("Usability review")},
+ {"Chris Fuenty", "stitch", tr("SASL support")},
+ {"Chris Holland", "Shade / Zren", tr("Various improvements")},
+ {"Chris Le Sueur", "Fish-Face", tr("Various fixes and improvements")},
+ {"Chris Moeller", "kode54", tr("Various fixes and improvements")},
+ {"Christian Schwarz", "", tr("Settings fixes")},
+ {"", "Condex", tr("Galician translation"), "", QLocale::Galician},
+ {"", "cordata", tr("Esperanto translation"), "", QLocale::Esperanto},
+ {"Daniel E. Moctezuma", "", tr("Japanese translation"), "", QLocale::Japanese},
+ {"Daniel Meltzer", "hydrogen", tr("Various fixes and improvements")},
+ {"Daniel Pielmeier", "billie", tr("Gentoo maintainer")},
+ {"Daniel Schaal", "", tr("Certificate handling improvements")},
+ {"Daniel Silverstone", "", tr("Fixes")},
+ {"Daniel Steinmetz", "son", tr("Early beta tester and bughunter (on Vista™!)")},
+ {"David Planella", "", tr("Translation system fixes")},
+ {"David Roden", "Bombe", tr("Fixes")},
+ {"David Sansome", "", tr("OSX Notification Center support")},
+ {"Demiray Muhterem", "", tr("Turkish translation"), "", QLocale::Turkish},
+ {"Deniz Türkoglu", "", tr("Mac fixes")},
+ {"Dennis Schridde", "devurandom", tr("D-Bus notifications")},
+ {"", "derpella", tr("Polish translation"), "", QLocale::Polish},
+ {"Diego Pettenò", "Flameeyes", tr("Build system improvements")},
+ {"Dirk Rettschlag", "MarcLandis", tr("Formatting support and other input line improvements, many other fixes")},
+ {"", "Dorian", tr("French translation"), "", QLocale::French},
+ {"Drew Patridge", "LinuxDolt", tr("BluesTheme stylesheet")},
+ {"Edward Hades", "", tr("Russian translation"), "", QLocale::Russian},
+ {"Fabiano Francesconi", "elbryan", tr("Italian translation"), "", QLocale::Italian},
+ {"Felix Geyer", "debfx", tr("Certificate handling improvements")},
+ {"Felix Kaechele", "", tr("German translation"), "", QLocale::German},
+ {"Florent Castelli", "", tr("Sanitize topic handling, twitch.tv support")},
+ {"Frederik M.J. Vestre", "freqmod", tr("Norwegian translation"), "", QLocale::Norwegian},
+ {"Gábor Németh", "ELITE_x", tr("Hungarian translation"), "", QLocale::Hungarian},
+ {"Gryllida A", "gry", tr("IRC parser improvements")},
+ {"György Balló", "", tr("Fixes")},
+ {"H. İbrahim Güngör", "igungor", tr("Turkish translation"), "", QLocale::Turkish},
+ {"Hannah von Reth", "TheOneRing", tr("Windows build support and Appveyor maintenance, snorenotify backend")},
+ {"Harald Fernengel", "harryF", tr("Initial Qt5 support")},
+ {"Harald Sitter", "apachelogger", tr("{Ku|U}buntu packager, motivator, promoter")},
+ {"Hendrik Leppkes", "nevcairiel", tr("Various features and improvements")},
+ {"Henning Rohlfs", "honk", tr("Various fixes")},
+ {"J-P Nurmi", "", tr("Various fixes")},
+ {"Jaak Ristioja", "", tr("Bugfixes")},
+ {"Jan Alexander Steffens", "heftig", tr("Fixes")},
+ {"Jaroslav Lichtblau", "", tr("Czech translation"), "", QLocale::Czech},
+ {"Jason Joyce", "", tr("Python improvements")},
+ {"Jason Lynch", "", tr("Bugfixes")},
+ {"Javier Llorente", "", tr("Proxy improvements, Spanish translation"), "", QLocale::Spanish},
+ {"Jens Arnold", "amiconn", tr("Postgres migration fixes")},
+ {"Jens True", "", tr("Danish translation"), "", QLocale::Danish},
+ {"Jerome Leclanche", "Adys", tr("Context menu fixes")},
+ {"Jesper Thomschütz", "", tr("Various fixes")},
+ {"Jiri Grönroos", "", tr("Finnish translation"), "", QLocale::Finnish},
+ {"Joe Hansen", "", tr("Danish translation"), "", QLocale::Danish},
+ {"Johannes Huber", "johu", tr("Many fixes and improvements, bug triaging")},
+ {"John Hand", "nox", tr("Original \"All-Seeing Eye\" logo")},
+ {"Jonas Heese", "Dante", tr("Project founder, various improvements")},
+ {"Jonathan Farnham", "", tr("Spanish translation"), "", QLocale::Spanish},
+ {"Joshua T Corbin", "tvakah", tr("Various fixes")},
+ {"Jovan Jojkić", "", tr("Serbian translation"), "", QLocale::Serbian},
+ {"Jure Repinc", "JLP", tr("Slovenian translation"), "", QLocale::Slovenian},
+ {"Jussi Schultink", "jussi01", tr("Tireless tester, {Ku|U}buntu tester and lobbyist, liters of delicious Finnish alcohol")},
+ {"K. Ernest Lee", "iFire", tr("Qt5 porting help, Travis CI setup")},
+ {"Kevin Funk", "KRF", tr("German translation"), "", QLocale::German},
+ {"Kimmo Huoman", "kipe", tr("Buffer merge improvements")},
+ {"Konstantin Bläsi", "", tr("Fixes")},
+ {"Kostas Koudaras", "", tr("Greek translation"), "", QLocale::Greek},
+ {"", "Larso", tr("Finnish translation"), "", QLocale::Finnish},
+ {"Lasse Liehu", "", tr("Finnish translation"), "", QLocale::Finnish},
+ {"Leo Franchi", "", tr("OSX improvements")},
+ {"Liudas Alisauskas", "", tr("Lithuanian translation"), "", QLocale::Lithuanian},
+ {"Luke Faraone", "", tr("Documentation fixes")},
+ {"Maia Kozheva", "", tr("Russian translation"), "", QLocale::Russian},
+ {"Manuel Hoffmann", "contradictioned", tr("German translation"), "", QLocale::German},
+ {"Marcin Jabrzyk", "", tr("Improvements")},
+ {"Marco Genise", "kaffeedoktor", tr("Ideas, hacking, initial motivation")},
+ {"Marco Paolone", "Quizzlo", tr("Italian translation"), "", QLocale::Italian},
+ {"Martin Mayer", "m4yer", tr("German translation"), "", QLocale::German},
+ {"Martin Sandsmark", "sandsmark", tr("Many fixes and improvements, Sonnet support, QuasselDroid")},
+ {"Matt Schatz", "genius3000", tr("Various fixes")},
+ {"Matthias Coy", "pennywise", tr("German translation"), "", QLocale::German},
+ {"Mattia Basaglia", "", tr("Fixes")},
+ {"Michael Groh", "brot", tr("German translation, fixes"), "", QLocale::German},
+ {"Michael Kedzierski", "ycros", tr("Mac fixes")},
+ {"Michael Marley", "mamarley", tr("Many fixes and improvements; Ubuntu PPAs")},
+ {"Miguel Anxo Bouzada", "", tr("Galician translation"), "", QLocale::Galician},
+ {"Miguel Revilla", "", tr("Spanish translation"), "", QLocale::Spanish},
+ {"Nuno Pinheiro", "", tr("Tons of Oxygen icons including the Quassel logo")},
+ {"Patrick Lauer", "bonsaikitten", tr("Gentoo maintainer")},
+ {"Paul Klumpp", "Haudrauf", tr("Initial design and main window layout")},
+ {"Pavel Volkovitskiy", "int", tr("Early beta tester and bughunter")},
+ {"Pedro Araujo", "", tr("Brazilian translation"), "", QLocale::Portuguese},
+ {"Per Nielsen", "", tr("Danish translation"), "", QLocale::Danish},
+ {"Pete Beardmore", "elbeardmorez", tr("Linewrap for input line")},
+ {"Petr Bena", "", tr("Performance improvements and cleanups")},
+ {"", "phuzion", tr("Various fixes")},
+ {"Pierre-Hugues Husson", "", tr("/print command")},
+ {"Pierre Schweitzer", "", tr("Performance improvements")},
+ {"Rafael Belmonte", "EagleScreen", tr("Spanish translation"), "", QLocale::Spanish},
+ {"Raju Devidas Vindane", "", tr("Hindi and Marathi translations"), "", QLocale::Hindi},
+ {"Ramanathan Sivagurunathan", "", tr("Bugfixes")},
+ {"Raul Salinas-Monteagudo", "", tr("Fixes")},
+ {"Regis Perrin", "ZRegis", tr("French translation"), "", QLocale::French},
+ {"Rolf Eike Beer", "DerDakon", tr("Build system improvements")},
+ {"Rolf Michael Bislin", "romibi", tr("Windows build support, automated OSX builds in Travis, various improvements")},
+ {"Roscoe van Wyk", "", tr("Bugfixes")},
+ {"Rüdiger Sonderfeld", "ruediger", tr("Emacs keybindings")},
+ {"Ryan Bales", "selabnayr", tr("Improvements")},
+ {"Sai Nane", "esainane", tr("Various fixes")},
+ {"", "salnx", tr("Highlight configuration improvements")},
+ {"Scott Kitterman", "ScottK", tr("Debian/Kubuntu packager, (packaging/build system) bughunter")},
+ {"Sebastian Meyer", "", tr("Bugfixes, German translation"), "", QLocale::German},
+ {"Sebastien Fricker", "", tr("Audio backend improvements")},
+ {"Sergiu Bivol", "", tr("Romanian translation"), "", QLocale::Romanian},
+ {"", "sfionov", tr("Russian translation"), "", QLocale::Russian},
+ {"Shengjing Zhu", "", tr("Chinese translation"), "", QLocale::Chinese},
+ {"Simon Philips", "", tr("Dutch translation"), "", QLocale::Dutch},
+ {"Sjors Gielen", "dazjorz", tr("Bugfixes")},
+ {"Stefanos Sofroniou", "", tr("Greek translation"), "", QLocale::Greek},
+ {"Stella Rouzi", "differentreality", tr("Greek translation"), "", QLocale::Greek},
+ {"Sungjin Kang", "", tr("Korean translation"), "", QLocale::Korean},
+ {"Sven Anderson", "", tr("Database performance improvements")},
+ {"Svetlana Tkachenko", "gry", tr("Alias improvements")},
+ {"Tae-Hoon Kwon", "", tr("Korean translation"), "", QLocale::Korean},
+ {"Terje Andersen", "tan", tr("Norwegian translation, documentation")},
+ {"Theo Chatzimichos", "tampakrap", tr("Greek translation"), "", QLocale::Greek},
+ {"Theofilos Intzoglou", "", tr("Greek translation"), "", QLocale::Greek},
+ {"Thomas Hogh", "Datafreak", tr("Former Windows builder")},
+ {"Thomas Müller", "", tr("Fixes, Debian packaging")},
+ {"Tim Schumacher", "xAFFE", tr("Fixes and feedback")},
+ {"Tinjo Kohen", "", tr("Esperanto translation"), "", QLocale::Esperanto},
+ {"Tobias Frei", "ToBeFree", tr("German translation"), "", QLocale::German},
+ {"Tomáš Chvátal", "scarabeus", tr("Czech translation"), "", QLocale::Czech},
+ {"Veeti Paananen", "", tr("Certificate handling improvements")},
+ {"Viktor Suprun", "", tr("Russian translation"), "", QLocale::Russian},
+ {"Vít Pelčák", "", tr("Czech translation"), "", QLocale::Czech},
+ {"Volkan Gezer", "", tr("Turkish translation"), "", QLocale::Turkish},
+ {"Weng Xuetian", "wengxt", tr("Build system fix")},
+ {"Willem Jan Palenstijn", "", tr("Fixes")},
+ {"Yaohan Chen", "hagabaka", tr("Network detection improvements")},
+ {"Yuri Chornoivan", "", tr("Ukrainian translation"), "", QLocale::Ukrainian},
+ {"Zé", "", tr("Portuguese translation"), "", QLocale::Portuguese},
+ {"", "zeugma", tr("Turkish translation"), "", QLocale::Turkish}});
}
#include <QString>
#ifdef HAVE_KF5
-# include <KCoreAddons/KAboutData>
+# include <KCoreAddons/KAboutData>
#endif
-
/**
* Represents a contributor or author for Quassel.
*
QString prettyName() const;
private:
- QString _name; ///< The person's name
- QString _nick; ///< The person's nick
- QString _task; ///< The person's task
- QString _emailAddress; ///< The person's email address
- QLocale::Language _language; ///< The language the person helps translate
+ QString _name; ///< The person's name
+ QString _nick; ///< The person's nick
+ QString _task; ///< The person's task
+ QString _emailAddress; ///< The person's email address
+ QLocale::Language _language; ///< The language the person helps translate
};
-
/**
* Holds a list of authors, contributors and translators.
*
*
* @param[in] parent The parent object, if applicable
*/
- AboutData(QObject *parent = nullptr);
+ AboutData(QObject* parent = nullptr);
/**
* Adds an author to the list of contributors.
* @param[in] author The author to add
* @returns A reference to this AboutData instance
*/
- AboutData &addAuthor(const AboutPerson &author);
+ AboutData& addAuthor(const AboutPerson& author);
/**
* Adds a list of authors to the list of contributors.
* @param[in] authors A list of authors to add
* @returns A reference to this AboutData instance
*/
- AboutData &addAuthors(std::initializer_list<AboutPerson> authors);
+ AboutData& addAuthors(std::initializer_list<AboutPerson> authors);
/**
* Adds a contributor.
* @param[in] author The contributor to add
* @returns A reference to this AboutData instance
*/
- AboutData &addCredit(const AboutPerson &credit);
+ AboutData& addCredit(const AboutPerson& credit);
/**
* Adds a list of contributors.
* @param[in] authors A list of contributors to add
* @returns A reference to this AboutData instance
*/
- AboutData &addCredits(std::initializer_list<AboutPerson> credits);
+ AboutData& addCredits(std::initializer_list<AboutPerson> credits);
/**
* Gets the list of authors stored in this AboutData instance.
*
* @param[in,out] aboutData An existing AboutData instance to add Quassel's contributors to
*/
- static void setQuasselPersons(AboutData *aboutData);
+ static void setQuasselPersons(AboutData* aboutData);
private:
QList<AboutPerson> _authors; ///< The list of authors
***************************************************************************/
#include "abstractbuffercontainer.h"
+
#include "client.h"
#include "clientbacklogmanager.h"
#include "networkmodel.h"
-AbstractBufferContainer::AbstractBufferContainer(QWidget *parent)
- : AbstractItemView(parent),
- _currentBuffer(0)
-{
-}
-
+AbstractBufferContainer::AbstractBufferContainer(QWidget* parent)
+ : AbstractItemView(parent)
+ , _currentBuffer(0)
+{}
-void AbstractBufferContainer::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
+void AbstractBufferContainer::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
Q_ASSERT(model());
if (!parent.isValid()) {
if (model()->rowCount(parent) != end - start + 1)
return;
- foreach(BufferId id, _chatViews.keys()) {
+ foreach (BufferId id, _chatViews.keys()) {
removeChatView(id);
}
_chatViews.clear();
}
}
-
void AbstractBufferContainer::removeBuffer(BufferId bufferId)
{
if (!_chatViews.contains(bufferId))
_chatViews.take(bufferId);
}
-
/*
Switching to first buffer is now handled in MainWin::clientNetworkUpdated()
}
*/
-void AbstractBufferContainer::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
+void AbstractBufferContainer::currentChanged(const QModelIndex& current, const QModelIndex& previous)
{
Q_UNUSED(previous)
}
}
-
void AbstractBufferContainer::setCurrentBuffer(BufferId bufferId)
{
BufferId prevBufferId = currentBuffer();
Q_OBJECT
public:
- AbstractBufferContainer(QWidget *parent);
+ AbstractBufferContainer(QWidget* parent);
inline BufferId currentBuffer() const { return _currentBuffer; }
signals:
void currentChanged(BufferId);
- void currentChanged(const QModelIndex &);
+ void currentChanged(const QModelIndex&);
protected:
//! Create an AbstractChatView for the given BufferId and add it to the UI if necessary
- virtual AbstractChatView *createChatView(BufferId) = 0;
+ virtual AbstractChatView* createChatView(BufferId) = 0;
//! Remove a chat view from the UI and delete it
/** This method shall remove the view from the UI (for example, from a QStackedWidget) if appropriate.
virtual inline bool autoMarkerLine() const { return true; }
protected slots:
- void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) override;
- void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) override;
+ void currentChanged(const QModelIndex& current, const QModelIndex& previous) override;
+ void rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) override;
//! Show the given chat view
/** This method is called when the given chat view should be displayed. Use this e.g. for
private:
BufferId _currentBuffer;
- QHash<BufferId, AbstractChatView *> _chatViews;
+ QHash<BufferId, AbstractChatView*> _chatViews;
};
-
class AbstractChatView
{
public:
#include "abstractitemview.h"
-AbstractItemView::AbstractItemView(QWidget *parent)
- : QWidget(parent),
- _model(nullptr),
- _selectionModel(nullptr)
-{
-}
+AbstractItemView::AbstractItemView(QWidget* parent)
+ : QWidget(parent)
+ , _model(nullptr)
+ , _selectionModel(nullptr)
+{}
-
-void AbstractItemView::setModel(QAbstractItemModel *model)
+void AbstractItemView::setModel(QAbstractItemModel* model)
{
if (_model) {
disconnect(_model, nullptr, this, nullptr);
}
_model = model;
- connect(model, &QAbstractItemModel::dataChanged,
- this, &AbstractItemView::dataChanged);
- connect(model, &QAbstractItemModel::rowsAboutToBeRemoved,
- this, &AbstractItemView::rowsAboutToBeRemoved);
- connect(model, &QAbstractItemModel::rowsInserted,
- this, &AbstractItemView::rowsInserted);
+ connect(model, &QAbstractItemModel::dataChanged, this, &AbstractItemView::dataChanged);
+ connect(model, &QAbstractItemModel::rowsAboutToBeRemoved, this, &AbstractItemView::rowsAboutToBeRemoved);
+ connect(model, &QAbstractItemModel::rowsInserted, this, &AbstractItemView::rowsInserted);
}
-
-void AbstractItemView::setSelectionModel(QItemSelectionModel *selectionModel)
+void AbstractItemView::setSelectionModel(QItemSelectionModel* selectionModel)
{
if (_selectionModel) {
disconnect(_selectionModel, nullptr, this, nullptr);
}
_selectionModel = selectionModel;
- connect(selectionModel, &QItemSelectionModel::currentChanged,
- this, &AbstractItemView::currentChanged);
- connect(selectionModel, &QItemSelectionModel::selectionChanged,
- this, &AbstractItemView::selectionChanged);
+ connect(selectionModel, &QItemSelectionModel::currentChanged, this, &AbstractItemView::currentChanged);
+ connect(selectionModel, &QItemSelectionModel::selectionChanged, this, &AbstractItemView::selectionChanged);
}
#include "uisupport-export.h"
-#include <QWidget>
+#include <QAbstractItemDelegate>
#include <QAbstractItemModel>
+#include <QItemSelection>
#include <QItemSelectionModel>
#include <QModelIndex>
-#include <QItemSelection>
-#include <QAbstractItemDelegate>
#include <QPointer>
+#include <QWidget>
class UISUPPORT_EXPORT AbstractItemView : public QWidget
{
Q_OBJECT
public:
- AbstractItemView(QWidget *parent = nullptr);
+ AbstractItemView(QWidget* parent = nullptr);
- inline QAbstractItemModel *model() { return _model; }
- void setModel(QAbstractItemModel *model);
+ inline QAbstractItemModel* model() { return _model; }
+ void setModel(QAbstractItemModel* model);
- inline QItemSelectionModel *selectionModel() const { return _selectionModel; }
- void setSelectionModel(QItemSelectionModel *selectionModel);
+ inline QItemSelectionModel* selectionModel() const { return _selectionModel; }
+ void setSelectionModel(QItemSelectionModel* selectionModel);
inline QModelIndex currentIndex() const { return _selectionModel->currentIndex(); }
protected slots:
- virtual void closeEditor(QWidget *, QAbstractItemDelegate::EndEditHint) {};
- virtual void commitData(QWidget *) {};
- virtual void currentChanged(const QModelIndex &, const QModelIndex &) {};
- virtual void dataChanged(const QModelIndex &, const QModelIndex &) {};
- virtual void editorDestroyed(QObject *) {};
- virtual void rowsAboutToBeRemoved(const QModelIndex &, int, int) {};
- virtual void rowsInserted(const QModelIndex &, int, int) {};
- virtual void selectionChanged(const QItemSelection &, const QItemSelection &) {};
+ virtual void closeEditor(QWidget*, QAbstractItemDelegate::EndEditHint){};
+ virtual void commitData(QWidget*){};
+ virtual void currentChanged(const QModelIndex&, const QModelIndex&){};
+ virtual void dataChanged(const QModelIndex&, const QModelIndex&){};
+ virtual void editorDestroyed(QObject*){};
+ virtual void rowsAboutToBeRemoved(const QModelIndex&, int, int){};
+ virtual void rowsInserted(const QModelIndex&, int, int){};
+ virtual void selectionChanged(const QItemSelection&, const QItemSelection&){};
protected:
QPointer<QAbstractItemModel> _model;
#include "uisupport-export.h"
+#include <utility>
+
#include <QObject>
#include <QString>
-#include <utility>
#include "bufferinfo.h"
Q_OBJECT
public:
- enum NotificationType {
+ enum NotificationType
+ {
Highlight = 0x01,
PrivMsg = 0x02,
HighlightFocused = 0x11,
PrivMsgFocused = 0x12
};
- struct Notification {
+ struct Notification
+ {
uint notificationId;
BufferId bufferId;
NotificationType type;
QString message;
Notification(uint id_, BufferId buf_, NotificationType type_, QString sender_, QString msg_)
- : notificationId(id_), bufferId(buf_), type(type_), sender(std::move(sender_)), message(std::move(msg_)) {}
+ : notificationId(id_)
+ , bufferId(buf_)
+ , type(type_)
+ , sender(std::move(sender_))
+ , message(std::move(msg_))
+ {}
};
using QObject::QObject;
- virtual void notify(const Notification &) = 0;
+ virtual void notify(const Notification&) = 0;
virtual void close(uint notificationId) { Q_UNUSED(notificationId); }
//! Factory to create a configuration widget suitable for a specific notification backend
* AbstractNotification will not take ownership of that configWidget!
* In case you need to communicate with the configWidget directly, make your connections here
*/
- virtual SettingsPage *createConfigWidget() const = 0;
+ virtual SettingsPage* createConfigWidget() const = 0;
signals:
//! May be emitted by the notification to tell the MainWin to raise itself
#include <QApplication>
-Action::Action(QObject *parent)
+Action::Action(QObject* parent)
: QWidgetAction(parent)
{
setProperty("isShortcutConfigurable", true);
connect(this, &QAction::triggered, this, &Action::slotTriggered);
}
-
-Action::Action(const QString &text, QObject *parent, const QKeySequence &shortcut)
+Action::Action(const QString& text, QObject* parent, const QKeySequence& shortcut)
: Action(parent)
{
setText(text);
setShortcut(shortcut);
}
-
-Action::Action(const QIcon &icon, const QString &text, QObject *parent, const QKeySequence &shortcut)
+Action::Action(const QIcon& icon, const QString& text, QObject* parent, const QKeySequence& shortcut)
: Action(text, parent, shortcut)
{
setIcon(icon);
}
-
void Action::slotTriggered()
{
emit triggered(QApplication::mouseButtons(), QApplication::keyboardModifiers());
}
-
bool Action::isShortcutConfigurable() const
{
return property("isShortcutConfigurable").toBool();
}
-
void Action::setShortcutConfigurable(bool b)
{
setProperty("isShortcutConfigurable", b);
}
-
QKeySequence Action::shortcut(ShortcutTypes type) const
{
Q_ASSERT(type);
return shortcuts().isEmpty() ? QKeySequence() : shortcuts().first();
}
-
-void Action::setShortcut(const QShortcut &shortcut, ShortcutTypes type)
+void Action::setShortcut(const QShortcut& shortcut, ShortcutTypes type)
{
setShortcut(shortcut.key(), type);
}
-
-void Action::setShortcut(const QKeySequence &key, ShortcutTypes type)
+void Action::setShortcut(const QKeySequence& key, ShortcutTypes type)
{
Q_ASSERT(type);
Q_PROPERTY(bool shortcutConfigurable READ isShortcutConfigurable WRITE setShortcutConfigurable)
Q_FLAGS(ShortcutType)
-public :
- enum ShortcutType {
+public:
+ enum ShortcutType
+ {
ActiveShortcut = 0x01,
DefaultShortcut = 0x02
};
Q_DECLARE_FLAGS(ShortcutTypes, ShortcutType)
- explicit Action(QObject *parent);
- Action(const QString &text, QObject *parent, const QKeySequence &shortcut = 0);
- Action(const QIcon &icon, const QString &text, QObject *parent, const QKeySequence &shortcut = 0);
+ explicit Action(QObject* parent);
+ Action(const QString& text, QObject* parent, const QKeySequence& shortcut = 0);
+ Action(const QIcon& icon, const QString& text, QObject* parent, const QKeySequence& shortcut = 0);
template<typename Receiver, typename Slot>
- Action(const QString &text, QObject *parent, const Receiver *receiver, Slot slot, const QKeySequence &shortcut = 0)
+ Action(const QString& text, QObject* parent, const Receiver* receiver, Slot slot, const QKeySequence& shortcut = 0)
: Action(text, parent, shortcut)
{
static_assert(!std::is_same<Slot, const char*>::value, "Old-style connects not supported");
}
template<typename Receiver, typename Slot>
- Action(const QIcon &icon, const QString &text, QObject *parent, const Receiver *receiver, Slot slot, const QKeySequence &shortcut = 0)
+ Action(const QIcon& icon, const QString& text, QObject* parent, const Receiver* receiver, Slot slot, const QKeySequence& shortcut = 0)
: Action(text, parent, receiver, slot, shortcut)
{
setIcon(icon);
}
QKeySequence shortcut(ShortcutTypes types = ActiveShortcut) const;
- void setShortcut(const QShortcut &shortcut, ShortcutTypes type = ShortcutTypes(ActiveShortcut | DefaultShortcut));
- void setShortcut(const QKeySequence &shortcut, ShortcutTypes type = ShortcutTypes(ActiveShortcut | DefaultShortcut));
+ void setShortcut(const QShortcut& shortcut, ShortcutTypes type = ShortcutTypes(ActiveShortcut | DefaultShortcut));
+ void setShortcut(const QKeySequence& shortcut, ShortcutTypes type = ShortcutTypes(ActiveShortcut | DefaultShortcut));
bool isShortcutConfigurable() const;
void setShortcutConfigurable(bool configurable);
void slotTriggered();
};
-
Q_DECLARE_OPERATORS_FOR_FLAGS(Action::ShortcutTypes)
* Parts of this implementation are based on KDE's KActionCollection. *
***************************************************************************/
+#include "actioncollection.h"
+
#include <QAction>
#include <QDebug>
#include <QMetaMethod>
-#include "actioncollection.h"
-
#include "action.h"
#include "uisettings.h"
-void ActionCollection::addActions(const std::vector<std::pair<QString, Action *>> &actions)
+void ActionCollection::addActions(const std::vector<std::pair<QString, Action*>>& actions)
{
- for (auto &&p : actions) {
+ for (auto&& p : actions) {
addAction(p.first, p.second);
}
}
-
#ifndef HAVE_KDE
int ActionCollection::count() const
return actions().count();
}
-
bool ActionCollection::isEmpty() const
{
return actions().count();
_actions.clear();
}
-
-QAction *ActionCollection::action(const QString &name) const
+QAction* ActionCollection::action(const QString& name) const
{
return _actionByName.value(name, 0);
}
-
-QList<QAction *> ActionCollection::actions() const
+QList<QAction*> ActionCollection::actions() const
{
return _actions;
}
-QAction *ActionCollection::addAction(const QString &name, QAction *action)
+QAction* ActionCollection::addAction(const QString& name, QAction* action)
{
if (!action)
return action;
else
action->setObjectName(indexName);
if (indexName.isEmpty())
- indexName = indexName.sprintf("unnamed-%p", (void *)action);
+ indexName = indexName.sprintf("unnamed-%p", (void*)action);
// do we already have this action?
if (_actionByName.value(indexName, 0) == action)
return action;
// or maybe another action under this name?
- if (QAction *oldAction = _actionByName.value(indexName))
+ if (QAction* oldAction = _actionByName.value(indexName))
takeAction(oldAction);
// do we already have this action under a different name?
_actionByName.insert(indexName, action);
_actions.append(action);
- foreach(QWidget *widget, _associatedWidgets) {
+ foreach (QWidget* widget, _associatedWidgets) {
widget->addAction(action);
}
return action;
}
-
-void ActionCollection::removeAction(QAction *action)
+void ActionCollection::removeAction(QAction* action)
{
delete takeAction(action);
}
-
-QAction *ActionCollection::takeAction(QAction *action)
+QAction* ActionCollection::takeAction(QAction* action)
{
if (!unlistAction(action))
return nullptr;
- foreach(QWidget *widget, _associatedWidgets) {
+ foreach (QWidget* widget, _associatedWidgets) {
widget->removeAction(action);
}
return action;
}
-
void ActionCollection::readSettings()
{
ShortcutSettings s;
QStringList savedShortcuts = s.savedShortcuts();
- foreach(const QString &name, _actionByName.keys()) {
+ foreach (const QString& name, _actionByName.keys()) {
if (!savedShortcuts.contains(name))
continue;
- auto *action = qobject_cast<Action *>(_actionByName.value(name));
+ auto* action = qobject_cast<Action*>(_actionByName.value(name));
if (action)
action->setShortcut(s.loadShortcut(name), Action::ActiveShortcut);
}
}
-
void ActionCollection::writeSettings() const
{
ShortcutSettings s;
- foreach(const QString &name, _actionByName.keys()) {
- auto *action = qobject_cast<Action *>(_actionByName.value(name));
+ foreach (const QString& name, _actionByName.keys()) {
+ auto* action = qobject_cast<Action*>(_actionByName.value(name));
if (!action)
continue;
if (!action->isShortcutConfigurable())
}
}
-
void ActionCollection::slotActionTriggered()
{
- auto *action = qobject_cast<QAction *>(sender());
+ auto* action = qobject_cast<QAction*>(sender());
if (action)
emit actionTriggered(action);
}
-
void ActionCollection::slotActionHovered()
{
- auto *action = qobject_cast<QAction *>(sender());
+ auto* action = qobject_cast<QAction*>(sender());
if (action)
emit actionHovered(action);
}
-
-void ActionCollection::actionDestroyed(QObject *obj)
+void ActionCollection::actionDestroyed(QObject* obj)
{
// remember that this is not an QAction anymore at this point
- auto *action = static_cast<QAction *>(obj);
+ auto* action = static_cast<QAction*>(obj);
unlistAction(action);
}
-void ActionCollection::connectNotify(const QMetaMethod &signal)
+void ActionCollection::connectNotify(const QMetaMethod& signal)
{
if (_connectHovered && _connectTriggered)
return;
if (QMetaMethod::fromSignal(&ActionCollection::actionHovered) == signal) {
if (!_connectHovered) {
_connectHovered = true;
- foreach(QAction* action, actions())
- connect(action, &QAction::hovered, this, &ActionCollection::slotActionHovered);
+ foreach (QAction* action, actions())
+ connect(action, &QAction::hovered, this, &ActionCollection::slotActionHovered);
}
}
else if (QMetaMethod::fromSignal(&ActionCollection::actionTriggered) == signal) {
if (!_connectTriggered) {
_connectTriggered = true;
- foreach(QAction* action, actions())
- connect(action, &QAction::triggered, this, &ActionCollection::slotActionTriggered);
+ foreach (QAction* action, actions())
+ connect(action, &QAction::triggered, this, &ActionCollection::slotActionTriggered);
}
}
QObject::connectNotify(signal);
}
-
-void ActionCollection::associateWidget(QWidget *widget) const
+void ActionCollection::associateWidget(QWidget* widget) const
{
- foreach(QAction *action, actions()) {
+ foreach (QAction* action, actions()) {
if (!widget->actions().contains(action))
widget->addAction(action);
}
}
-
-void ActionCollection::addAssociatedWidget(QWidget *widget)
+void ActionCollection::addAssociatedWidget(QWidget* widget)
{
if (!_associatedWidgets.contains(widget)) {
widget->addActions(actions());
}
}
-
-void ActionCollection::removeAssociatedWidget(QWidget *widget)
+void ActionCollection::removeAssociatedWidget(QWidget* widget)
{
- foreach(QAction *action, actions())
- widget->removeAction(action);
+ foreach (QAction* action, actions())
+ widget->removeAction(action);
_associatedWidgets.removeAll(widget);
disconnect(widget, &QObject::destroyed, this, &ActionCollection::associatedWidgetDestroyed);
}
-
-QList<QWidget *> ActionCollection::associatedWidgets() const
+QList<QWidget*> ActionCollection::associatedWidgets() const
{
return _associatedWidgets;
}
-
void ActionCollection::clearAssociatedWidgets()
{
- foreach(QWidget *widget, _associatedWidgets)
- foreach(QAction *action, actions())
- widget->removeAction(action);
+ foreach (QWidget* widget, _associatedWidgets)
+ foreach (QAction* action, actions())
+ widget->removeAction(action);
_associatedWidgets.clear();
}
-
-void ActionCollection::associatedWidgetDestroyed(QObject *obj)
+void ActionCollection::associatedWidgetDestroyed(QObject* obj)
{
- _associatedWidgets.removeAll(static_cast<QWidget *>(obj));
+ _associatedWidgets.removeAll(static_cast<QWidget*>(obj));
}
-
-bool ActionCollection::unlistAction(QAction *action)
+bool ActionCollection::unlistAction(QAction* action)
{
// This might be called with a partly destroyed QAction!
int index = _actions.indexOf(action);
- if (index == -1) return false;
+ if (index == -1)
+ return false;
QString name = action->objectName();
_actionByName.remove(name);
#include <vector>
#ifdef HAVE_KDE
-# include <KXmlGui/KActionCollection>
+# include <KXmlGui/KActionCollection>
#endif
#include <QDebug>
using ActionCollectionParent::ActionCollectionParent;
// Convenience function that takes a list of Actions
- void addActions(const std::vector<std::pair<QString, Action *>> &actions);
+ void addActions(const std::vector<std::pair<QString, Action*>>& actions);
// Everything else is defined in KActionCollection
#ifndef HAVE_KDE
/** Not that this only adds all current actions in the collection to that widget;
* subsequently added actions won't be added automatically.
*/
- void associateWidget(QWidget *widget) const;
+ void associateWidget(QWidget* widget) const;
/// Associate all actions in this collection to the given \a widget.
/** Subsequently added actions will be automagically associated with this widget as well.
*/
- void addAssociatedWidget(QWidget *widget);
+ void addAssociatedWidget(QWidget* widget);
- void removeAssociatedWidget(QWidget *widget);
- QList<QWidget *> associatedWidgets() const;
+ void removeAssociatedWidget(QWidget* widget);
+ QList<QWidget*> associatedWidgets() const;
void clearAssociatedWidgets();
void readSettings();
int count() const;
bool isEmpty() const;
- QAction *action(int index) const;
- QAction *action(const QString &name) const;
- QList<QAction *> actions() const;
+ QAction* action(int index) const;
+ QAction* action(const QString& name) const;
+ QList<QAction*> actions() const;
- QAction *addAction(const QString &name, QAction *action);
- void removeAction(QAction *action);
- QAction *takeAction(QAction *action);
+ QAction* addAction(const QString& name, QAction* action);
+ void removeAction(QAction* action);
+ QAction* takeAction(QAction* action);
signals:
- void inserted(QAction *action);
- void actionHovered(QAction *action);
- void actionTriggered(QAction *action);
+ void inserted(QAction* action);
+ void actionHovered(QAction* action);
+ void actionTriggered(QAction* action);
protected slots:
- void connectNotify(const QMetaMethod &signal) override;
+ void connectNotify(const QMetaMethod& signal) override;
virtual void slotActionTriggered();
private slots:
void slotActionHovered();
- void actionDestroyed(QObject *);
- void associatedWidgetDestroyed(QObject *);
+ void actionDestroyed(QObject*);
+ void associatedWidgetDestroyed(QObject*);
private:
- bool unlistAction(QAction *);
+ bool unlistAction(QAction*);
- QMap<QString, QAction *> _actionByName;
- QList<QAction *> _actions;
- QList<QWidget *> _associatedWidgets;
+ QMap<QString, QAction*> _actionByName;
+ QList<QAction*> _actions;
+ QList<QWidget*> _associatedWidgets;
bool _connectHovered{false};
bool _connectTriggered{false};
#include "networkmodel.h"
-
-BufferHotListFilter::BufferHotListFilter(QAbstractItemModel *source, QObject *parent)
+BufferHotListFilter::BufferHotListFilter(QAbstractItemModel* source, QObject* parent)
: QSortFilterProxyModel(parent)
{
setSourceModel(source);
setDynamicSortFilter(true);
- sort(0, Qt::DescendingOrder); // enable sorting... this is "usually" triggered by a enabling setSortingEnabled(true) on a view;
+ sort(0, Qt::DescendingOrder); // enable sorting... this is "usually" triggered by a enabling setSortingEnabled(true) on a view;
}
BufferId BufferHotListFilter::hottestBuffer()
{
- invalidate();
- sort(0, Qt::DescendingOrder);
- QModelIndex topIndex = index(0,0);
- return data(topIndex, NetworkModel::BufferIdRole).value<BufferId>();
+ invalidate();
+ sort(0, Qt::DescendingOrder);
+ QModelIndex topIndex = index(0, 0);
+ return data(topIndex, NetworkModel::BufferIdRole).value<BufferId>();
}
-bool BufferHotListFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
+bool BufferHotListFilter::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
Q_ASSERT(sourceModel());
QModelIndex source_index = sourceModel()->index(source_row, 0, source_parent);
return true;
}
-
-bool BufferHotListFilter::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
+bool BufferHotListFilter::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const
{
int leftActivity = sourceModel()->data(source_left, NetworkModel::BufferActivityRole).toInt();
int rightActivity = sourceModel()->data(source_right, NetworkModel::BufferActivityRole).toInt();
MsgId leftUnreadMsgId = sourceModel()->data(source_left, NetworkModel::BufferFirstUnreadMsgIdRole).value<MsgId>();
MsgId rightUnreadMsgId = sourceModel()->data(source_right, NetworkModel::BufferFirstUnreadMsgIdRole).value<MsgId>();
- return leftUnreadMsgId > rightUnreadMsgId; // newer messages are treated to be "less"
+ return leftUnreadMsgId > rightUnreadMsgId; // newer messages are treated to be "less"
}
-
// QVariant BufferHotListFilter::data(const QModelIndex &index, int role) const {
// QVariant d = QSortFilterProxyModel::data(index, role);
#include "uisupport-export.h"
#include <QSortFilterProxyModel>
+
#include "types.h"
class UISUPPORT_EXPORT BufferHotListFilter : public QSortFilterProxyModel
Q_OBJECT
public:
- BufferHotListFilter(QAbstractItemModel *source, QObject *parent = nullptr);
+ BufferHotListFilter(QAbstractItemModel* source, QObject* parent = nullptr);
- inline int columnCount(const QModelIndex &) const override { return 1; }
+ inline int columnCount(const QModelIndex&) const override { return 1; }
BufferId hottestBuffer();
-// QVariant data(const QModelIndex &index, int role) const;
+ // QVariant data(const QModelIndex &index, int role) const;
protected:
- bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override;
- bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override;
+ bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override;
+ bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override;
};
#include "bufferview.h"
-#include <QApplication>
#include <QAction>
+#include <QApplication>
#include <QFlags>
#include <QHeaderView>
#include <QLineEdit>
#include "action.h"
#include "buffermodel.h"
-#include "bufferviewfilter.h"
#include "buffersettings.h"
#include "buffersyncer.h"
+#include "bufferviewfilter.h"
#include "client.h"
#include "contextmenuactionprovider.h"
#include "graphicalui.h"
#include "network.h"
#include "networkmodel.h"
-#include "contextmenuactionprovider.h"
/*****************************************
-* The TreeView showing the Buffers
-*****************************************/
+ * The TreeView showing the Buffers
+ *****************************************/
// Please be carefull when reimplementing methods which are used to inform the view about changes to the data
// to be on the safe side: call QTreeView's method aswell (or TreeViewTouch's)
-BufferView::BufferView(QWidget *parent)
+BufferView::BufferView(QWidget* parent)
: TreeViewTouch(parent)
{
connect(this, &QTreeView::collapsed, this, &BufferView::storeExpandedState);
setSelectionMode(QAbstractItemView::ExtendedSelection);
- QAbstractItemDelegate *oldDelegate = itemDelegate();
- auto *tristateDelegate = new BufferViewDelegate(this);
+ QAbstractItemDelegate* oldDelegate = itemDelegate();
+ auto* tristateDelegate = new BufferViewDelegate(this);
setItemDelegate(tristateDelegate);
delete oldDelegate;
}
-
void BufferView::init()
{
header()->setContextMenuPolicy(Qt::ActionsContextMenu);
// New entries will be expanded automatically when added; no need to call expandAll()
- header()->hide(); // nobody seems to use this anyway
+ header()->hide(); // nobody seems to use this anyway
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
#endif
}
-
-void BufferView::setModel(QAbstractItemModel *model)
+void BufferView::setModel(QAbstractItemModel* model)
{
delete selectionModel();
TreeViewTouch::setModel(model);
init();
// remove old Actions
- QList<QAction *> oldactions = header()->actions();
- foreach(QAction *action, oldactions) {
+ QList<QAction*> oldactions = header()->actions();
+ foreach (QAction* action, oldactions) {
header()->removeAction(action);
action->deleteLater();
}
return;
QString sectionName;
- QAction *showSection;
+ QAction* showSection;
for (int i = 1; i < model->columnCount(); i++) {
sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
showSection = new QAction(sectionName, header());
setExpandedState();
}
-
-void BufferView::setFilteredModel(QAbstractItemModel *model_, BufferViewConfig *config)
+void BufferView::setFilteredModel(QAbstractItemModel* model_, BufferViewConfig* config)
{
- auto *filter = qobject_cast<BufferViewFilter *>(model());
+ auto* filter = qobject_cast<BufferViewFilter*>(model());
if (filter) {
filter->setConfig(config);
setConfig(config);
setModel(model_);
}
else {
- auto *filter = new BufferViewFilter(model_, config);
+ auto* filter = new BufferViewFilter(model_, config);
setModel(filter);
connect(filter, &BufferViewFilter::configChanged, this, &BufferView::on_configChanged);
}
setConfig(config);
}
-
-void BufferView::setConfig(BufferViewConfig *config)
+void BufferView::setConfig(BufferViewConfig* config)
{
if (_config == config)
return;
}
}
-
-void BufferView::setRootIndexForNetworkId(const NetworkId &networkId)
+void BufferView::setRootIndexForNetworkId(const NetworkId& networkId)
{
if (!networkId.isValid() || !model()) {
setIndentation(10);
}
}
-
-void BufferView::joinChannel(const QModelIndex &index)
+void BufferView::joinChannel(const QModelIndex& index)
{
BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
}
-
-void BufferView::dropEvent(QDropEvent *event)
+void BufferView::dropEvent(QDropEvent* event)
{
QModelIndex index = indexAt(event->pos());
// check if we're really _on_ the item and not indicating a move to just above or below the item
// Magic margin number for this is from QAbstractItemViewPrivate::position()
const int margin = 2;
- if (cursorPos.y() - indexRect.top() < margin
- || indexRect.bottom() - cursorPos.y() < margin)
+ if (cursorPos.y() - indexRect.top() < margin || indexRect.bottom() - cursorPos.y() < margin)
return TreeViewTouch::dropEvent(event);
// If more than one buffer was being dragged, treat this as a rearrangement instead of a merge request
- QList<QPair<NetworkId, BufferId> > bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
+ QList<QPair<NetworkId, BufferId>> bufferList = Client::networkModel()->mimeDataToBufferList(event->mimeData());
if (bufferList.count() != 1)
return TreeViewTouch::dropEvent(event);
if (index2.data(NetworkModel::BufferTypeRole) == BufferInfo::ChannelBuffer && index2.data(NetworkModel::ItemActiveRole) == true)
return TreeViewTouch::dropEvent(event);
- //If the source buffer is not mergeable(AKA not a Channel and not a Query), try rearranging instead
- if (index2.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer && index2.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
+ // If the source buffer is not mergeable(AKA not a Channel and not a Query), try rearranging instead
+ if (index2.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer
+ && index2.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
return TreeViewTouch::dropEvent(event);
// If the target buffer is not mergeable(AKA not a Channel and not a Query), try rearranging instead
- if (index.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer && index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
+ if (index.data(NetworkModel::BufferTypeRole) != BufferInfo::ChannelBuffer
+ && index.data(NetworkModel::BufferTypeRole) != BufferInfo::QueryBuffer)
return TreeViewTouch::dropEvent(event);
// Confirm that the user really wants to merge the buffers before doing so
- int res = QMessageBox::question(nullptr, tr("Merge buffers permanently?"),
- tr("Do you want to merge the buffer \"%1\" permanently into buffer \"%2\"?\n This cannot be reversed!").arg(Client::networkModel()->bufferName(bufferId2)).arg(Client::networkModel()->bufferName(bufferId1)),
- QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
+ int res = QMessageBox::question(nullptr,
+ tr("Merge buffers permanently?"),
+ tr("Do you want to merge the buffer \"%1\" permanently into buffer \"%2\"?\n This cannot be reversed!")
+ .arg(Client::networkModel()->bufferName(bufferId2))
+ .arg(Client::networkModel()->bufferName(bufferId1)),
+ QMessageBox::Yes | QMessageBox::No,
+ QMessageBox::No);
if (res == QMessageBox::Yes) {
Client::mergeBuffersPermanently(bufferId1, bufferId2);
}
}
-
void BufferView::removeSelectedBuffers(bool permanently)
{
if (!config())
BufferId bufferId;
QSet<BufferId> removedRows;
- foreach(QModelIndex index, selectionModel()->selectedIndexes()) {
+ foreach (QModelIndex index, selectionModel()->selectedIndexes()) {
if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::BufferItemType)
continue;
removedRows << bufferId;
}
- foreach(BufferId bufferId, removedRows) {
+ foreach (BufferId bufferId, removedRows) {
if (permanently)
config()->requestRemoveBufferPermanently(bufferId);
else
}
}
-
-void BufferView::rowsInserted(const QModelIndex &parent, int start, int end)
+void BufferView::rowsInserted(const QModelIndex& parent, int start, int end)
{
TreeViewTouch::rowsInserted(parent, start, end);
setExpandedState(parent);
}
-
void BufferView::on_layoutChanged()
{
int numNets = model()->rowCount(QModelIndex());
}
}
-
void BufferView::on_configChanged()
{
Q_ASSERT(model());
}
}
-
void BufferView::setExpandedState()
{
// Expand all active networks, collapse inactive ones... unless manually changed
NetworkId networkId;
for (int row = 0; row < model()->rowCount(); row++) {
networkIdx = model()->index(row, 0);
- if (model()->rowCount(networkIdx) == 0)
+ if (model()->rowCount(networkIdx) == 0)
continue;
networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
}
}
-
-void BufferView::storeExpandedState(const QModelIndex &networkIdx)
+void BufferView::storeExpandedState(const QModelIndex& networkIdx)
{
NetworkId networkId = model()->data(networkIdx, NetworkModel::NetworkIdRole).value<NetworkId>();
_expandedState[networkId] = oldState;
}
-
-void BufferView::setExpandedState(const QModelIndex &networkIdx)
+void BufferView::setExpandedState(const QModelIndex& networkIdx)
{
if (model()->data(networkIdx, NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
return;
update(networkIdx);
setExpanded(networkIdx, expandNetwork);
}
- storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
+ storeExpandedState(networkIdx); // this call is needed to keep track of the isActive state
}
-void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
+void BufferView::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles)
{
TreeViewTouch::dataChanged(topLeft, bottomRight, roles);
}
}
-
void BufferView::toggleHeader(bool checked)
{
- auto *action = qobject_cast<QAction *>(sender());
+ auto* action = qobject_cast<QAction*>(sender());
header()->setSectionHidden((action->property("column")).toInt(), !checked);
}
-
-void BufferView::contextMenuEvent(QContextMenuEvent *event)
+void BufferView::contextMenuEvent(QContextMenuEvent* event)
{
QModelIndex index = indexAt(event->pos());
if (!index.isValid())
contextMenu.exec(QCursor::pos());
}
-
-void BufferView::addActionsToMenu(QMenu *contextMenu, const QModelIndex &index)
+void BufferView::addActionsToMenu(QMenu* contextMenu, const QModelIndex& index)
{
QModelIndexList indexList = selectedIndexes();
// make sure the item we clicked on is first
GraphicalUi::contextMenuActionProvider()->addActions(contextMenu, indexList, this, &BufferView::menuActionTriggered, (bool)config());
}
-
-void BufferView::addFilterActions(QMenu *contextMenu, const QModelIndex &index)
+void BufferView::addFilterActions(QMenu* contextMenu, const QModelIndex& index)
{
- auto *filter = qobject_cast<BufferViewFilter *>(model());
+ auto* filter = qobject_cast<BufferViewFilter*>(model());
if (filter) {
- QList<QAction *> filterActions = filter->actions(index);
+ QList<QAction*> filterActions = filter->actions(index);
if (!filterActions.isEmpty()) {
contextMenu->addSeparator();
- foreach(QAction *action, filterActions) {
+ foreach (QAction* action, filterActions) {
contextMenu->addAction(action);
}
}
}
}
-
-void BufferView::menuActionTriggered(QAction *result)
+void BufferView::menuActionTriggered(QAction* result)
{
ContextMenuActionProvider::ActionType type = (ContextMenuActionProvider::ActionType)result->data().toInt();
switch (type) {
}
}
-
void BufferView::nextBuffer()
{
changeBuffer(Forward);
}
-
void BufferView::previousBuffer()
{
changeBuffer(Backward);
}
-
void BufferView::changeBuffer(Direction direction)
{
QModelIndex currentIndex = selectionModel()->currentIndex();
QModelIndex lastNetIndex = model()->index(model()->rowCount() - 1, 0, QModelIndex());
if (currentIndex.parent().isValid()) {
- //If we are a child node just switch among siblings unless it's the first/last child
+ // If we are a child node just switch among siblings unless it's the first/last child
resultingIndex = currentIndex.sibling(currentIndex.row() + direction, 0);
if (!resultingIndex.isValid()) {
}
}
else {
- //If we have a toplevel node, try and get an adjacent child
+ // If we have a toplevel node, try and get an adjacent child
if (direction == Backward) {
QModelIndex newParent = currentIndex.sibling(currentIndex.row() - 1, 0);
if (currentIndex.row() == 0)
selectionModel()->select(bufferIndex, QItemSelectionModel::ClearAndSelect);
}
-void BufferView::wheelEvent(QWheelEvent *event)
+void BufferView::wheelEvent(QWheelEvent* event)
{
if (ItemViewSettings().mouseWheelChangesBuffer() == (bool)(event->modifiers() & Qt::AltModifier))
return TreeViewTouch::wheelEvent(event);
changeBuffer((Direction)rowDelta);
}
-
void BufferView::hideCurrentBuffer()
{
QModelIndex index = selectionModel()->currentIndex();
BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
- //The check above means we won't be looking at a network, which should always be the first row, so we can just go backwards.
+ // The check above means we won't be looking at a network, which should always be the first row, so we can just go backwards.
changeBuffer(Backward);
config()->requestRemoveBuffer(bufferId);
void BufferView::filterTextChanged(const QString& filterString)
{
- auto *filter = qobject_cast<BufferViewFilter *>(model());
+ auto* filter = qobject_cast<BufferViewFilter*>(model());
if (!filter) {
return;
}
filter->setFilterString(filterString);
- on_configChanged(); // make sure collapsation is correct
+ on_configChanged(); // make sure collapsation is correct
}
-
QSize BufferView::sizeHint() const
{
return TreeViewTouch::sizeHint();
return {columnSize, 50};
}
-
void BufferView::changeHighlight(BufferView::Direction direction)
{
// If for some weird reason we get a new delegate
if (direction == Backward) {
newIndex = indexBelow(newIndex);
- } else {
+ }
+ else {
newIndex = indexAbove(newIndex);
}
if (_currentHighlight.isValid()) {
selectionModel()->setCurrentIndex(_currentHighlight, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
selectionModel()->select(_currentHighlight, QItemSelectionModel::ClearAndSelect);
- } else {
+ }
+ else {
selectFirstBuffer();
}
class ColorsChangedEvent : public QEvent
{
public:
- ColorsChangedEvent() : QEvent(QEvent::User) {};
+ ColorsChangedEvent()
+ : QEvent(QEvent::User){};
};
-
-BufferViewDelegate::BufferViewDelegate(QObject *parent)
+BufferViewDelegate::BufferViewDelegate(QObject* parent)
: QStyledItemDelegate(parent)
-{
-}
+{}
-
-void BufferViewDelegate::customEvent(QEvent *event)
+void BufferViewDelegate::customEvent(QEvent* event)
{
if (event->type() != QEvent::User)
return;
event->accept();
}
-
-bool BufferViewDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
+bool BufferViewDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index)
{
if (event->type() != QEvent::MouseButtonRelease)
return QStyledItemDelegate::editorEvent(event, model, option, index);
initStyleOption(&viewOpt, index);
QRect checkRect = viewOpt.widget->style()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, viewOpt.widget);
- auto *me = static_cast<QMouseEvent *>(event);
+ auto* me = static_cast<QMouseEvent*>(event);
if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
return QStyledItemDelegate::editorEvent(event, model, option, index);
return true;
}
-
// ==============================
// BufferView Dock
// ==============================
-BufferViewDock::BufferViewDock(BufferViewConfig *config, QWidget *parent)
- : QDockWidget(parent),
- _childWidget(nullptr),
- _widget(new QWidget(parent)),
- _filterEdit(new QLineEdit(parent)),
- _active(false),
- _title(config->bufferViewName())
+BufferViewDock::BufferViewDock(BufferViewConfig* config, QWidget* parent)
+ : QDockWidget(parent)
+ , _childWidget(nullptr)
+ , _widget(new QWidget(parent))
+ , _filterEdit(new QLineEdit(parent))
+ , _active(false)
+ , _title(config->bufferViewName())
{
setObjectName("BufferViewDock-" + QString::number(config->bufferViewId()));
toggleViewAction()->setData(config->bufferViewId());
- setAllowedAreas(Qt::RightDockWidgetArea|Qt::LeftDockWidgetArea);
+ setAllowedAreas(Qt::RightDockWidgetArea | Qt::LeftDockWidgetArea);
connect(config, &BufferViewConfig::bufferViewNameSet, this, &BufferViewDock::bufferViewRenamed);
connect(config, &BufferViewConfig::configChanged, this, &BufferViewDock::configChanged);
updateTitle();
QDockWidget::setWidget(_widget);
}
-void BufferViewDock::setLocked(bool locked) {
+void BufferViewDock::setLocked(bool locked)
+{
if (locked) {
setFeatures(nullptr);
}
_filterEdit->setVisible(false);
}
- BufferView *view = bufferView();
+ BufferView* view = bufferView();
if (!view) {
return;
}
if (!_filterEdit->text().isEmpty()) {
view->selectHighlighted();
_filterEdit->clear();
- } else {
+ }
+ else {
view->clearHighlight();
}
}
}
}
-bool BufferViewDock::eventFilter(QObject *object, QEvent *event)
+bool BufferViewDock::eventFilter(QObject* object, QEvent* event)
{
- if (object != _filterEdit) {
- return false;
- }
+ if (object != _filterEdit) {
+ return false;
+ }
if (event->type() == QEvent::FocusOut) {
if (!config()->showSearch() && _filterEdit->text().isEmpty()) {
_filterEdit->setVisible(false);
return true;
}
- } else if (event->type() == QEvent::KeyRelease) {
+ }
+ else if (event->type() == QEvent::KeyRelease) {
auto keyEvent = static_cast<QKeyEvent*>(event);
- BufferView *view = bufferView();
+ BufferView* view = bufferView();
if (!view) {
return false;
}
return false;
}
-void BufferViewDock::bufferViewRenamed(const QString &newName)
+void BufferViewDock::bufferViewRenamed(const QString& newName)
{
_title = newName;
updateTitle();
toggleViewAction()->setText(newName);
}
-
int BufferViewDock::bufferViewId() const
{
- BufferView *view = bufferView();
+ BufferView* view = bufferView();
if (!view)
return 0;
return 0;
}
-
-BufferViewConfig *BufferViewDock::config() const
+BufferViewConfig* BufferViewDock::config() const
{
- BufferView *view = bufferView();
+ BufferView* view = bufferView();
if (!view)
return nullptr;
else
return view->config();
}
-void BufferViewDock::setWidget(QWidget *newWidget)
+void BufferViewDock::setWidget(QWidget* newWidget)
{
_widget->layout()->addWidget(newWidget);
_childWidget = newWidget;
#include "uisupport-export.h"
#include <QAction>
-#include <QMenu>
#include <QDockWidget>
+#include <QMenu>
#include <QModelIndex>
-#include <QStyledItemDelegate>
#include <QPointer>
+#include <QStyledItemDelegate>
#include "actioncollection.h"
#include "bufferviewconfig.h"
Q_OBJECT
public:
- enum Direction {
+ enum Direction
+ {
Forward = 1,
Backward = -1
};
- BufferView(QWidget *parent = nullptr);
+ BufferView(QWidget* parent = nullptr);
void init();
- void setModel(QAbstractItemModel *model) override;
- void setFilteredModel(QAbstractItemModel *model, BufferViewConfig *config);
+ void setModel(QAbstractItemModel* model) override;
+ void setFilteredModel(QAbstractItemModel* model, BufferViewConfig* config);
- void setConfig(BufferViewConfig *config);
- inline BufferViewConfig *config() { return _config; }
+ void setConfig(BufferViewConfig* config);
+ inline BufferViewConfig* config() { return _config; }
- void addActionsToMenu(QMenu *menu, const QModelIndex &index);
- void addFilterActions(QMenu *contextMenu, const QModelIndex &index);
+ void addActionsToMenu(QMenu* menu, const QModelIndex& index);
+ void addFilterActions(QMenu* contextMenu, const QModelIndex& index);
void selectFirstBuffer();
public slots:
- void setRootIndexForNetworkId(const NetworkId &networkId);
+ void setRootIndexForNetworkId(const NetworkId& networkId);
void removeSelectedBuffers(bool permanently = false);
- void menuActionTriggered(QAction *);
+ void menuActionTriggered(QAction*);
void nextBuffer();
void previousBuffer();
void hideCurrentBuffer();
void clearHighlight();
signals:
- void removeBuffer(const QModelIndex &);
- void removeBufferPermanently(const QModelIndex &);
+ void removeBuffer(const QModelIndex&);
+ void removeBufferPermanently(const QModelIndex&);
protected:
- void dropEvent(QDropEvent *event) override;
- void rowsInserted(const QModelIndex &parent, int start, int end) override;
- void wheelEvent(QWheelEvent *) override;
+ void dropEvent(QDropEvent* event) override;
+ void rowsInserted(const QModelIndex& parent, int start, int end) override;
+ void wheelEvent(QWheelEvent*) override;
QSize sizeHint() const override;
- void focusInEvent(QFocusEvent *event) override { QAbstractScrollArea::focusInEvent(event); }
- void contextMenuEvent(QContextMenuEvent *event) override;
+ void focusInEvent(QFocusEvent* event) override { QAbstractScrollArea::focusInEvent(event); }
+ void contextMenuEvent(QContextMenuEvent* event) override;
- void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles) override;
+ void dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles) override;
private slots:
- void joinChannel(const QModelIndex &index);
+ void joinChannel(const QModelIndex& index);
void toggleHeader(bool checked);
/**
* @see setExpandedState()
* @param[in] networkIdx QModelIndex of the root network to store
*/
- void storeExpandedState(const QModelIndex &networkIdx);
+ void storeExpandedState(const QModelIndex& networkIdx);
/**
* Set the display state of the given network according to network status and manual changes
* @see storeExpandedState()
* @param[in] networkIdx QModelIndex of the root network to update
*/
- void setExpandedState(const QModelIndex &networkIdx);
+ void setExpandedState(const QModelIndex& networkIdx);
void on_configChanged();
void on_layoutChanged();
private:
QPointer<BufferViewConfig> _config;
- enum ExpandedState {
+ enum ExpandedState
+ {
WasExpanded = 0x01,
WasActive = 0x02
};
QModelIndex _currentHighlight;
};
-
// ******************************
// BufferViewDelegate
// ******************************
Q_OBJECT
public:
- BufferViewDelegate(QObject *parent = nullptr);
- bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override;
+ BufferViewDelegate(QObject* parent = nullptr);
+ bool editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index) override;
- void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;
+ void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override;
public:
QModelIndex currentHighlight;
protected:
- void customEvent(QEvent *event) override;
+ void customEvent(QEvent* event) override;
};
-
// ==============================
// BufferView Dock
// ==============================
Q_OBJECT
Q_PROPERTY(bool active READ isActive WRITE setActive STORED true)
-public :
- BufferViewDock(BufferViewConfig *config, QWidget *parent);
+public:
+ BufferViewDock(BufferViewConfig* config, QWidget* parent);
int bufferViewId() const;
- BufferViewConfig *config() const;
- inline BufferView *bufferView() const { return qobject_cast<BufferView *>(widget()); }
+ BufferViewConfig* config() const;
+ inline BufferView* bufferView() const { return qobject_cast<BufferView*>(widget()); }
inline bool isActive() const { return _active; }
- void setWidget(QWidget *newWidget);
+ void setWidget(QWidget* newWidget);
void setLocked(bool locked);
- QWidget *widget() const { return _childWidget; }
+ QWidget* widget() const { return _childWidget; }
void activateFilter();
void setActive(bool active = true);
protected slots:
- bool eventFilter(QObject *object, QEvent *event) override;
- void focusInEvent(QFocusEvent*event) override { qDebug() << event; }
+ bool eventFilter(QObject* object, QEvent* event) override;
+ void focusInEvent(QFocusEvent* event) override { qDebug() << event; }
private slots:
- void bufferViewRenamed(const QString &newName);
+ void bufferViewRenamed(const QString& newName);
void updateTitle();
void configChanged();
void onFilterReturnPressed();
private:
- QWidget *_childWidget;
- QWidget *_widget;
- QPointer<QWidget> _oldFocusItem; // QPointer in case the old item gets deleted
- QLineEdit *_filterEdit;
+ QWidget* _childWidget;
+ QWidget* _widget;
+ QPointer<QWidget> _oldFocusItem; // QPointer in case the old item gets deleted
+ QLineEdit* _filterEdit;
bool _active;
QString _title;
};
#include "bufferviewfilter.h"
#include <QApplication>
-#include <QPalette>
#include <QBrush>
+#include <QPalette>
#include "bufferinfo.h"
#include "buffermodel.h"
#include "networkmodel.h"
#include "uistyle.h"
-
/*****************************************
-* The Filter for the Tree View
-*****************************************/
-BufferViewFilter::BufferViewFilter(QAbstractItemModel *model, BufferViewConfig *config)
- : QSortFilterProxyModel(model),
- _config(nullptr),
- _sortOrder(Qt::AscendingOrder),
- _showServerQueries(false),
- _editMode(false),
- _enableEditMode(tr("Show / Hide Chats"), this)
+ * The Filter for the Tree View
+ *****************************************/
+BufferViewFilter::BufferViewFilter(QAbstractItemModel* model, BufferViewConfig* config)
+ : QSortFilterProxyModel(model)
+ , _config(nullptr)
+ , _sortOrder(Qt::AscendingOrder)
+ , _showServerQueries(false)
+ , _editMode(false)
+ , _enableEditMode(tr("Show / Hide Chats"), this)
{
setConfig(config);
setSourceModel(model);
showServerQueriesChanged();
}
-
-void BufferViewFilter::setConfig(BufferViewConfig *config)
+void BufferViewFilter::setConfig(BufferViewConfig* config)
{
if (_config == config)
return;
}
}
-
void BufferViewFilter::configInitialized()
{
if (!config())
emit configChanged();
}
-
void BufferViewFilter::showServerQueriesChanged()
{
BufferSettings bufferSettings;
}
}
-
-QList<QAction *> BufferViewFilter::actions(const QModelIndex &index)
+QList<QAction*> BufferViewFilter::actions(const QModelIndex& index)
{
Q_UNUSED(index)
- QList<QAction *> actionList;
+ QList<QAction*> actionList;
actionList << &_enableEditMode;
return actionList;
}
enableEditMode(!string.isEmpty());
}
-
void BufferViewFilter::enableEditMode(bool enable)
{
if (_editMode == enable) {
invalidate();
}
-
-Qt::ItemFlags BufferViewFilter::flags(const QModelIndex &index) const
+Qt::ItemFlags BufferViewFilter::flags(const QModelIndex& index) const
{
QModelIndex source_index = mapToSource(index);
Qt::ItemFlags flags = sourceModel()->flags(source_index);
// This DOES mean that it looks like you can merge a buffer into the Status buffer, but that is restricted in BufferView::dropEvent().
if (bufferType == BufferInfo::StatusBuffer) {
// But only if the layout isn't locked!
- auto *clientConf = qobject_cast<ClientBufferViewConfig *>(config());
+ auto* clientConf = qobject_cast<ClientBufferViewConfig*>(config());
if (clientConf && !clientConf->isLocked()) {
flags |= Qt::ItemIsDropEnabled;
}
return flags;
}
-
-bool BufferViewFilter::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
+bool BufferViewFilter::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent)
{
if (!config() || !NetworkModel::mimeContainsBufferList(data))
return QSortFilterProxyModel::dropMimeData(data, action, row, column, parent);
if (sourceModel()->data(source_parent, NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType)
droppedNetworkId = sourceModel()->data(source_parent, NetworkModel::NetworkIdRole).value<NetworkId>();
- QList<QPair<NetworkId, BufferId> > bufferList = NetworkModel::mimeDataToBufferList(data);
+ QList<QPair<NetworkId, BufferId>> bufferList = NetworkModel::mimeDataToBufferList(data);
BufferId bufferId;
NetworkId networkId;
int pos;
if (config()->bufferList().contains(bufferId) && !config()->sortAlphabetically()) {
if (config()->bufferList().indexOf(bufferId) < pos)
pos--;
- auto *clientConf = qobject_cast<ClientBufferViewConfig *>(config());
+ auto* clientConf = qobject_cast<ClientBufferViewConfig*>(config());
if (!clientConf || !clientConf->isLocked())
config()->requestMoveBuffer(bufferId, pos);
}
return true;
}
-
void BufferViewFilter::sort(int column, Qt::SortOrder order)
{
_sortOrder = order;
QSortFilterProxyModel::sort(column, order);
}
-
-void BufferViewFilter::addBuffer(const BufferId &bufferId) const
+void BufferViewFilter::addBuffer(const BufferId& bufferId) const
{
if (!config() || config()->bufferList().contains(bufferId))
return;
config()->requestAddBuffer(bufferId, pos);
}
-
-void BufferViewFilter::addBuffers(const QList<BufferId> &bufferIds) const
+void BufferViewFilter::addBuffers(const QList<BufferId>& bufferIds) const
{
if (!config())
return;
QList<BufferId> bufferList = config()->bufferList();
- foreach(BufferId bufferId, bufferIds) {
+ foreach (BufferId bufferId, bufferIds) {
if (bufferList.contains(bufferId))
continue;
}
}
-
-bool BufferViewFilter::filterAcceptBuffer(const QModelIndex &source_bufferIndex) const
+bool BufferViewFilter::filterAcceptBuffer(const QModelIndex& source_bufferIndex) const
{
// no config -> "all buffers" -> accept everything
if (!config())
if (!config()->bufferList().contains(bufferId) && !_editMode) {
// add the buffer if...
- if (config()->isInitialized()
- && !config()->removedBuffers().contains(bufferId) // it hasn't been manually removed and either
- && ((config()->addNewBuffersAutomatically() && !config()->temporarilyRemovedBuffers().contains(bufferId)) // is totally unknown to us (a new buffer)...
- || (config()->temporarilyRemovedBuffers().contains(bufferId) && activityLevel > BufferInfo::OtherActivity))) { // or was just temporarily hidden and has a new message waiting for us.
+ if (config()->isInitialized() && !config()->removedBuffers().contains(bufferId) // it hasn't been manually removed and either
+ && ((config()->addNewBuffersAutomatically()
+ && !config()->temporarilyRemovedBuffers().contains(bufferId)) // is totally unknown to us (a new buffer)...
+ || (config()->temporarilyRemovedBuffers().contains(bufferId)
+ && activityLevel > BufferInfo::OtherActivity))) { // or was just temporarily hidden and has a new message waiting for us.
addBuffer(bufferId);
}
// note: adding the buffer to the valid list does not temper with the following filters ("show only channels" and stuff)
return false;
}
- if (config()->networkId().isValid() && config()->networkId() != sourceModel()->data(source_bufferIndex, NetworkModel::NetworkIdRole).value<NetworkId>())
+ if (config()->networkId().isValid()
+ && config()->networkId() != sourceModel()->data(source_bufferIndex, NetworkModel::NetworkIdRole).value<NetworkId>())
return false;
int allowedBufferTypes = config()->allowedBufferTypes();
if (!(allowedBufferTypes & bufferType))
return false;
- if (bufferType & BufferInfo::QueryBuffer && !_showServerQueries && sourceModel()->data(source_bufferIndex, Qt::DisplayRole).toString().contains('.')) {
+ if (bufferType & BufferInfo::QueryBuffer && !_showServerQueries
+ && sourceModel()->data(source_bufferIndex, Qt::DisplayRole).toString().contains('.')) {
return false;
}
QString name = info.bufferName();
if (name.contains(_filterString, Qt::CaseInsensitive)) {
return true;
- } else {
+ }
+ else {
return false;
}
}
if (bufferId == Client::bufferModel()->data(currentIndex, NetworkModel::BufferIdRole).value<BufferId>())
return true;
- if (config()->hideInactiveBuffers() && !sourceModel()->data(source_bufferIndex, NetworkModel::ItemActiveRole).toBool() && activityLevel <= BufferInfo::OtherActivity)
+ if (config()->hideInactiveBuffers() && !sourceModel()->data(source_bufferIndex, NetworkModel::ItemActiveRole).toBool()
+ && activityLevel <= BufferInfo::OtherActivity)
return false;
if (config()->minimumActivity() > activityLevel)
return true;
}
-
-bool BufferViewFilter::filterAcceptNetwork(const QModelIndex &source_index) const
+bool BufferViewFilter::filterAcceptNetwork(const QModelIndex& source_index) const
{
if (!config())
return true;
}
}
-
-bool BufferViewFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
+bool BufferViewFilter::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
QModelIndex child = sourceModel()->index(source_row, 0, source_parent);
}
}
-
-bool BufferViewFilter::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
+bool BufferViewFilter::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const
{
int leftItemType = sourceModel()->data(source_left, NetworkModel::ItemTypeRole).toInt();
int rightItemType = sourceModel()->data(source_right, NetworkModel::ItemTypeRole).toInt();
}
}
-
-bool BufferViewFilter::bufferLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
+bool BufferViewFilter::bufferLessThan(const QModelIndex& source_left, const QModelIndex& source_right) const
{
BufferId leftBufferId = sourceModel()->data(source_left, NetworkModel::BufferIdRole).value<BufferId>();
BufferId rightBufferId = sourceModel()->data(source_right, NetworkModel::BufferIdRole).value<BufferId>();
// If filtering, prioritize relevant items first
if (!_filterString.isEmpty()) {
// Get names of the buffers
- QString leftBufferName = sourceModel()->data(source_left, NetworkModel::BufferInfoRole)
- .value<BufferInfo>().bufferName();
- QString rightBufferName = sourceModel()->data(source_right, NetworkModel::BufferInfoRole)
- .value<BufferInfo>().bufferName();
+ QString leftBufferName = sourceModel()->data(source_left, NetworkModel::BufferInfoRole).value<BufferInfo>().bufferName();
+ QString rightBufferName = sourceModel()->data(source_right, NetworkModel::BufferInfoRole).value<BufferInfo>().bufferName();
// Check if there's any differences across types, most important first
if ((QString::compare(leftBufferName, _filterString, Qt::CaseInsensitive) == 0)
- != (QString::compare(rightBufferName, _filterString, Qt::CaseInsensitive) == 0)) {
+ != (QString::compare(rightBufferName, _filterString, Qt::CaseInsensitive) == 0)) {
// One of these buffers is an exact match with the filter string, while the other isn't
// Prioritize whichever one is the exact match
// (If left buffer is exact, return true to set it as less than right)
return (QString::compare(leftBufferName, _filterString, Qt::CaseInsensitive) == 0);
}
else if (leftBufferName.startsWith(_filterString, Qt::CaseInsensitive)
- != rightBufferName.startsWith(_filterString, Qt::CaseInsensitive)) {
+ != rightBufferName.startsWith(_filterString, Qt::CaseInsensitive)) {
// One of these buffers starts with the filter string, while the other doesn't
// Prioritize whichever one starts with the filter string
// (If left buffer starts with, return true to set it as less than right)
return bufferIdLessThan(leftBufferId, rightBufferId);
}
-
-bool BufferViewFilter::networkLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
+bool BufferViewFilter::networkLessThan(const QModelIndex& source_left, const QModelIndex& source_right) const
{
// NetworkId leftNetworkId = sourceModel()->data(source_left, NetworkModel::NetworkIdRole).value<NetworkId>();
// NetworkId rightNetworkId = sourceModel()->data(source_right, NetworkModel::NetworkIdRole).value<NetworkId>();
return QSortFilterProxyModel::lessThan(source_left, source_right);
}
-
-QVariant BufferViewFilter::data(const QModelIndex &index, int role) const
+QVariant BufferViewFilter::data(const QModelIndex& index, int role) const
{
switch (role) {
case Qt::FontRole:
}
}
-
-QVariant BufferViewFilter::checkedState(const QModelIndex &index) const
+QVariant BufferViewFilter::checkedState(const QModelIndex& index) const
{
if (!_editMode || !config())
return QVariant();
return Qt::Unchecked;
}
-
-bool BufferViewFilter::setData(const QModelIndex &index, const QVariant &value, int role)
+bool BufferViewFilter::setData(const QModelIndex& index, const QVariant& value, int role)
{
switch (role) {
case Qt::CheckStateRole:
}
}
-
-bool BufferViewFilter::setCheckedState(const QModelIndex &index, Qt::CheckState state)
+bool BufferViewFilter::setCheckedState(const QModelIndex& index, Qt::CheckState state)
{
QModelIndex source_index = mapToSource(index);
BufferId bufferId = sourceModel()->data(source_index, NetworkModel::BufferIdRole).value<BufferId>();
return true;
}
-
-bool BufferViewFilter::bufferIdLessThan(const BufferId &left, const BufferId &right)
+bool BufferViewFilter::bufferIdLessThan(const BufferId& left, const BufferId& right)
{
Q_CHECK_PTR(Client::networkModel());
if (!Client::networkModel())
if (leftType != rightType)
return leftType < rightType;
else
- return QString::compare(Client::networkModel()->data(leftIndex, Qt::DisplayRole).toString(), Client::networkModel()->data(rightIndex, Qt::DisplayRole).toString(), Qt::CaseInsensitive) < 0;
+ return QString::compare(Client::networkModel()->data(leftIndex, Qt::DisplayRole).toString(),
+ Client::networkModel()->data(rightIndex, Qt::DisplayRole).toString(),
+ Qt::CaseInsensitive)
+ < 0;
}
#include <QSet>
#include <QSortFilterProxyModel>
-#include "types.h"
#include "bufferviewconfig.h"
+#include "types.h"
/*****************************************
* Buffer View Filter
Q_OBJECT
public:
- enum Mode {
+ enum Mode
+ {
NoActive = 0x01,
NoInactive = 0x02,
SomeNets = 0x04,
};
Q_DECLARE_FLAGS(Modes, Mode)
- BufferViewFilter(QAbstractItemModel *model, BufferViewConfig *config = nullptr);
+ BufferViewFilter(QAbstractItemModel* model, BufferViewConfig* config = nullptr);
- Qt::ItemFlags flags(const QModelIndex &index) const override;
- bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override;
+ Qt::ItemFlags flags(const QModelIndex& index) const override;
+ bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) override;
- QVariant data(const QModelIndex &index, int role) const override;
- QVariant checkedState(const QModelIndex &index) const;
+ QVariant data(const QModelIndex& index, int role) const override;
+ QVariant checkedState(const QModelIndex& index) const;
- bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
- bool setCheckedState(const QModelIndex &index, Qt::CheckState state);
+ bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override;
+ bool setCheckedState(const QModelIndex& index, Qt::CheckState state);
- void setConfig(BufferViewConfig *config);
- inline BufferViewConfig *config() const { return _config; }
+ void setConfig(BufferViewConfig* config);
+ inline BufferViewConfig* config() const { return _config; }
void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override;
- QList<QAction *> actions(const QModelIndex &index);
+ QList<QAction*> actions(const QModelIndex& index);
void setFilterString(const QString string);
protected:
- bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override;
- bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override;
- bool bufferLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const;
- bool networkLessThan(const QModelIndex &source_left, const QModelIndex &source_right) const;
+ bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override;
+ bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override;
+ bool bufferLessThan(const QModelIndex& source_left, const QModelIndex& source_right) const;
+ bool networkLessThan(const QModelIndex& source_left, const QModelIndex& source_right) const;
signals:
void configChanged();
QSet<BufferId> _toRemove;
QString _filterString;
- bool filterAcceptBuffer(const QModelIndex &) const;
- bool filterAcceptNetwork(const QModelIndex &) const;
- void addBuffer(const BufferId &bufferId) const;
- void addBuffers(const QList<BufferId> &bufferIds) const;
- static bool bufferIdLessThan(const BufferId &, const BufferId &);
+ bool filterAcceptBuffer(const QModelIndex&) const;
+ bool filterAcceptNetwork(const QModelIndex&) const;
+ void addBuffer(const BufferId& bufferId) const;
+ void addBuffers(const QList<BufferId>& bufferIds) const;
+ static bool bufferIdLessThan(const BufferId&, const BufferId&);
};
-
Q_DECLARE_OPERATORS_FOR_FLAGS(BufferViewFilter::Modes)
#include "networkmodel.h"
#include "types.h"
-BufferViewOverlayFilter::BufferViewOverlayFilter(QAbstractItemModel *model, BufferViewOverlay *overlay)
- : QSortFilterProxyModel(model),
- _overlay(nullptr)
+BufferViewOverlayFilter::BufferViewOverlayFilter(QAbstractItemModel* model, BufferViewOverlay* overlay)
+ : QSortFilterProxyModel(model)
+ , _overlay(nullptr)
{
setOverlay(overlay);
setSourceModel(model);
setDynamicSortFilter(true);
}
-
-void BufferViewOverlayFilter::setOverlay(BufferViewOverlay *overlay)
+void BufferViewOverlayFilter::setOverlay(BufferViewOverlay* overlay)
{
if (_overlay == overlay)
return;
invalidate();
}
-
void BufferViewOverlayFilter::overlayDestroyed()
{
setOverlay(nullptr);
}
-
-bool BufferViewOverlayFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
+bool BufferViewOverlayFilter::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
if (!_overlay)
return false;
Q_OBJECT
public:
- BufferViewOverlayFilter(QAbstractItemModel *model, BufferViewOverlay *overlay = nullptr);
+ BufferViewOverlayFilter(QAbstractItemModel* model, BufferViewOverlay* overlay = nullptr);
- void setOverlay(BufferViewOverlay *overlay);
+ void setOverlay(BufferViewOverlay* overlay);
protected:
- bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override;
+ bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override;
private slots:
void overlayDestroyed();
private:
- BufferViewOverlay *_overlay;
+ BufferViewOverlay* _overlay;
};
#include "clearablelineedit.h"
-#include <QToolButton>
#include <QStyle>
+#include <QToolButton>
#include "icon.h"
-ClearableLineEdit::ClearableLineEdit(QWidget *parent)
+ClearableLineEdit::ClearableLineEdit(QWidget* parent)
: QLineEdit(parent)
{
clearButton = new QToolButton(this);
setStyleSheet(QString("QLineEdit { padding-right: %1px; } ").arg(clearButton->sizeHint().width() + frameWidth + 1));
QSize msz = minimumSizeHint();
setMinimumSize(qMax(msz.width(), clearButton->sizeHint().height() + frameWidth * 2 + 2),
- qMax(msz.height(), clearButton->sizeHint().height() + frameWidth * 2 + 2));
+ qMax(msz.height(), clearButton->sizeHint().height() + frameWidth * 2 + 2));
}
-
-void ClearableLineEdit::resizeEvent(QResizeEvent *)
+void ClearableLineEdit::resizeEvent(QResizeEvent*)
{
QSize size = clearButton->sizeHint();
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
- clearButton->move(rect().right() - frameWidth - size.width(),
- (rect().bottom() + 1 - size.height())/2);
+ clearButton->move(rect().right() - frameWidth - size.width(), (rect().bottom() + 1 - size.height()) / 2);
}
-
-void ClearableLineEdit::updateClearButton(const QString &text)
+void ClearableLineEdit::updateClearButton(const QString& text)
{
clearButton->setVisible(!text.isEmpty());
}
Q_OBJECT
public:
- ClearableLineEdit(QWidget *parent = nullptr);
+ ClearableLineEdit(QWidget* parent = nullptr);
protected:
- void resizeEvent(QResizeEvent *event) override;
+ void resizeEvent(QResizeEvent* event) override;
private slots:
- void updateClearButton(const QString &text);
+ void updateClearButton(const QString& text);
private:
- QToolButton *clearButton;
+ QToolButton* clearButton;
};
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "clickable.h"
+
#include <QDesktopServices>
#include <QModelIndex>
#include <QUrl>
#include "buffermodel.h"
-#include "clickable.h"
#include "client.h"
-void Clickable::activate(NetworkId networkId, const QString &text) const
+void Clickable::activate(NetworkId networkId, const QString& text) const
{
if (!isValid())
return;
}
}
-
// NOTE: This method is not threadsafe and not reentrant!
// (RegExps are not constant while matching, and they are static here for efficiency)
-ClickableList ClickableList::fromString(const QString &str)
+ClickableList ClickableList::fromString(const QString& str)
{
// For matching URLs
static QString scheme(R"((?:(?:mailto:|(?:[+.-]?\w)+://)|www(?=\.\S+\.)))");
// TODO: Nicks, we'll need a filtering for only matching known nicknames further down if we do this
};
- static const int regExpCount = 2; // number of regexps in the array above
+ static const int regExpCount = 2; // number of regexps in the array above
- qint16 matches[] = { 0, 0, 0 };
- qint16 matchEnd[] = { 0, 0, 0 };
+ qint16 matches[] = {0, 0, 0};
+ qint16 matchEnd[] = {0, 0, 0};
ClickableList result;
- //QString str = data(ChatLineModel::DisplayRole).toString();
+ // QString str = data(ChatLineModel::DisplayRole).toString();
qint16 idx = 0;
qint16 minidx;
type = -1;
minidx = str.length();
for (int i = 0; i < regExpCount; i++) {
- if (matches[i] < 0 || matchEnd[i] > str.length()) continue;
+ if (matches[i] < 0 || matchEnd[i] > str.length())
+ continue;
if (idx >= matchEnd[i]) {
matches[i] = regExp[i].indexIn(str, qMax(matchEnd[i], idx));
- if (matches[i] >= 0) matchEnd[i] = matches[i] + regExp[i].cap(1).length();
+ if (matches[i] >= 0)
+ matchEnd[i] = matches[i] + regExp[i].cap(1).length();
}
if (matches[i] >= 0 && matches[i] < minidx) {
minidx = matches[i];
if (type >= 0) {
idx = matchEnd[type];
QString match = str.mid(matches[type], matchEnd[type] - matches[type]);
- if (type == Clickable::Url && str.at(idx-1) == ')') { // special case: closing paren only matches if we had an open one
+ if (type == Clickable::Url && str.at(idx - 1) == ')') { // special case: closing paren only matches if we had an open one
if (!match.contains('(')) {
matchEnd[type]--;
match.chop(1);
}
result.emplace_back((Clickable::Type)type, matches[type], matchEnd[type] - matches[type]);
}
- }
- while (type >= 0);
+ } while (type >= 0);
return result;
}
-
Clickable ClickableList::atCursorPos(int idx)
{
- foreach(const Clickable &click, *this) {
+ foreach (const Clickable& click, *this) {
if (idx >= click.start() && idx < click.start() + click.length())
return click;
}
{
public:
// Don't change these enums without also changing dependent methods!
- enum Type {
+ enum Type
+ {
Invalid = -1,
Url = 0,
Channel = 1,
};
explicit inline Clickable(Type type = Invalid, quint16 start = 0, quint16 length = 0)
- : _type(type), _start(start), _length(length)
+ : _type(type)
+ , _start(start)
+ , _length(length)
{}
inline Type type() const { return _type; }
inline bool isValid() const { return _type != Invalid; }
- void activate(NetworkId networkId, const QString &bufferName) const;
+ void activate(NetworkId networkId, const QString& bufferName) const;
private:
Type _type;
quint16 _length;
};
-
class UISUPPORT_EXPORT ClickableList : public std::vector<Clickable>
{
public:
- static ClickableList fromString(const QString &);
+ static ClickableList fromString(const QString&);
Clickable atCursorPos(int idx);
};
#include <QDebug>
#include <QMouseEvent>
-ClickableLabel::ClickableLabel(QWidget *parent)
+ClickableLabel::ClickableLabel(QWidget* parent)
: QLabel(parent)
-{
-}
-
+{}
-void ClickableLabel::mouseReleaseEvent(QMouseEvent *event)
+void ClickableLabel::mouseReleaseEvent(QMouseEvent* event)
{
if (event->pos().x() > size().width() || event->pos().y() > size().height())
return;
Q_OBJECT
public:
- ClickableLabel(QWidget *parent = nullptr);
+ ClickableLabel(QWidget* parent = nullptr);
signals:
void clicked();
protected:
- void mouseReleaseEvent(QMouseEvent *event) override;
+ void mouseReleaseEvent(QMouseEvent* event) override;
};
#include <QStyle>
#include <QStyleOptionFrame>
-
-ColorButton::ColorButton(QWidget *parent) : QToolButton(parent)
+ColorButton::ColorButton(QWidget* parent)
+ : QToolButton(parent)
{
setText("");
connect(this, &QAbstractButton::clicked, this, &ColorButton::chooseColor);
}
-
-void ColorButton::setColor(const QColor &color)
+void ColorButton::setColor(const QColor& color)
{
_color = color;
QPixmap pixmap(QSize(32, 32));
emit colorChanged(color);
}
-
QColor ColorButton::color() const
{
return _color;
}
-
void ColorButton::chooseColor()
{
QColor c = QColorDialog::getColor(color(), this);
Q_OBJECT
Q_PROPERTY(QColor color READ color WRITE setColor USER true)
-public :
- explicit ColorButton(QWidget *parent = nullptr);
- explicit ColorButton(const QColor &c, QWidget *parent = nullptr);
+public:
+ explicit ColorButton(QWidget* parent = nullptr);
+ explicit ColorButton(const QColor& c, QWidget* parent = nullptr);
- void setColor(const QColor &color);
+ void setColor(const QColor& color);
QColor color() const;
signals:
- void colorChanged(const QColor &);
+ void colorChanged(const QColor&);
private slots:
void chooseColor();
#include "contextmenuactionprovider.h"
#include <QInputDialog>
+#include <QMap>
#include <QMenu>
#include <QMessageBox>
-#include <QMap>
#include "buffermodel.h"
#include "buffersettings.h"
#include "network.h"
#include "util.h"
-ContextMenuActionProvider::ContextMenuActionProvider(QObject *parent) : NetworkModelController(parent)
+ContextMenuActionProvider::ContextMenuActionProvider(QObject* parent)
+ : NetworkModelController(parent)
{
registerAction(NetworkConnect, icon::get("network-connect"), tr("Connect"));
registerAction(NetworkDisconnect, icon::get("network-disconnect"), tr("Disconnect"));
registerAction(ShowNetworkConfig, tr("Configure"));
registerAction(ShowIgnoreList, tr("Show Ignore List"));
- auto *hideEventsMenu = new QMenu();
+ auto* hideEventsMenu = new QMenu();
hideEventsMenu->addAction(action(HideJoinPartQuit));
hideEventsMenu->addSeparator();
hideEventsMenu->addAction(action(HideJoin));
_hideEventsMenuAction = new Action(tr("Hide Events"), nullptr);
_hideEventsMenuAction->setMenu(hideEventsMenu);
- auto *nickCtcpMenu = new QMenu();
+ auto* nickCtcpMenu = new QMenu();
nickCtcpMenu->addAction(action(NickCtcpPing));
nickCtcpMenu->addAction(action(NickCtcpVersion));
nickCtcpMenu->addAction(action(NickCtcpTime));
_nickCtcpMenuAction = new Action(tr("CTCP"), nullptr);
_nickCtcpMenuAction->setMenu(nickCtcpMenu);
- auto *nickModeMenu = new QMenu();
+ auto* nickModeMenu = new QMenu();
nickModeMenu->addAction(action(NickOp));
nickModeMenu->addAction(action(NickDeop));
// this is where the halfops will be placed if available
_nickModeMenuAction = new Action(tr("Actions"), nullptr);
_nickModeMenuAction->setMenu(nickModeMenu);
- auto *ignoreMenu = new QMenu();
+ auto* ignoreMenu = new QMenu();
_nickIgnoreMenuAction = new Action(tr("Ignore"), nullptr);
_nickIgnoreMenuAction->setMenu(ignoreMenu);
// They don't need any of the Action fancyness so we use plain QActions
_ignoreDescriptions << new QAction(tr("Add Ignore Rule"), this);
_ignoreDescriptions << new QAction(tr("Existing Rules"), this);
- foreach(QAction *act, _ignoreDescriptions)
- act->setEnabled(false);
+ foreach (QAction* act, _ignoreDescriptions)
+ act->setEnabled(false);
}
-
ContextMenuActionProvider::~ContextMenuActionProvider()
{
_hideEventsMenuAction->menu()->deleteLater();
_ignoreDescriptions.clear();
}
-
-void ContextMenuActionProvider::addActions(QMenu *menu, BufferId bufId, ActionSlot slot)
+void ContextMenuActionProvider::addActions(QMenu* menu, BufferId bufId, ActionSlot slot)
{
if (!bufId.isValid())
return;
addActions(menu, Client::networkModel()->bufferIndex(bufId), std::move(slot));
}
-
-void ContextMenuActionProvider::addActions(QMenu *menu, const QModelIndex &index, ActionSlot slot, bool isCustomBufferView)
+void ContextMenuActionProvider::addActions(QMenu* menu, const QModelIndex& index, ActionSlot slot, bool isCustomBufferView)
{
if (!index.isValid())
return;
addActions(menu, QList<QModelIndex>() << index, nullptr, QString(), std::move(slot), isCustomBufferView);
}
-
-void ContextMenuActionProvider::addActions(QMenu *menu, MessageFilter *filter, BufferId msgBuffer, ActionSlot slot)
+void ContextMenuActionProvider::addActions(QMenu* menu, MessageFilter* filter, BufferId msgBuffer, ActionSlot slot)
{
addActions(menu, filter, msgBuffer, QString(), std::move(slot));
}
-
-void ContextMenuActionProvider::addActions(QMenu *menu, MessageFilter *filter, BufferId msgBuffer, const QString &chanOrNick, ActionSlot slot)
+void ContextMenuActionProvider::addActions(QMenu* menu, MessageFilter* filter, BufferId msgBuffer, const QString& chanOrNick, ActionSlot slot)
{
if (!filter)
return;
addActions(menu, QList<QModelIndex>() << Client::networkModel()->bufferIndex(msgBuffer), filter, chanOrNick, std::move(slot), false);
}
-
-void ContextMenuActionProvider::addActions(QMenu *menu, const QList<QModelIndex> &indexList, ActionSlot slot, bool isCustomBufferView)
+void ContextMenuActionProvider::addActions(QMenu* menu, const QList<QModelIndex>& indexList, ActionSlot slot, bool isCustomBufferView)
{
addActions(menu, indexList, nullptr, QString(), std::move(slot), isCustomBufferView);
}
-
// add a list of actions sensible for the current item(s)
-void ContextMenuActionProvider::addActions(QMenu *menu,
- const QList<QModelIndex> &indexList_,
- MessageFilter *filter_,
- const QString &contextItem_,
+void ContextMenuActionProvider::addActions(QMenu* menu,
+ const QList<QModelIndex>& indexList_,
+ MessageFilter* filter_,
+ const QString& contextItem_,
ActionSlot actionSlot,
bool isCustomBufferView)
{
}
}
-
-void ContextMenuActionProvider::addNetworkItemActions(QMenu *menu, const QModelIndex &index)
+void ContextMenuActionProvider::addNetworkItemActions(QMenu* menu, const QModelIndex& index)
{
NetworkId networkId = index.data(NetworkModel::NetworkIdRole).value<NetworkId>();
if (!networkId.isValid())
return;
- const Network *network = Client::network(networkId);
+ const Network* network = Client::network(networkId);
Q_CHECK_PTR(network);
if (!network)
return;
addAction(JoinChannel, menu, index, ActiveState);
}
-
-void ContextMenuActionProvider::addBufferItemActions(QMenu *menu, const QModelIndex &index, bool isCustomBufferView)
+void ContextMenuActionProvider::addBufferItemActions(QMenu* menu, const QModelIndex& index, bool isCustomBufferView)
{
BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
addAction(BufferRemove, menu, index, InactiveState);
break;
- case BufferInfo::QueryBuffer:
- {
- //IrcUser *ircUser = qobject_cast<IrcUser *>(index.data(NetworkModel::IrcUserRole).value<QObject *>());
- //if(ircUser) {
+ case BufferInfo::QueryBuffer: {
+ // IrcUser *ircUser = qobject_cast<IrcUser *>(index.data(NetworkModel::IrcUserRole).value<QObject *>());
+ // if(ircUser) {
addIrcUserActions(menu, index);
menu->addSeparator();
//}
}
}
-
-void ContextMenuActionProvider::addIrcUserActions(QMenu *menu, const QModelIndex &index)
+void ContextMenuActionProvider::addIrcUserActions(QMenu* menu, const QModelIndex& index)
{
// this can be called: a) as a nicklist context menu (index has IrcUserItemType)
// b) as a query buffer context menu (index has BufferItemType and is a QueryBufferItem)
addAction(_nickModeMenuAction, menu, itemType == NetworkModel::IrcUserItemType);
addAction(_nickCtcpMenuAction, menu);
- auto *ircUser = qobject_cast<IrcUser *>(index.data(NetworkModel::IrcUserRole).value<QObject *>());
+ auto* ircUser = qobject_cast<IrcUser*>(index.data(NetworkModel::IrcUserRole).value<QObject*>());
if (ircUser) {
- Network *network = ircUser->network();
+ Network* network = ircUser->network();
// only show entries for usermode +h if server supports it
if (network && network->prefixModes().contains('h')) {
action(NickHalfop)->setVisible(true);
BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
if (bufferInfo.type() == BufferInfo::ChannelBuffer)
bufferName = bufferInfo.bufferName();
- QMap<QString, bool> ignoreMap = Client::ignoreListManager()->matchingRulesForHostmask(ircUser->hostmask(), ircUser->network()->networkName(), bufferName);
+ QMap<QString, bool> ignoreMap = Client::ignoreListManager()->matchingRulesForHostmask(ircUser->hostmask(),
+ ircUser->network()->networkName(),
+ bufferName);
addIgnoreMenu(menu, ircUser->hostmask(), ignoreMap);
// end of ignoreliststuff
}
}
}
-
-Action *ContextMenuActionProvider::addAction(ActionType type, QMenu *menu, const QModelIndex &index, ItemActiveStates requiredActiveState)
+Action* ContextMenuActionProvider::addAction(ActionType type, QMenu* menu, const QModelIndex& index, ItemActiveStates requiredActiveState)
{
return addAction(action(type), menu, checkRequirements(index, requiredActiveState));
}
-
-Action *ContextMenuActionProvider::addAction(Action *action, QMenu *menu, const QModelIndex &index, ItemActiveStates requiredActiveState)
+Action* ContextMenuActionProvider::addAction(Action* action, QMenu* menu, const QModelIndex& index, ItemActiveStates requiredActiveState)
{
return addAction(action, menu, checkRequirements(index, requiredActiveState));
}
-
-Action *ContextMenuActionProvider::addAction(ActionType type, QMenu *menu, bool condition)
+Action* ContextMenuActionProvider::addAction(ActionType type, QMenu* menu, bool condition)
{
return addAction(action(type), menu, condition);
}
-
-Action *ContextMenuActionProvider::addAction(Action *action, QMenu *menu, bool condition)
+Action* ContextMenuActionProvider::addAction(Action* action, QMenu* menu, bool condition)
{
if (condition) {
menu->addAction(action);
return action;
}
-
-void ContextMenuActionProvider::addHideEventsMenu(QMenu *menu, BufferId bufferId)
+void ContextMenuActionProvider::addHideEventsMenu(QMenu* menu, BufferId bufferId)
{
if (BufferSettings(bufferId).hasFilter())
addHideEventsMenu(menu, BufferSettings(bufferId).messageFilter());
addHideEventsMenu(menu);
}
-
-void ContextMenuActionProvider::addHideEventsMenu(QMenu *menu, MessageFilter *msgFilter)
+void ContextMenuActionProvider::addHideEventsMenu(QMenu* menu, MessageFilter* msgFilter)
{
if (BufferSettings(msgFilter->idString()).hasFilter())
addHideEventsMenu(menu, BufferSettings(msgFilter->idString()).messageFilter());
addHideEventsMenu(menu);
}
-
-void ContextMenuActionProvider::addHideEventsMenu(QMenu *menu, int filter)
+void ContextMenuActionProvider::addHideEventsMenu(QMenu* menu, int filter)
{
action(HideApplyToAll)->setEnabled(filter != -1);
action(HideUseDefaults)->setEnabled(filter != -1);
menu->addAction(_hideEventsMenuAction);
}
-
-void ContextMenuActionProvider::addIgnoreMenu(QMenu *menu, const QString &hostmask, const QMap<QString, bool> &ignoreMap)
+void ContextMenuActionProvider::addIgnoreMenu(QMenu* menu, const QString& hostmask, const QMap<QString, bool>& ignoreMap)
{
- QMenu *ignoreMenu = _nickIgnoreMenuAction->menu();
+ QMenu* ignoreMenu = _nickIgnoreMenuAction->menu();
ignoreMenu->clear();
QString nick = nickFromMask(hostmask);
QString ident = userFromMask(hostmask);
action(NickIgnoreHost)->setText(text);
action(NickIgnoreHost)->setProperty("ignoreRule", text);
- text = domain.at(0) == '.' ? QString("*!%1@*%2").arg(ident, domain)
- : QString("*!%1@%2").arg(ident, domain);
+ text = domain.at(0) == '.' ? QString("*!%1@*%2").arg(ident, domain) : QString("*!%1@%2").arg(ident, domain);
action(NickIgnoreDomain)->setText(text);
action(NickIgnoreDomain)->setProperty("ignoreRule", text);
ignoreMenu->addAction(_ignoreDescriptions.at(1));
while (ruleIter != ignoreMap.constEnd()) {
if (counter < 5) {
- auto type = static_cast<ActionType>(NickIgnoreToggleEnabled0 + counter*0x100000);
- Action *act = action(type);
+ auto type = static_cast<ActionType>(NickIgnoreToggleEnabled0 + counter * 0x100000);
+ Action* act = action(type);
act->setText(ruleIter.key());
act->setProperty("ignoreRule", ruleIter.key());
act->setChecked(ruleIter.value());
Q_OBJECT
public:
- ContextMenuActionProvider(QObject *parent = nullptr);
+ ContextMenuActionProvider(QObject* parent = nullptr);
~ContextMenuActionProvider() override;
//! Provide a list of actions applying to the given item
* @return A list of actions applying to the given item
*/
template<typename Receiver, typename Slot>
- void addActions(QMenu *menu, const QModelIndex &index, Receiver *receiver, Slot slot, bool isCustomBufferView = false)
+ void addActions(QMenu* menu, const QModelIndex& index, Receiver* receiver, Slot slot, bool isCustomBufferView = false)
{
addActions(menu, index, buildActionSlot(receiver, std::move(slot)), isCustomBufferView);
}
- void addActions(QMenu *menu, const QModelIndex &index, ActionSlot = {}, bool isCustomBufferView = false);
+ void addActions(QMenu* menu, const QModelIndex& index, ActionSlot = {}, bool isCustomBufferView = false);
template<typename Receiver, typename Slot>
- void addActions(QMenu *menu, const QList<QModelIndex> &indexList, Receiver *receiver, Slot slot, bool isCustomBufferView = false)
+ void addActions(QMenu* menu, const QList<QModelIndex>& indexList, Receiver* receiver, Slot slot, bool isCustomBufferView = false)
{
addActions(menu, indexList, buildActionSlot(receiver, std::move(slot)), isCustomBufferView);
}
- void addActions(QMenu *menu, const QList<QModelIndex> &indexList, ActionSlot = {}, bool isCustomBufferView = false);
+ void addActions(QMenu* menu, const QList<QModelIndex>& indexList, ActionSlot = {}, bool isCustomBufferView = false);
template<typename Receiver, typename Slot>
- void addActions(QMenu *menu, BufferId id, Receiver *receiver, Slot slot)
+ void addActions(QMenu* menu, BufferId id, Receiver* receiver, Slot slot)
{
addActions(menu, id, buildActionSlot(receiver, std::move(slot)));
}
- void addActions(QMenu *menu, BufferId id, ActionSlot = {});
+ void addActions(QMenu* menu, BufferId id, ActionSlot = {});
template<typename Receiver, typename Slot>
- void addActions(QMenu *menu, MessageFilter *filter, BufferId msgBuffer, Receiver *receiver, Slot slot)
+ void addActions(QMenu* menu, MessageFilter* filter, BufferId msgBuffer, Receiver* receiver, Slot slot)
{
addActions(menu, filter, msgBuffer, buildActionSlot(receiver, std::move(slot)));
}
- void addActions(QMenu *menu, MessageFilter *filter, BufferId msgBuffer, ActionSlot = {});
+ void addActions(QMenu* menu, MessageFilter* filter, BufferId msgBuffer, ActionSlot = {});
template<typename Receiver, typename Slot>
- void addActions(QMenu *menu, MessageFilter *filter, BufferId msgBuffer, const QString &chanOrNick, Receiver *receiver, Slot slot)
+ void addActions(QMenu* menu, MessageFilter* filter, BufferId msgBuffer, const QString& chanOrNick, Receiver* receiver, Slot slot)
{
addActions(menu, filter, msgBuffer, chanOrNick, buildActionSlot(receiver, std::move(slot)));
}
- void addActions(QMenu *menu, MessageFilter *filter, BufferId msgBuffer, const QString &chanOrNick, ActionSlot = {});
+ void addActions(QMenu* menu, MessageFilter* filter, BufferId msgBuffer, const QString& chanOrNick, ActionSlot = {});
private:
- void addActions(QMenu *menu, const QList<QModelIndex> &indexList, MessageFilter *filter, const QString &chanOrNick, ActionSlot actionSlot, bool isCustomBufferView);
-
- Action *addAction(ActionType, QMenu *, bool condition = true);
- Action *addAction(Action *, QMenu *, bool condition = true);
- Action *addAction(ActionType, QMenu *, const QModelIndex &index, ItemActiveStates requiredActiveState = QFlags<ItemActiveState>(ActiveState | InactiveState));
- Action *addAction(Action *, QMenu *, const QModelIndex &index, ItemActiveStates requiredActiveState = QFlags<ItemActiveState>(ActiveState | InactiveState));
-
- void addHideEventsMenu(QMenu *, BufferId bufferId);
- void addHideEventsMenu(QMenu *, MessageFilter *msgFilter);
- void addHideEventsMenu(QMenu *, int filter = -1);
- void addIgnoreMenu(QMenu *menu, const QString &hostmask, const QMap<QString, bool> &ignoreMap);
-
- void addNetworkItemActions(QMenu *, const QModelIndex &);
- void addBufferItemActions(QMenu *, const QModelIndex &, bool isCustomBufferView = false);
- void addIrcUserActions(QMenu *, const QModelIndex &);
-
- Action *_hideEventsMenuAction;
- Action *_nickCtcpMenuAction;
- Action *_nickModeMenuAction;
- Action *_nickIgnoreMenuAction;
- QList<QAction *> _ignoreDescriptions;
+ void addActions(QMenu* menu,
+ const QList<QModelIndex>& indexList,
+ MessageFilter* filter,
+ const QString& chanOrNick,
+ ActionSlot actionSlot,
+ bool isCustomBufferView);
+
+ Action* addAction(ActionType, QMenu*, bool condition = true);
+ Action* addAction(Action*, QMenu*, bool condition = true);
+ Action* addAction(ActionType,
+ QMenu*,
+ const QModelIndex& index,
+ ItemActiveStates requiredActiveState = QFlags<ItemActiveState>(ActiveState | InactiveState));
+ Action* addAction(Action*,
+ QMenu*,
+ const QModelIndex& index,
+ ItemActiveStates requiredActiveState = QFlags<ItemActiveState>(ActiveState | InactiveState));
+
+ void addHideEventsMenu(QMenu*, BufferId bufferId);
+ void addHideEventsMenu(QMenu*, MessageFilter* msgFilter);
+ void addHideEventsMenu(QMenu*, int filter = -1);
+ void addIgnoreMenu(QMenu* menu, const QString& hostmask, const QMap<QString, bool>& ignoreMap);
+
+ void addNetworkItemActions(QMenu*, const QModelIndex&);
+ void addBufferItemActions(QMenu*, const QModelIndex&, bool isCustomBufferView = false);
+ void addIrcUserActions(QMenu*, const QModelIndex&);
+
+ Action* _hideEventsMenuAction;
+ Action* _nickCtcpMenuAction;
+ Action* _nickModeMenuAction;
+ Action* _nickIgnoreMenuAction;
+ QList<QAction*> _ignoreDescriptions;
};
#include "flatproxymodel.h"
-#include <QItemSelection>
#include <QDebug>
+#include <QItemSelection>
-FlatProxyModel::FlatProxyModel(QObject *parent)
+FlatProxyModel::FlatProxyModel(QObject* parent)
: QAbstractProxyModel(parent)
-{
-}
-
+{}
-QModelIndex FlatProxyModel::mapFromSource(const QModelIndex &sourceIndex) const
+QModelIndex FlatProxyModel::mapFromSource(const QModelIndex& sourceIndex) const
{
if (!sourceIndex.isValid())
return {};
- SourceItem *sourceItem = sourceToInternal(sourceIndex);
+ SourceItem* sourceItem = sourceToInternal(sourceIndex);
Q_ASSERT(sourceItem);
return createIndex(sourceItem->pos(), sourceIndex.column(), sourceItem);
}
-
-QModelIndex FlatProxyModel::mapToSource(const QModelIndex &proxyIndex) const
+QModelIndex FlatProxyModel::mapToSource(const QModelIndex& proxyIndex) const
{
if (!proxyIndex.isValid())
return {};
int row = proxyIndex.row();
QModelIndex sourceParent;
- SourceItem *sourceItem = _rootSourceItem->findChild(row);
+ SourceItem* sourceItem = _rootSourceItem->findChild(row);
while (sourceItem) {
if (sourceItem->pos() == row) {
return sourceModel()->index(sourceItem->sourceRow(), proxyIndex.column(), sourceParent);
qWarning() << "FlatProxyModel::mapToSource(): couldn't find source index for" << proxyIndex;
Q_ASSERT(false);
- return {}; // make compilers happy :)
+ return {}; // make compilers happy :)
}
-
-bool FlatProxyModel::_RangeRect::operator<(const FlatProxyModel::_RangeRect &other) const
+bool FlatProxyModel::_RangeRect::operator<(const FlatProxyModel::_RangeRect& other) const
{
if (left != other.left)
return left < other.left;
return bottom < other.bottom;
}
-
-QItemSelection FlatProxyModel::mapSelectionFromSource(const QItemSelection &sourceSelection) const
+QItemSelection FlatProxyModel::mapSelectionFromSource(const QItemSelection& sourceSelection) const
{
QList<_RangeRect> newRanges;
- QHash<QModelIndex, SourceItem *> itemLookup;
+ QHash<QModelIndex, SourceItem*> itemLookup;
// basics steps of the loop:
// 1. convert each source ItemSelectionRange to a mapped Range (internal one for easier post processing)
// 2. insert it into the list of previously mapped Ranges sorted by top location
for (int i = 0; i < sourceSelection.count(); i++) {
- const QItemSelectionRange ¤tRange = sourceSelection[i];
+ const QItemSelectionRange& currentRange = sourceSelection[i];
QModelIndex currentParent = currentRange.topLeft().parent();
Q_ASSERT(currentParent == currentRange.bottomRight().parent());
- SourceItem *parentItem = nullptr;
+ SourceItem* parentItem = nullptr;
if (!itemLookup.contains(currentParent)) {
parentItem = sourceToInternal(currentParent);
itemLookup[currentParent] = parentItem;
parentItem = itemLookup[currentParent];
}
- _RangeRect newRange = { currentRange.topLeft().column(), currentRange.bottomRight().column(),
- currentRange.topLeft().row(), currentRange.bottomRight().row(),
- parentItem->child(currentRange.topLeft().row()), parentItem->child(currentRange.bottomRight().row()) };
+ _RangeRect newRange = {currentRange.topLeft().column(),
+ currentRange.bottomRight().column(),
+ currentRange.topLeft().row(),
+ currentRange.bottomRight().row(),
+ parentItem->child(currentRange.topLeft().row()),
+ parentItem->child(currentRange.bottomRight().row())};
if (newRanges.isEmpty()) {
newRanges << newRange;
continue;
}
- _RangeRect &first = newRanges[0];
+ _RangeRect& first = newRanges[0];
if (newRange < first) {
newRanges.prepend(newRange);
continue;
bool inserted = false;
for (int j = 0; j < newRanges.count() - 1; j++) {
- _RangeRect &a = newRanges[j];
- _RangeRect &b = newRanges[j + 1];
+ _RangeRect& a = newRanges[j];
+ _RangeRect& b = newRanges[j + 1];
if (a < newRange && newRange < b) {
newRanges[j + 1] = newRange;
if (inserted)
continue;
- _RangeRect &last = newRanges[newRanges.count() - 1];
+ _RangeRect& last = newRanges[newRanges.count() - 1];
if (last < newRange) {
newRanges.append(newRange);
continue;
// we've got a sorted list of ranges now. so we can easily check if there is a possibility to merge
for (int i = newRanges.count() - 1; i > 0; i--) {
- _RangeRect &a = newRanges[i - 1];
- _RangeRect &b = newRanges[i];
+ _RangeRect& a = newRanges[i - 1];
+ _RangeRect& b = newRanges[i];
if (a.left != b.left || a.right != b.right)
continue;
if (b.bottom > a.bottom) {
a.bottom = b.bottom;
a.bottomItem = b.bottomItem;
- } // otherwise b is totally enclosed in a -> nothing to do but drop b.
+ } // otherwise b is totally enclosed in a -> nothing to do but drop b.
newRanges.removeAt(i);
}
QItemSelection proxySelection;
for (int i = 0; i < newRanges.count(); i++) {
- _RangeRect &r = newRanges[i];
+ _RangeRect& r = newRanges[i];
proxySelection << QItemSelectionRange(createIndex(r.top, r.left, r.topItem), createIndex(r.bottom, r.right, r.bottomItem));
}
return proxySelection;
}
-
-QItemSelection FlatProxyModel::mapSelectionToSource(const QItemSelection &proxySelection) const
+QItemSelection FlatProxyModel::mapSelectionToSource(const QItemSelection& proxySelection) const
{
QItemSelection sourceSelection;
for (int i = 0; i < proxySelection.count(); i++) {
- const QItemSelectionRange &range = proxySelection[i];
+ const QItemSelectionRange& range = proxySelection[i];
- SourceItem *topLeftItem = nullptr;
- SourceItem *bottomRightItem = nullptr;
- auto *currentItem = static_cast<SourceItem *>(range.topLeft().internalPointer());
+ SourceItem* topLeftItem = nullptr;
+ SourceItem* bottomRightItem = nullptr;
+ auto* currentItem = static_cast<SourceItem*>(range.topLeft().internalPointer());
int row = range.topLeft().row();
int left = range.topLeft().column();
int right = range.bottomRight().column();
}
else {
Q_ASSERT(topLeftItem && bottomRightItem);
- sourceSelection << QItemSelectionRange(mapToSource(createIndex(topLeftItem->pos(), left, topLeftItem)), mapToSource(createIndex(bottomRightItem->pos(), right, bottomRightItem)));
+ sourceSelection << QItemSelectionRange(mapToSource(createIndex(topLeftItem->pos(), left, topLeftItem)),
+ mapToSource(createIndex(bottomRightItem->pos(), right, bottomRightItem)));
topLeftItem = nullptr;
bottomRightItem = nullptr;
}
row++;
}
- if (topLeftItem && bottomRightItem) { // there should be one range left.
- sourceSelection << QItemSelectionRange(mapToSource(createIndex(topLeftItem->pos(), left, topLeftItem)), mapToSource(createIndex(bottomRightItem->pos(), right, bottomRightItem)));
+ if (topLeftItem && bottomRightItem) { // there should be one range left.
+ sourceSelection << QItemSelectionRange(mapToSource(createIndex(topLeftItem->pos(), left, topLeftItem)),
+ mapToSource(createIndex(bottomRightItem->pos(), right, bottomRightItem)));
}
}
return sourceSelection;
}
-
-void FlatProxyModel::setSourceModel(QAbstractItemModel *sourceModel)
+void FlatProxyModel::setSourceModel(QAbstractItemModel* sourceModel)
{
if (QAbstractProxyModel::sourceModel()) {
disconnect(QAbstractProxyModel::sourceModel(), nullptr, this, nullptr);
emit layoutChanged();
if (sourceModel) {
- connect(sourceModel, &QAbstractItemModel::columnsAboutToBeInserted,
- this, &FlatProxyModel::on_columnsAboutToBeInserted);
- connect(sourceModel, &QAbstractItemModel::columnsAboutToBeRemoved,
- this, &FlatProxyModel::on_columnsAboutToBeRemoved);
- connect(sourceModel, &QAbstractItemModel::columnsInserted,
- this, &FlatProxyModel::on_columnsInserted);
- connect(sourceModel, &QAbstractItemModel::columnsRemoved,
- this, &FlatProxyModel::on_columnsRemoved);
-
- connect(sourceModel, &QAbstractItemModel::dataChanged,
- this, &FlatProxyModel::on_dataChanged);
+ connect(sourceModel, &QAbstractItemModel::columnsAboutToBeInserted, this, &FlatProxyModel::on_columnsAboutToBeInserted);
+ connect(sourceModel, &QAbstractItemModel::columnsAboutToBeRemoved, this, &FlatProxyModel::on_columnsAboutToBeRemoved);
+ connect(sourceModel, &QAbstractItemModel::columnsInserted, this, &FlatProxyModel::on_columnsInserted);
+ connect(sourceModel, &QAbstractItemModel::columnsRemoved, this, &FlatProxyModel::on_columnsRemoved);
+
+ connect(sourceModel, &QAbstractItemModel::dataChanged, this, &FlatProxyModel::on_dataChanged);
// on_headerDataChanged(Qt::Orientation orientation, int first, int last)
- connect(sourceModel, &QAbstractItemModel::layoutAboutToBeChanged,
- this, &FlatProxyModel::on_layoutAboutToBeChanged);
- connect(sourceModel, &QAbstractItemModel::layoutChanged,
- this, &FlatProxyModel::on_layoutChanged);
+ connect(sourceModel, &QAbstractItemModel::layoutAboutToBeChanged, this, &FlatProxyModel::on_layoutAboutToBeChanged);
+ connect(sourceModel, &QAbstractItemModel::layoutChanged, this, &FlatProxyModel::on_layoutChanged);
- connect(sourceModel, &QAbstractItemModel::modelAboutToBeReset,
- this, &FlatProxyModel::on_modelAboutToBeReset);
+ connect(sourceModel, &QAbstractItemModel::modelAboutToBeReset, this, &FlatProxyModel::on_modelAboutToBeReset);
// void on_modelReset()
- connect(sourceModel, &QAbstractItemModel::rowsAboutToBeInserted,
- this, &FlatProxyModel::on_rowsAboutToBeInserted);
- connect(sourceModel, &QAbstractItemModel::rowsAboutToBeRemoved,
- this, &FlatProxyModel::on_rowsAboutToBeRemoved);
- connect(sourceModel, &QAbstractItemModel::rowsInserted,
- this, &FlatProxyModel::on_rowsInserted);
- connect(sourceModel, &QAbstractItemModel::rowsRemoved,
- this, &FlatProxyModel::on_rowsRemoved);
+ connect(sourceModel, &QAbstractItemModel::rowsAboutToBeInserted, this, &FlatProxyModel::on_rowsAboutToBeInserted);
+ connect(sourceModel, &QAbstractItemModel::rowsAboutToBeRemoved, this, &FlatProxyModel::on_rowsAboutToBeRemoved);
+ connect(sourceModel, &QAbstractItemModel::rowsInserted, this, &FlatProxyModel::on_rowsInserted);
+ connect(sourceModel, &QAbstractItemModel::rowsRemoved, this, &FlatProxyModel::on_rowsRemoved);
}
}
-
-void FlatProxyModel::insertSubTree(const QModelIndex &source_idx, bool emitInsert)
+void FlatProxyModel::insertSubTree(const QModelIndex& source_idx, bool emitInsert)
{
- SourceItem *newSubTree = new SourceItem(source_idx.row(), sourceToInternal(sourceModel()->parent(source_idx)));
+ SourceItem* newSubTree = new SourceItem(source_idx.row(), sourceToInternal(sourceModel()->parent(source_idx)));
if (newSubTree->parent()) {
newSubTree->setPos(newSubTree->parent()->pos() + source_idx.row() + 1);
}
- SourceItem *lastItem = insertSubTreeHelper(newSubTree, newSubTree, source_idx);
+ SourceItem* lastItem = insertSubTreeHelper(newSubTree, newSubTree, source_idx);
Q_ASSERT(lastItem);
Q_ASSERT(lastItem->next() == nullptr);
if (newSubTree->parent()) {
if (newSubTree->parent()->childCount() > source_idx.row()) {
- SourceItem *next = newSubTree->parent()->child(source_idx.row());
+ SourceItem* next = newSubTree->parent()->child(source_idx.row());
lastItem->setNext(next);
int nextPos = lastItem->pos() + 1;
while (next) {
}
}
if (source_idx.row() > 0) {
- SourceItem *previous = newSubTree->parent()->child(source_idx.row() - 1);
+ SourceItem* previous = newSubTree->parent()->child(source_idx.row() - 1);
while (previous->childCount() > 0) {
previous = previous->child(previous->childCount() - 1);
}
endInsertRows();
}
-
-FlatProxyModel::SourceItem *FlatProxyModel::insertSubTreeHelper(SourceItem *parentItem, SourceItem *lastItem_, const QModelIndex &source_idx)
+FlatProxyModel::SourceItem* FlatProxyModel::insertSubTreeHelper(SourceItem* parentItem, SourceItem* lastItem_, const QModelIndex& source_idx)
{
- SourceItem *lastItem = lastItem_;
- SourceItem *newItem = nullptr;
+ SourceItem* lastItem = lastItem_;
+ SourceItem* newItem = nullptr;
for (int row = 0; row < sourceModel()->rowCount(source_idx); row++) {
newItem = new SourceItem(row, parentItem);
newItem->setPos(lastItem->pos() + 1);
return lastItem;
}
-
-void FlatProxyModel::removeSubTree(const QModelIndex &source_idx, bool emitRemove)
+void FlatProxyModel::removeSubTree(const QModelIndex& source_idx, bool emitRemove)
{
- SourceItem *sourceItem = sourceToInternal(source_idx);
+ SourceItem* sourceItem = sourceToInternal(source_idx);
if (!sourceItem)
return;
- SourceItem *prevItem = sourceItem->parent();
+ SourceItem* prevItem = sourceItem->parent();
if (sourceItem->sourceRow() > 0) {
prevItem = prevItem->child(sourceItem->sourceRow() - 1);
while (prevItem->childCount() > 0) {
}
}
- SourceItem *lastItem = sourceItem;
+ SourceItem* lastItem = sourceItem;
while (lastItem->childCount() > 0) {
lastItem = lastItem->child(lastItem->childCount() - 1);
}
nextPos = prevItem->pos() + 1;
}
- SourceItem *nextItem = lastItem->next();
+ SourceItem* nextItem = lastItem->next();
while (nextItem) {
nextItem->setPos(nextPos);
nextPos++;
endRemoveRows();
}
-
-QModelIndex FlatProxyModel::index(int row, int column, const QModelIndex &parent) const
+QModelIndex FlatProxyModel::index(int row, int column, const QModelIndex& parent) const
{
if (parent.isValid()) {
qWarning() << "FlatProxyModel::index() called with valid parent:" << parent;
return {};
}
- SourceItem *item = _rootSourceItem;
+ SourceItem* item = _rootSourceItem;
while (item->pos() != row) {
item = item->findChild(row);
if (!item) {
return createIndex(row, column, item);
}
-
-QModelIndex FlatProxyModel::parent(const QModelIndex &index) const
+QModelIndex FlatProxyModel::parent(const QModelIndex& index) const
{
Q_UNUSED(index)
// this is a flat model
return {};
}
-
-int FlatProxyModel::rowCount(const QModelIndex &index) const
+int FlatProxyModel::rowCount(const QModelIndex& index) const
{
if (!_rootSourceItem)
return 0;
if (index.isValid())
return 0;
- SourceItem *item = _rootSourceItem;
+ SourceItem* item = _rootSourceItem;
while (item->childCount() > 0) {
item = item->child(item->childCount() - 1);
}
return item->pos() + 1;
}
-
-int FlatProxyModel::columnCount(const QModelIndex &index) const
+int FlatProxyModel::columnCount(const QModelIndex& index) const
{
Q_UNUSED(index)
if (!sourceModel()) {
}
}
-
-FlatProxyModel::SourceItem *FlatProxyModel::sourceToInternal(const QModelIndex &sourceIndex) const
+FlatProxyModel::SourceItem* FlatProxyModel::sourceToInternal(const QModelIndex& sourceIndex) const
{
QList<int> childPath;
for (QModelIndex idx = sourceIndex; idx.isValid(); idx = sourceModel()->parent(idx)) {
Q_ASSERT(!sourceIndex.isValid() || !childPath.isEmpty());
- SourceItem *item = _rootSourceItem;
+ SourceItem* item = _rootSourceItem;
for (int i = 0; i < childPath.count(); i++) {
item = item->child(childPath[i]);
}
return item;
}
-
-void FlatProxyModel::on_columnsAboutToBeInserted(const QModelIndex &parent, int start, int end)
+void FlatProxyModel::on_columnsAboutToBeInserted(const QModelIndex& parent, int start, int end)
{
Q_UNUSED(parent);
beginInsertColumns(QModelIndex(), start, end);
}
-
-void FlatProxyModel::on_columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
+void FlatProxyModel::on_columnsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
Q_UNUSED(parent);
beginRemoveColumns(QModelIndex(), start, end);
}
-
-void FlatProxyModel::on_columnsInserted(const QModelIndex &parent, int start, int end)
+void FlatProxyModel::on_columnsInserted(const QModelIndex& parent, int start, int end)
{
Q_UNUSED(parent);
Q_UNUSED(start);
endInsertColumns();
}
-
-void FlatProxyModel::on_columnsRemoved(const QModelIndex &parent, int start, int end)
+void FlatProxyModel::on_columnsRemoved(const QModelIndex& parent, int start, int end)
{
Q_UNUSED(parent);
Q_UNUSED(start);
endRemoveRows();
}
-
-void FlatProxyModel::on_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
+void FlatProxyModel::on_dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
{
Q_ASSERT(sourceModel());
Q_ASSERT(sourceModel()->parent(topLeft) == sourceModel()->parent(bottomRight));
- SourceItem *topLeftItem = sourceToInternal(topLeft);
+ SourceItem* topLeftItem = sourceToInternal(topLeft);
Q_ASSERT(topLeftItem);
Q_ASSERT(topLeftItem->parent()->childCount() > bottomRight.row());
QModelIndex proxyTopLeft = createIndex(topLeftItem->pos(), topLeft.column(), topLeftItem);
- QModelIndex proxyBottomRight = createIndex(topLeftItem->pos() + bottomRight.row() - topLeft.row(), bottomRight.column(), topLeftItem->parent()->child(bottomRight.row()));
+ QModelIndex proxyBottomRight = createIndex(topLeftItem->pos() + bottomRight.row() - topLeft.row(),
+ bottomRight.column(),
+ topLeftItem->parent()->child(bottomRight.row()));
emit dataChanged(proxyTopLeft, proxyBottomRight);
}
-
void FlatProxyModel::on_layoutAboutToBeChanged()
{
emit layoutAboutToBeChanged();
removeSubTree(QModelIndex(), false /* don't emit removeRows() */);
}
-
void FlatProxyModel::on_layoutChanged()
{
insertSubTree(QModelIndex(), false /* don't emit insertRows() */);
emit layoutChanged();
}
-
-void FlatProxyModel::on_rowsAboutToBeInserted(const QModelIndex &parent, int start, int end)
+void FlatProxyModel::on_rowsAboutToBeInserted(const QModelIndex& parent, int start, int end)
{
Q_ASSERT(sourceModel());
Q_ASSERT(_rootSourceItem);
- SourceItem *sourceItem = sourceToInternal(parent);
+ SourceItem* sourceItem = sourceToInternal(parent);
Q_ASSERT(sourceItem);
beginInsertRows(QModelIndex(), sourceItem->pos() + start + 1, sourceItem->pos() + end + 1);
- SourceItem *prevItem = sourceItem;
+ SourceItem* prevItem = sourceItem;
if (start > 0) {
prevItem = sourceItem->child(start - 1);
while (prevItem->childCount() > 0) {
}
Q_ASSERT(prevItem);
- SourceItem *nextItem = prevItem->next();
+ SourceItem* nextItem = prevItem->next();
- SourceItem *newItem = nullptr;
+ SourceItem* newItem = nullptr;
int newPos = prevItem->pos() + 1;
for (int row = start; row <= end; row++) {
newItem = new SourceItem(row, sourceItem);
}
}
-
-void FlatProxyModel::on_rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
+void FlatProxyModel::on_rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
Q_ASSERT(sourceModel());
Q_ASSERT(_rootSourceItem);
- SourceItem *sourceItem = sourceToInternal(parent);
+ SourceItem* sourceItem = sourceToInternal(parent);
beginRemoveRows(QModelIndex(), sourceItem->pos() + start + 1, sourceItem->pos() + end + 1);
// sanity check - if that check fails our indexes would be messed up
for (int row = start; row <= end; row++) {
if (sourceItem->child(row)->childCount() > 0) {
- qWarning() << "on_rowsAboutToBeRemoved(): sourceModel() removed rows which have children on their own!" << sourceModel()->index(row, 0, parent);
+ qWarning() << "on_rowsAboutToBeRemoved(): sourceModel() removed rows which have children on their own!"
+ << sourceModel()->index(row, 0, parent);
Q_ASSERT(false);
}
}
}
-
-void FlatProxyModel::on_rowsInserted(const QModelIndex &parent, int start, int end)
+void FlatProxyModel::on_rowsInserted(const QModelIndex& parent, int start, int end)
{
Q_ASSERT(sourceModel());
Q_ASSERT(_rootSourceItem);
- SourceItem *sourceItem = sourceToInternal(parent);
+ SourceItem* sourceItem = sourceToInternal(parent);
Q_ASSERT(sourceItem);
Q_UNUSED(sourceItem);
endInsertRows();
}
-
-void FlatProxyModel::on_rowsRemoved(const QModelIndex &parent, int start, int end)
+void FlatProxyModel::on_rowsRemoved(const QModelIndex& parent, int start, int end)
{
Q_ASSERT(sourceModel());
Q_ASSERT(_rootSourceItem);
- SourceItem *sourceItem = sourceToInternal(parent);
+ SourceItem* sourceItem = sourceToInternal(parent);
Q_ASSERT(sourceItem);
- SourceItem *prevItem = sourceItem;
+ SourceItem* prevItem = sourceItem;
if (start > 0) {
prevItem = sourceItem->child(start - 1);
while (prevItem->childCount() > 0) {
}
Q_ASSERT(prevItem);
- SourceItem *nextItem = sourceItem->child(end)->next();
+ SourceItem* nextItem = sourceItem->child(end)->next();
int newPos = prevItem->pos() + 1;
prevItem->setNext(nextItem);
nextItem = nextItem->next();
}
- SourceItem *childItem;
+ SourceItem* childItem;
for (int row = start; row <= end; row++) {
childItem = sourceItem->_childs.takeAt(start);
delete childItem;
endRemoveRows();
}
-
// integrity Tets
void FlatProxyModel::linkTest() const
{
return;
int pos = -1;
- SourceItem *item = _rootSourceItem;
+ SourceItem* item = _rootSourceItem;
while (true) {
qDebug() << item << ":" << item->pos() << "==" << pos;
Q_ASSERT(item->pos() == pos);
qDebug() << "success!";
}
-
void FlatProxyModel::completenessTest() const
{
qDebug() << "Checking FlatProxyModel for Completeness:";
qDebug() << "success!";
}
-
-void FlatProxyModel::checkChildCount(const QModelIndex &index, const SourceItem *item, int &pos) const
+void FlatProxyModel::checkChildCount(const QModelIndex& index, const SourceItem* item, int& pos) const
{
if (!sourceModel())
return;
- qDebug() << index << "(Item:" << item << "):" << sourceModel()->rowCount(index) << "==" << item->childCount();
+ qDebug() << index << "(Item:" << item << "):" << sourceModel()->rowCount(index) << "==" << item->childCount();
qDebug() << "ProxyPos:" << item->pos() << "==" << pos;
Q_ASSERT(sourceModel()->rowCount(index) == item->childCount());
}
}
-
// ========================================
// SourceItem
// ========================================
-FlatProxyModel::SourceItem::SourceItem(int row, SourceItem *parent)
+FlatProxyModel::SourceItem::SourceItem(int row, SourceItem* parent)
: _parent(parent)
{
if (parent) {
}
}
-
FlatProxyModel::SourceItem::~SourceItem()
{
for (int i = 0; i < childCount(); i++) {
_childs.clear();
}
-
int FlatProxyModel::SourceItem::sourceRow() const
{
if (!parent())
return -1;
else
- return parent()->_childs.indexOf(const_cast<FlatProxyModel::SourceItem *>(this));
+ return parent()->_childs.indexOf(const_cast<FlatProxyModel::SourceItem*>(this));
}
-
-FlatProxyModel::SourceItem *FlatProxyModel::SourceItem::findChild(int proxyPos) const
+FlatProxyModel::SourceItem* FlatProxyModel::SourceItem::findChild(int proxyPos) const
{
Q_ASSERT(proxyPos > pos());
Q_ASSERT(_childs.count() > 0);
Q_OBJECT
public:
- FlatProxyModel(QObject *parent = nullptr);
+ FlatProxyModel(QObject* parent = nullptr);
- QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override;
- QModelIndex mapToSource(const QModelIndex &proxyIndex) const override;
+ QModelIndex mapFromSource(const QModelIndex& sourceIndex) const override;
+ QModelIndex mapToSource(const QModelIndex& proxyIndex) const override;
- QItemSelection mapSelectionFromSource(const QItemSelection &sourceSelection) const override;
- QItemSelection mapSelectionToSource(const QItemSelection &proxySelection) const override;
+ QItemSelection mapSelectionFromSource(const QItemSelection& sourceSelection) const override;
+ QItemSelection mapSelectionToSource(const QItemSelection& proxySelection) const override;
- void setSourceModel(QAbstractItemModel *sourceModel) override;
+ void setSourceModel(QAbstractItemModel* sourceModel) override;
- QModelIndex index(int row, int column, const QModelIndex &parent) const override;
- QModelIndex parent(const QModelIndex &index) const override;
+ QModelIndex index(int row, int column, const QModelIndex& parent) const override;
+ QModelIndex parent(const QModelIndex& index) const override;
- int rowCount(const QModelIndex &index) const override;
- int columnCount(const QModelIndex &index) const override;
+ int rowCount(const QModelIndex& index) const override;
+ int columnCount(const QModelIndex& index) const override;
public slots:
void linkTest() const;
void completenessTest() const;
private slots:
- void on_columnsAboutToBeInserted(const QModelIndex &parent, int start, int end);
- void on_columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
- void on_columnsInserted(const QModelIndex &parent, int start, int end);
- void on_columnsRemoved(const QModelIndex &parent, int start, int end);
+ void on_columnsAboutToBeInserted(const QModelIndex& parent, int start, int end);
+ void on_columnsAboutToBeRemoved(const QModelIndex& parent, int start, int end);
+ void on_columnsInserted(const QModelIndex& parent, int start, int end);
+ void on_columnsRemoved(const QModelIndex& parent, int start, int end);
- void on_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
-// void on_headerDataChanged(Qt::Orientation orientation, int first, int last);
+ void on_dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight);
+ // void on_headerDataChanged(Qt::Orientation orientation, int first, int last);
void on_layoutAboutToBeChanged();
void on_layoutChanged();
- inline void on_modelAboutToBeReset() { beginResetModel(); endResetModel(); }
+ inline void on_modelAboutToBeReset()
+ {
+ beginResetModel();
+ endResetModel();
+ }
// void on_modelReset();
- void on_rowsAboutToBeInserted(const QModelIndex &parent, int start, int end);
- void on_rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
- void on_rowsInserted(const QModelIndex &parent, int start, int end);
- void on_rowsRemoved(const QModelIndex &parent, int start, int end);
+ void on_rowsAboutToBeInserted(const QModelIndex& parent, int start, int end);
+ void on_rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end);
+ void on_rowsInserted(const QModelIndex& parent, int start, int end);
+ void on_rowsRemoved(const QModelIndex& parent, int start, int end);
private:
QList<int> _childCount;
class SourceItem;
- SourceItem *_rootSourceItem{nullptr};
+ SourceItem* _rootSourceItem{nullptr};
- void insertSubTree(const QModelIndex &source_idx, bool emitInsert = true);
- SourceItem *insertSubTreeHelper(SourceItem *parentItem, SourceItem *lastItem_, const QModelIndex &source_idx);
+ void insertSubTree(const QModelIndex& source_idx, bool emitInsert = true);
+ SourceItem* insertSubTreeHelper(SourceItem* parentItem, SourceItem* lastItem_, const QModelIndex& source_idx);
- void removeSubTree(const QModelIndex &source_idx, bool emitRemove = true);
+ void removeSubTree(const QModelIndex& source_idx, bool emitRemove = true);
- SourceItem *sourceToInternal(const QModelIndex &sourceIndex) const;
+ SourceItem* sourceToInternal(const QModelIndex& sourceIndex) const;
- void checkChildCount(const QModelIndex &index, const SourceItem *item, int &pos) const;
+ void checkChildCount(const QModelIndex& index, const SourceItem* item, int& pos) const;
class _RangeRect
{
-public:
+ public:
int left, right, top, bottom;
SourceItem *topItem, *bottomItem;
- bool operator<(const _RangeRect &other) const;
+ bool operator<(const _RangeRect& other) const;
};
};
-
class FlatProxyModel::SourceItem
{
public:
- SourceItem(int row = 0, SourceItem *parent = nullptr);
+ SourceItem(int row = 0, SourceItem* parent = nullptr);
~SourceItem();
- inline SourceItem *parent() const { return _parent; }
- inline SourceItem *child(int i) const { return _childs[i]; }
+ inline SourceItem* parent() const { return _parent; }
+ inline SourceItem* child(int i) const { return _childs[i]; }
inline int childCount() const { return _childs.count(); }
inline int pos() const { return _pos; }
- inline SourceItem *next() const { return _next; }
+ inline SourceItem* next() const { return _next; }
int sourceRow() const;
- SourceItem *findChild(int proxyPos) const;
+ SourceItem* findChild(int proxyPos) const;
private:
- inline void removeChild(SourceItem *item) { _childs.removeAt(_childs.indexOf(item)); }
+ inline void removeChild(SourceItem* item) { _childs.removeAt(_childs.indexOf(item)); }
inline void setPos(int i) { _pos = i; }
- inline void setNext(SourceItem *next) { _next = next; }
+ inline void setNext(SourceItem* next) { _next = next; }
- SourceItem *_parent;
- QList<SourceItem *> _childs;
+ SourceItem* _parent;
+ QList<SourceItem*> _childs;
int _pos{-1};
- SourceItem *_next{nullptr};
+ SourceItem* _next{nullptr};
friend class FlatProxyModel;
};
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "fontselector.h"
+
#include <QEvent>
#include <QFontDialog>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
-#include "fontselector.h"
-
-FontSelector::FontSelector(QWidget *parent) : QWidget(parent)
+FontSelector::FontSelector(QWidget* parent)
+ : QWidget(parent)
{
- auto *layout = new QHBoxLayout(this);
- QPushButton *chooseButton = new QPushButton(tr("Choose..."), this);
+ auto* layout = new QHBoxLayout(this);
+ QPushButton* chooseButton = new QPushButton(tr("Choose..."), this);
connect(chooseButton, &QAbstractButton::clicked, this, &FontSelector::chooseFont);
layout->addWidget(_demo = new QLabel("Font"));
_font = font();
}
-
-void FontSelector::setSelectedFont(const QFont &font)
+void FontSelector::setSelectedFont(const QFont& font)
{
_font = font;
_demo->setText(QString("%1 %2pt").arg(font.family()).arg(font.pointSize()));
emit fontChanged(font);
}
-
void FontSelector::chooseFont()
{
bool ok;
}
}
-
-void FontSelector::changeEvent(QEvent *e)
+void FontSelector::changeEvent(QEvent* e)
{
if (e->type() == QEvent::StyleChange) {
_demo->setFont(_font);
Q_OBJECT
Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont)
-public :
- FontSelector(QWidget *parent = nullptr);
+public:
+ FontSelector(QWidget* parent = nullptr);
- inline const QFont &selectedFont() const { return _font; }
+ inline const QFont& selectedFont() const { return _font; }
public slots:
- void setSelectedFont(const QFont &font);
+ void setSelectedFont(const QFont& font);
signals:
- void fontChanged(const QFont &);
+ void fontChanged(const QFont&);
protected:
- void changeEvent(QEvent *e) override;
+ void changeEvent(QEvent* e) override;
protected slots:
void chooseFont();
private:
QFont _font;
- QLabel *_demo;
+ QLabel* _demo;
};
#include "graphicalui.h"
#include "actioncollection.h"
-#include "uisettings.h"
#include "contextmenuactionprovider.h"
#include "toolbaractionprovider.h"
+#include "uisettings.h"
#ifdef Q_WS_X11
-# include <QX11Info>
+# include <QX11Info>
#endif
-QWidget *GraphicalUi::_mainWidget = nullptr;
-QHash<QString, ActionCollection *> GraphicalUi::_actionCollections;
-ContextMenuActionProvider *GraphicalUi::_contextMenuActionProvider = nullptr;
-ToolBarActionProvider *GraphicalUi::_toolBarActionProvider = nullptr;
-UiStyle *GraphicalUi::_uiStyle = nullptr;
-
+QWidget* GraphicalUi::_mainWidget = nullptr;
+QHash<QString, ActionCollection*> GraphicalUi::_actionCollections;
+ContextMenuActionProvider* GraphicalUi::_contextMenuActionProvider = nullptr;
+ToolBarActionProvider* GraphicalUi::_toolBarActionProvider = nullptr;
+UiStyle* GraphicalUi::_uiStyle = nullptr;
-GraphicalUi::GraphicalUi(QObject *parent) : AbstractUi(parent), Singleton<GraphicalUi>(this)
+GraphicalUi::GraphicalUi(QObject* parent)
+ : AbstractUi(parent)
+ , Singleton<GraphicalUi>(this)
{
Q_INIT_RESOURCE(pics);
Q_INIT_RESOURCE(hicolor_icons);
#endif
}
-
void GraphicalUi::init()
{
#ifdef Q_OS_WIN
#endif
}
-
-ActionCollection *GraphicalUi::actionCollection(const QString &category, const QString &translatedCategory)
+ActionCollection* GraphicalUi::actionCollection(const QString& category, const QString& translatedCategory)
{
if (_actionCollections.contains(category))
return _actionCollections.value(category);
- auto *coll = new ActionCollection(_mainWidget);
+ auto* coll = new ActionCollection(_mainWidget);
if (!translatedCategory.isEmpty())
coll->setProperty("Category", translatedCategory);
return coll;
}
-
-QHash<QString, ActionCollection *> GraphicalUi::actionCollections()
+QHash<QString, ActionCollection*> GraphicalUi::actionCollections()
{
return _actionCollections;
}
-
void GraphicalUi::loadShortcuts()
{
- foreach(ActionCollection *coll, actionCollections())
- coll->readSettings();
+ foreach (ActionCollection* coll, actionCollections())
+ coll->readSettings();
}
-
void GraphicalUi::saveShortcuts()
{
ShortcutSettings s;
s.clear();
- foreach(ActionCollection *coll, actionCollections())
- coll->writeSettings();
+ foreach (ActionCollection* coll, actionCollections())
+ coll->writeSettings();
}
-
-void GraphicalUi::setMainWidget(QWidget *widget)
+void GraphicalUi::setMainWidget(QWidget* widget)
{
_mainWidget = widget;
}
-
-void GraphicalUi::setContextMenuActionProvider(ContextMenuActionProvider *provider)
+void GraphicalUi::setContextMenuActionProvider(ContextMenuActionProvider* provider)
{
_contextMenuActionProvider = provider;
}
-
-void GraphicalUi::setToolBarActionProvider(ToolBarActionProvider *provider)
+void GraphicalUi::setToolBarActionProvider(ToolBarActionProvider* provider)
{
_toolBarActionProvider = provider;
}
-
-void GraphicalUi::setUiStyle(UiStyle *style)
+void GraphicalUi::setUiStyle(UiStyle* style)
{
_uiStyle = style;
}
-
void GraphicalUi::disconnectedFromCore()
{
_contextMenuActionProvider->disconnectedFromCore();
AbstractUi::disconnectedFromCore();
}
-
-bool GraphicalUi::eventFilter(QObject *obj, QEvent *event)
+bool GraphicalUi::eventFilter(QObject* obj, QEvent* event)
{
#ifdef Q_OS_WIN
if (obj == mainWidget() && event->type() == QEvent::ActivationChange) {
return AbstractUi::eventFilter(obj, event);
}
-
// NOTE: Window activation stuff seems to work just fine in Plasma 5 without requiring X11 hacks.
// TODO: Evaluate cleaning all this up once we can get rid of Qt4/KDE4
return true;
}
-
bool GraphicalUi::isMainWidgetVisible()
{
return !instance()->checkMainWidgetVisibility(false);
}
-
void GraphicalUi::minimizeRestore(bool show)
{
if (show)
hideMainWidget();
}
-
void GraphicalUi::activateMainWidget()
{
#ifdef Q_WS_X11
#endif
}
-
void GraphicalUi::hideMainWidget()
{
if (instance()->isHidingMainWidgetAllowed())
#endif
}
-
void GraphicalUi::toggleMainWidget()
{
instance()->checkMainWidgetVisibility(true);
class UiStyle;
#ifdef Q_OS_WIN
-# include <windows.h>
+# include <windows.h>
#endif
#ifdef Q_OS_MAC
-#include <Carbon/Carbon.h>
+# include <Carbon/Carbon.h>
#endif
class UISUPPORT_EXPORT GraphicalUi : public AbstractUi, protected Singleton<GraphicalUi>
public:
//! Access global ActionCollections.
/** These ActionCollections are associated with the main window, i.e. they contain global
- * actions (and thus, shortcuts). Widgets providing application-wide shortcuts should
- * create appropriate Action objects using GraphicalUi::actionCollection(cat)->add\<Action\>().
- * @param category The category (default: "General")
- */
- static ActionCollection *actionCollection(const QString &category = "General", const QString &translatedCategory = QString());
- static QHash<QString, ActionCollection *> actionCollections();
+ * actions (and thus, shortcuts). Widgets providing application-wide shortcuts should
+ * create appropriate Action objects using GraphicalUi::actionCollection(cat)->add\<Action\>().
+ * @param category The category (default: "General")
+ */
+ static ActionCollection* actionCollection(const QString& category = "General", const QString& translatedCategory = QString());
+ static QHash<QString, ActionCollection*> actionCollections();
//! Load custom shortcuts from ShortcutSettings
/** @note This method assumes that all configurable actions are defined when being called
//! Save custom shortcuts to ShortcutSettings
static void saveShortcuts();
- inline static ContextMenuActionProvider *contextMenuActionProvider();
- inline static ToolBarActionProvider *toolBarActionProvider();
- inline static UiStyle *uiStyle();
- inline static QWidget *mainWidget();
+ inline static ContextMenuActionProvider* contextMenuActionProvider();
+ inline static ToolBarActionProvider* toolBarActionProvider();
+ inline static UiStyle* uiStyle();
+ inline static QWidget* mainWidget();
//! Force the main widget to the front and focus it (may not work in all window systems)
static void activateMainWidget();
static bool isMainWidgetVisible();
protected:
- GraphicalUi(QObject *parent = nullptr);
+ GraphicalUi(QObject* parent = nullptr);
void init() override;
//! This is the widget we associate global actions with, typically the main window
- void setMainWidget(QWidget *);
+ void setMainWidget(QWidget*);
//! Check if the mainWidget is visible and optionally toggle its visibility
/** With KDE integration, we check if the mainWidget is (partially) obscured in order to determine if
*/
virtual inline bool isHidingMainWidgetAllowed() const;
- void setContextMenuActionProvider(ContextMenuActionProvider *);
- void setToolBarActionProvider(ToolBarActionProvider *);
- void setUiStyle(UiStyle *);
+ void setContextMenuActionProvider(ContextMenuActionProvider*);
+ void setToolBarActionProvider(ToolBarActionProvider*);
+ void setUiStyle(UiStyle*);
- bool eventFilter(QObject *obj, QEvent *event) override;
+ bool eventFilter(QObject* obj, QEvent* event) override;
protected slots:
void disconnectedFromCore() override;
private:
- static QWidget *_mainWidget;
- static QHash<QString, ActionCollection *> _actionCollections;
- static ContextMenuActionProvider *_contextMenuActionProvider;
- static ToolBarActionProvider *_toolBarActionProvider;
- static UiStyle *_uiStyle;
+ static QWidget* _mainWidget;
+ static QHash<QString, ActionCollection*> _actionCollections;
+ static ContextMenuActionProvider* _contextMenuActionProvider;
+ static ToolBarActionProvider* _toolBarActionProvider;
+ static UiStyle* _uiStyle;
#ifdef Q_OS_WIN
DWORD _dwTickCount;
#endif
};
-
// inlines
-ContextMenuActionProvider *GraphicalUi::contextMenuActionProvider() { return _contextMenuActionProvider; }
-ToolBarActionProvider *GraphicalUi::toolBarActionProvider() { return _toolBarActionProvider; }
-UiStyle *GraphicalUi::uiStyle() { return _uiStyle; }
-QWidget *GraphicalUi::mainWidget() { return _mainWidget; }
-bool GraphicalUi::isHidingMainWidgetAllowed() const { return false; }
+ContextMenuActionProvider* GraphicalUi::contextMenuActionProvider()
+{
+ return _contextMenuActionProvider;
+}
+
+ToolBarActionProvider* GraphicalUi::toolBarActionProvider()
+{
+ return _toolBarActionProvider;
+}
+
+UiStyle* GraphicalUi::uiStyle()
+{
+ return _uiStyle;
+}
+
+QWidget* GraphicalUi::mainWidget()
+{
+ return _mainWidget;
+}
+
+bool GraphicalUi::isHidingMainWidgetAllowed() const
+{
+ return false;
+}
namespace {
-void printWarning(const QString &iconName, const QString &extra = {})
+void printWarning(const QString& iconName, const QString& extra = {})
{
static std::set<QString> warnedAbout;
if (warnedAbout.insert(iconName).second) {
}
}
-}
-
+} // namespace
-QIcon get(const QString &iconName, const QString &fallbackPath)
+QIcon get(const QString& iconName, const QString& fallbackPath)
{
return get(std::vector<QString>{iconName}, fallbackPath);
}
-
-QIcon get(const std::vector<QString> &iconNames, const QString &fallbackPath)
+QIcon get(const std::vector<QString>& iconNames, const QString& fallbackPath)
{
- for (auto &&iconName : iconNames) {
+ for (auto&& iconName : iconNames) {
// Exact match
if (QIcon::hasThemeIcon(iconName)) {
return QIcon::fromTheme(iconName);
}
}
- for (auto &&iconName : iconNames) {
+ for (auto&& iconName : iconNames) {
// Try to get something from the theme anyway (i.e. a more generic fallback)
QIcon fallback = QIcon::fromTheme(iconName);
if (!fallback.availableSizes().isEmpty()) {
// Build error string
QStringList requested;
- for (auto &&iconName : iconNames) {
+ for (auto&& iconName : iconNames) {
requested << iconName;
}
QString missing = "{" + requested.join(", ") + "}";
return {};
}
-}
+} // namespace icon
* @param fallbackPath Full path to a fallback icon
* @returns The requested icon, if available
*/
-UISUPPORT_EXPORT QIcon get(const QString &iconName, const QString &fallbackPath = {});
+UISUPPORT_EXPORT QIcon get(const QString& iconName, const QString& fallbackPath = {});
/**
* Gets an icon from the current icon theme.
* @param fallbackPath Full path to a fallback icon
* @returns The requested icon, if available
*/
-UISUPPORT_EXPORT QIcon get(const std::vector<QString> &iconNames, const QString &fallbackPath = {});
+UISUPPORT_EXPORT QIcon get(const std::vector<QString>& iconNames, const QString& fallbackPath = {});
-}
+} // namespace icon
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "multilineedit.h"
+
#include <QApplication>
#include <QMessageBox>
#include <QScrollBar>
#include "actioncollection.h"
#include "bufferview.h"
#include "graphicalui.h"
-#include "multilineedit.h"
#include "tabcompleter.h"
const int leftMargin = 3;
-MultiLineEdit::MultiLineEdit(QWidget *parent)
+MultiLineEdit::MultiLineEdit(QWidget* parent)
: MultiLineEditParent(parent)
{
document()->setDocumentMargin(0);
_mircColorMap["15"] = "#c0c0c0";
}
-
#if defined HAVE_SONNET && !defined HAVE_KDE
-Sonnet::Highlighter *MultiLineEdit::highlighter() const
+Sonnet::Highlighter* MultiLineEdit::highlighter() const
{
return _spellCheckDecorator->highlighter();
}
-
void MultiLineEdit::setSpellCheckEnabled(bool enabled)
{
highlighter()->setActive(enabled);
}
}
-void MultiLineEdit::contextMenuEvent(QContextMenuEvent *event)
+void MultiLineEdit::contextMenuEvent(QContextMenuEvent* event)
{
- QMenu *menu = createStandardContextMenu();
+ QMenu* menu = createStandardContextMenu();
menu->addSeparator();
auto action = menu->addAction(tr("Auto Spell Check"));
#endif
-
-void MultiLineEdit::setCustomFont(const QFont &font)
+void MultiLineEdit::setCustomFont(const QFont& font)
{
setFont(font);
updateSizeHint();
}
-
void MultiLineEdit::setMode(Mode mode)
{
if (mode == _mode)
_mode = mode;
}
-
void MultiLineEdit::setLineWrapEnabled(bool enable)
{
setLineWrapMode(enable ? WidgetWidth : NoWrap);
updateSizeHint();
}
-
void MultiLineEdit::setMinHeight(int lines)
{
if (lines == _minHeight)
updateSizeHint();
}
-
void MultiLineEdit::setMaxHeight(int lines)
{
if (lines == _maxHeight)
updateSizeHint();
}
-
void MultiLineEdit::setScrollBarsEnabled(bool enable)
{
if (_scrollBarsEnabled == enable)
updateScrollBars();
}
-
void MultiLineEdit::updateScrollBars()
{
QFontMetrics fm(font());
setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
}
-
-void MultiLineEdit::resizeEvent(QResizeEvent *event)
+void MultiLineEdit::resizeEvent(QResizeEvent* event)
{
QTextEdit::resizeEvent(event);
updateSizeHint();
updateScrollBars();
}
-
void MultiLineEdit::updateSizeHint()
{
QFontMetrics fm(font());
opt.lineWidth = lineWidth();
opt.midLineWidth = midLineWidth();
opt.state |= QStyle::State_Sunken;
- QWidget *widget = this;
+ QWidget* widget = this;
#ifdef Q_OS_MAC
widget = 0;
#endif
}
}
-
QSize MultiLineEdit::sizeHint() const
{
if (!_sizeHint.isValid()) {
- auto *that = const_cast<MultiLineEdit *>(this);
+ auto* that = const_cast<MultiLineEdit*>(this);
that->updateSizeHint();
}
return _sizeHint;
}
-
QSize MultiLineEdit::minimumSizeHint() const
{
return sizeHint();
}
-
void MultiLineEdit::setEmacsMode(bool enable)
{
_emacsMode = enable;
}
-
-void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
+void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget*)
{
_pasteProtectionEnabled = enable;
}
-
void MultiLineEdit::historyMoveBack()
{
addToHistory(convertRichtextToMircCodes(), true);
}
}
-
void MultiLineEdit::historyMoveForward()
{
addToHistory(convertRichtextToMircCodes(), true);
if (_idx < _history.count()) {
_idx++;
- if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
+ if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
showHistoryEntry();
else
- reset(); // equals clear() in this case
+ reset(); // equals clear() in this case
}
else {
addToHistory(convertRichtextToMircCodes());
}
}
-
-bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
+bool MultiLineEdit::addToHistory(const QString& text, bool temporary)
{
if (text.isEmpty())
return false;
return false;
}
-
-bool MultiLineEdit::event(QEvent *e)
+bool MultiLineEdit::event(QEvent* e)
{
// We need to make sure that global shortcuts aren't eaten
if (e->type() == QEvent::ShortcutOverride) {
- auto *event = static_cast<QKeyEvent *>(e);
+ auto* event = static_cast<QKeyEvent*>(e);
QKeySequence key = QKeySequence(event->key() | event->modifiers());
- foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
+ foreach (QAction* action, GraphicalUi::actionCollection()->actions()) {
if (action->shortcuts().contains(key)) {
e->ignore();
return false;
return MultiLineEditParent::event(e);
}
-
-void MultiLineEdit::keyPressEvent(QKeyEvent *event)
+void MultiLineEdit::keyPressEvent(QKeyEvent* event)
{
if (event == QKeySequence::InsertLineSeparator) {
if (_mode == SingleLine) {
if (!(event->modifiers() & Qt::ControlModifier)) {
int pos = textCursor().position();
moveCursor(QTextCursor::Up);
- if (pos == textCursor().position()) // already on top line -> history
+ if (pos == textCursor().position()) // already on top line -> history
historyMoveBack();
}
else
if (!(event->modifiers() & Qt::ControlModifier)) {
int pos = textCursor().position();
moveCursor(QTextCursor::Down);
- if (pos == textCursor().position()) // already on bottom line -> history
+ if (pos == textCursor().position()) // already on bottom line -> history
historyMoveForward();
}
else
break;
}
}
- else if (event->modifiers() & Qt::MetaModifier ||
- event->modifiers() & Qt::AltModifier)
- {
+ else if (event->modifiers() & Qt::MetaModifier || event->modifiers() & Qt::AltModifier) {
switch (event->key()) {
case Qt::Key_Right:
moveCursor(QTextCursor::WordRight);
cut();
return;
- case Qt::Key_U: // uppercase word
+ case Qt::Key_U: // uppercase word
moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
textCursor().insertText(textCursor().selectedText().toUpper());
return;
- case Qt::Key_L: // lowercase word
+ case Qt::Key_L: // lowercase word
moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
textCursor().insertText(textCursor().selectedText().toLower());
return;
- case Qt::Key_C:
- { // capitalize word
+ case Qt::Key_C: { // capitalize word
moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
QString const text = textCursor().selectedText();
textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
return;
}
- case Qt::Key_T:
- { // transpose words
+ case Qt::Key_T: { // transpose words
moveCursor(QTextCursor::StartOfWord);
moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
QString const word1 = textCursor().selectedText();
#endif
}
-
QString MultiLineEdit::convertRichtextToMircCodes()
{
bool underline, bold, italic, color;
mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
if (mircFgColor.isEmpty()) {
- mircFgColor = "01"; //use black if the current foreground color can't be converted
+ mircFgColor = "01"; // use black if the current foreground color can't be converted
}
mircText.append(mircFgColor);
return mircText;
}
-
-bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
+bool MultiLineEdit::mircCodesChanged(QTextCursor& cursor, QTextCursor& peekcursor)
{
bool changed = false;
if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
return changed;
}
-
-QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
+QString MultiLineEdit::convertMircCodesToHtml(const QString& text)
{
QStringList words;
QRegExp mircCode = QRegExp("(\ 2|\1d|\1f|\ 3)", Qt::CaseSensitive);
if (posRight < 0) {
words << text.mid(posLeft);
- break; // no more mirc color codes
+ break; // no more mirc color codes
}
if (posLeft < posRight) {
int len = 3;
QString fg = words[i].mid(pos + 1, 2);
QString bg;
- if (words[i][pos+3] == ',')
- bg = words[i].mid(pos+4, 2);
+ if (words[i][pos + 3] == ',')
+ bg = words[i].mid(pos + 4, 2);
style.append(" color:");
style.append(_mircColorMap[fg]);
return words.join("").replace("\n", "<br />");
}
-
void MultiLineEdit::on_returnPressed()
{
on_returnPressed(convertRichtextToMircCodes());
}
-
void MultiLineEdit::on_returnPressed(QString text)
{
if (_completionSpace && text.endsWith(" ")) {
}
if (!text.isEmpty()) {
- foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
+ foreach (const QString& line, text.split('\n', QString::SkipEmptyParts)) {
if (line.isEmpty())
continue;
addToHistory(line);
}
}
-
void MultiLineEdit::on_textChanged()
{
_completionSpace = qMax(_completionSpace - 1, 0);
msg += "<br />";
}
msg += "...</p>";
- QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
+ QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes | QMessageBox::No);
question.setDefaultButton(QMessageBox::No);
#ifdef Q_OS_MAC
question.setWindowFlags(question.windowFlags() | Qt::Sheet);
return;
}
- foreach(QString line, lines) {
+ foreach (QString line, lines) {
clear();
insert(line);
on_returnPressed();
ensureCursorVisible();
}
-
void MultiLineEdit::on_documentHeightChanged(qreal)
{
updateScrollBars();
}
-
void MultiLineEdit::reset()
{
// every time the MultiLineEdit is cleared we also reset history index
_idx = _history.count();
clear();
QTextBlockFormat format = textCursor().blockFormat();
- format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
+ format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
textCursor().setBlockFormat(format);
updateScrollBars();
}
-
void MultiLineEdit::showHistoryEntry()
{
// if the user changed the history, display the changed line
setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
QTextCursor cursor = textCursor();
QTextBlockFormat format = cursor.blockFormat();
- format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
+ format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
cursor.setBlockFormat(format);
cursor.movePosition(QTextCursor::End);
setTextCursor(cursor);
updateScrollBars();
}
-
void MultiLineEdit::addCompletionSpace()
{
// Inserting the space emits textChanged, which should not disable removal
_completionSpace = 2;
insertPlainText(" ");
}
-
#include "uisupport-export.h"
-#include <QKeyEvent>
#include <QHash>
+#include <QKeyEvent>
#if defined HAVE_KF5
-# include <KTextWidgets/KTextEdit>
-# define MultiLineEditParent KTextEdit
+# include <KTextWidgets/KTextEdit>
+# define MultiLineEditParent KTextEdit
#else
-# include <QTextEdit>
-# define MultiLineEditParent QTextEdit
+# include <QTextEdit>
+# define MultiLineEditParent QTextEdit
#endif
#if defined HAVE_SONNET && !defined HAVE_KDE
-# include <QContextMenuEvent>
-# include <Sonnet/Highlighter>
-# include <Sonnet/SpellCheckDecorator>
+# include <QContextMenuEvent>
+
+# include <Sonnet/Highlighter>
+# include <Sonnet/SpellCheckDecorator>
#endif
class UISUPPORT_EXPORT MultiLineEdit : public MultiLineEditParent
Q_OBJECT
public:
- enum Mode {
+ enum Mode
+ {
SingleLine,
MultiLine
};
- MultiLineEdit(QWidget *parent = nullptr);
+ MultiLineEdit(QWidget* parent = nullptr);
- void setCustomFont(const QFont &); // should be used instead setFont(), so we can set our size correctly
+ void setCustomFont(const QFont&); // should be used instead setFont(), so we can set our size correctly
// Compatibility methods with the rest of the classes which still expect this to be a QLineEdit
inline QString text() const { return toPlainText(); }
inline QString html() const { return toHtml(); }
inline int cursorPosition() const { return textCursor().position(); }
- inline void insert(const QString &newText) { insertPlainText(newText); }
+ inline void insert(const QString& newText) { insertPlainText(newText); }
inline void backspace() { keyPressEvent(new QKeyEvent(QEvent::KeyPress, Qt::Key_Backspace, Qt::NoModifier)); }
inline bool hasSelectedText() const { return textCursor().hasSelection(); }
inline QString mircColorFromRGB(QString rgbColor) const { return _mircColorMap.key(rgbColor); }
inline QString rgbColorFromMirc(QString mircColor) const { return _mircColorMap[mircColor]; }
- inline QMap<QString, QString> mircColorMap() const { return _mircColorMap; }
+ inline QMap<QString, QString> mircColorMap() const { return _mircColorMap; }
inline QStringList history() const { return _history; }
inline QHash<int, QString> tempHistory() const { return _tempHistory; }
void setMaxHeight(int numLines);
void setEmacsMode(bool enable = true);
void setScrollBarsEnabled(bool enable = true);
- void setPasteProtectionEnabled(bool enable = true, QWidget *msgBoxParent = nullptr);
+ void setPasteProtectionEnabled(bool enable = true, QWidget* msgBoxParent = nullptr);
void setLineWrapEnabled(bool enable = false);
inline void setHistory(QStringList history) { _history = history; }
inline void setIdx(qint32 idx) { _idx = idx; }
signals:
- void textEntered(const QString &text);
+ void textEntered(const QString& text);
void noTextEntered();
protected:
- bool event(QEvent *e) override;
- void keyPressEvent(QKeyEvent *event) override;
- void resizeEvent(QResizeEvent *event) override;
+ bool event(QEvent* e) override;
+ void keyPressEvent(QKeyEvent* event) override;
+ void resizeEvent(QResizeEvent* event) override;
#if defined HAVE_SONNET && !defined HAVE_KDE
- void contextMenuEvent(QContextMenuEvent *event) override;
+ void contextMenuEvent(QContextMenuEvent* event) override;
#endif
private slots:
void on_textChanged();
void on_documentHeightChanged(qreal height);
- bool addToHistory(const QString &text, bool temporary = false);
+ bool addToHistory(const QString& text, bool temporary = false);
void historyMoveForward();
void historyMoveBack();
QString convertRichtextToMircCodes();
- QString convertMircCodesToHtml(const QString &text);
- bool mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor);
+ QString convertMircCodesToHtml(const QString& text);
+ bool mircCodesChanged(QTextCursor& cursor, QTextCursor& peekcursor);
private:
void reset();
#if defined HAVE_SONNET && !defined HAVE_KDE
// This member function is provided by KTextEdit
- Sonnet::Highlighter *highlighter() const;
+ Sonnet::Highlighter* highlighter() const;
private slots:
void setSpellCheckEnabled(bool enabled);
private:
- Sonnet::SpellCheckDecorator *_spellCheckDecorator{nullptr};
+ Sonnet::SpellCheckDecorator* _spellCheckDecorator{nullptr};
#endif
};
#include <QDialogButtonBox>
#include <QGridLayout>
#include <QIcon>
+#include <QInputDialog>
#include <QLabel>
#include <QLineEdit>
-#include <QInputDialog>
#include <QMessageBox>
#include <QPushButton>
#include "network.h"
#include "util.h"
-NetworkModelController::NetworkModelController(QObject *parent)
- : QObject(parent),
- _actionCollection(new ActionCollection(this))
+NetworkModelController::NetworkModelController(QObject* parent)
+ : QObject(parent)
+ , _actionCollection(new ActionCollection(this))
{
connect(_actionCollection, &ActionCollection::actionTriggered, this, &NetworkModelController::actionTriggered);
}
-
-Action *NetworkModelController::registerAction(ActionType type, const QString &text, bool checkable)
+Action* NetworkModelController::registerAction(ActionType type, const QString& text, bool checkable)
{
return registerAction(type, QPixmap(), text, checkable);
}
-
-Action *NetworkModelController::registerAction(ActionType type, const QIcon &icon, const QString &text, bool checkable)
+Action* NetworkModelController::registerAction(ActionType type, const QIcon& icon, const QString& text, bool checkable)
{
- Action *act;
+ Action* act;
if (icon.isNull())
act = new Action(text, this);
else
return act;
}
-
/******** Helper Functions ***********************************************************************/
-void NetworkModelController::setIndexList(const QModelIndex &index)
+void NetworkModelController::setIndexList(const QModelIndex& index)
{
_indexList = QList<QModelIndex>() << index;
}
-
-void NetworkModelController::setIndexList(const QList<QModelIndex> &list)
+void NetworkModelController::setIndexList(const QList<QModelIndex>& list)
{
_indexList = list;
}
-
-void NetworkModelController::setMessageFilter(MessageFilter *filter)
+void NetworkModelController::setMessageFilter(MessageFilter* filter)
{
_messageFilter = filter;
}
-
-void NetworkModelController::setContextItem(const QString &contextItem)
+void NetworkModelController::setContextItem(const QString& contextItem)
{
_contextItem = contextItem;
}
-
void NetworkModelController::setSlot(ActionSlot slot)
{
_actionSlot = std::move(slot);
}
-
-bool NetworkModelController::checkRequirements(const QModelIndex &index, ItemActiveStates requiredActiveState)
+bool NetworkModelController::checkRequirements(const QModelIndex& index, ItemActiveStates requiredActiveState)
{
if (!index.isValid())
return false;
- ItemActiveStates isActive = index.data(NetworkModel::ItemActiveRole).toBool()
- ? ActiveState
- : InactiveState;
+ ItemActiveStates isActive = index.data(NetworkModel::ItemActiveRole).toBool() ? ActiveState : InactiveState;
if (!(isActive & requiredActiveState))
return false;
return true;
}
-
-QString NetworkModelController::nickName(const QModelIndex &index) const
+QString NetworkModelController::nickName(const QModelIndex& index) const
{
- auto *ircUser = qobject_cast<IrcUser *>(index.data(NetworkModel::IrcUserRole).value<QObject *>());
+ auto* ircUser = qobject_cast<IrcUser*>(index.data(NetworkModel::IrcUserRole).value<QObject*>());
if (ircUser)
return ircUser->nick();
if (bufferInfo.type() != BufferInfo::QueryBuffer)
return QString();
- return bufferInfo.bufferName(); // FIXME this might break with merged queries maybe
+ return bufferInfo.bufferName(); // FIXME this might break with merged queries maybe
}
-
-BufferId NetworkModelController::findQueryBuffer(const QModelIndex &index, const QString &predefinedNick) const
+BufferId NetworkModelController::findQueryBuffer(const QModelIndex& index, const QString& predefinedNick) const
{
NetworkId networkId = index.data(NetworkModel::NetworkIdRole).value<NetworkId>();
if (!networkId.isValid())
return findQueryBuffer(networkId, nick);
}
-
-BufferId NetworkModelController::findQueryBuffer(NetworkId networkId, const QString &nick) const
+BufferId NetworkModelController::findQueryBuffer(NetworkId networkId, const QString& nick) const
{
return Client::networkModel()->bufferId(networkId, nick);
}
-
-void NetworkModelController::removeBuffers(const QModelIndexList &indexList)
+void NetworkModelController::removeBuffers(const QModelIndexList& indexList)
{
QList<BufferInfo> inactive;
- foreach(QModelIndex index, indexList) {
+ foreach (QModelIndex index, indexList) {
BufferInfo info = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
if (info.isValid()) {
if (info.type() == BufferInfo::QueryBuffer
msg = tr("Do you want to delete the following buffer(s) permanently?", "", inactive.count());
msg += "<ul>";
int count = 0;
- foreach(BufferInfo info, inactive) {
+ foreach (BufferInfo info, inactive) {
if (count < 10) {
msg += QString("<li>%1</li>").arg(info.bufferName());
count++;
msg += "</ul>";
if (count > 9 && inactive.size() - count != 0)
msg += tr("...and <b>%1</b> more<br><br>").arg(inactive.size() - count);
- msg += tr("<b>Note:</b> This will delete all related data, including all backlog data, from the core's database and cannot be undone.");
+ msg += tr(
+ "<b>Note:</b> This will delete all related data, including all backlog data, from the core's database and cannot be undone.");
if (inactive.count() != indexList.count())
msg += tr("<br>Active channel buffers cannot be deleted, please part the channel first.");
- if (QMessageBox::question(nullptr, tr("Remove buffers permanently?"), msg, QMessageBox::Yes|QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) {
- foreach(BufferInfo info, inactive)
- Client::removeBuffer(info.bufferId());
+ if (QMessageBox::question(nullptr, tr("Remove buffers permanently?"), msg, QMessageBox::Yes | QMessageBox::No, QMessageBox::No)
+ == QMessageBox::Yes) {
+ foreach (BufferInfo info, inactive)
+ Client::removeBuffer(info.bufferId());
}
}
}
-
-void NetworkModelController::handleExternalAction(ActionType type, QAction *action)
+void NetworkModelController::handleExternalAction(ActionType type, QAction* action)
{
Q_UNUSED(type);
if (_actionSlot) {
}
}
-
/******** Handle Actions *************************************************************************/
-void NetworkModelController::actionTriggered(QAction *action)
+void NetworkModelController::actionTriggered(QAction* action)
{
ActionType type = (ActionType)action->data().toInt();
if (type > 0) {
}
}
-
-void NetworkModelController::handleNetworkAction(ActionType type, QAction *)
+void NetworkModelController::handleNetworkAction(ActionType type, QAction*)
{
- if (type == NetworkConnectAllWithDropdown || type == NetworkDisconnectAllWithDropdown || type == NetworkConnectAll || type == NetworkDisconnectAll) {
- if (type == NetworkConnectAllWithDropdown && QMessageBox::question(nullptr, tr("Question"), tr("Really Connect to all IRC Networks?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No)
+ if (type == NetworkConnectAllWithDropdown || type == NetworkDisconnectAllWithDropdown || type == NetworkConnectAll
+ || type == NetworkDisconnectAll) {
+ if (type == NetworkConnectAllWithDropdown
+ && QMessageBox::question(nullptr,
+ tr("Question"),
+ tr("Really Connect to all IRC Networks?"),
+ QMessageBox::Yes | QMessageBox::No,
+ QMessageBox::Yes)
+ == QMessageBox::No)
return;
- if (type == NetworkDisconnectAllWithDropdown && QMessageBox::question(nullptr, tr("Question"), tr("Really disconnect from all IRC Networks?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No)
+ if (type == NetworkDisconnectAllWithDropdown
+ && QMessageBox::question(nullptr,
+ tr("Question"),
+ tr("Really disconnect from all IRC Networks?"),
+ QMessageBox::Yes | QMessageBox::No,
+ QMessageBox::No)
+ == QMessageBox::No)
return;
- foreach(NetworkId id, Client::networkIds()) {
- const Network *net = Client::network(id);
+ foreach (NetworkId id, Client::networkIds()) {
+ const Network* net = Client::network(id);
if ((type == NetworkConnectAllWithDropdown || type == NetworkConnectAll) && net->connectionState() == Network::Disconnected)
net->requestConnect();
if ((type == NetworkDisconnectAllWithDropdown || type == NetworkDisconnectAll) && net->connectionState() != Network::Disconnected)
if (!indexList().count())
return;
- const Network *network = Client::network(indexList().at(0).data(NetworkModel::NetworkIdRole).value<NetworkId>());
+ const Network* network = Client::network(indexList().at(0).data(NetworkModel::NetworkIdRole).value<NetworkId>());
Q_CHECK_PTR(network);
if (!network)
return;
}
}
-
-void NetworkModelController::handleBufferAction(ActionType type, QAction *)
+void NetworkModelController::handleBufferAction(ActionType type, QAction*)
{
if (type == BufferRemove) {
removeBuffers(indexList());
}
else {
- QList<BufferInfo> bufferList; // create temp list because model indexes might change
- foreach(QModelIndex index, indexList()) {
+ QList<BufferInfo> bufferList; // create temp list because model indexes might change
+ foreach (QModelIndex index, indexList()) {
BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
if (bufferInfo.isValid())
bufferList << bufferInfo;
}
- foreach(BufferInfo bufferInfo, bufferList) {
+ foreach (BufferInfo bufferInfo, bufferList) {
switch (type) {
case BufferJoin:
Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
break;
- case BufferPart:
- {
+ case BufferPart: {
QString reason = Client::identity(Client::network(bufferInfo.networkId())->identity())->partReason();
Client::userInput(bufferInfo, QString("/PART %1").arg(reason));
break;
}
}
-
-void NetworkModelController::handleHideAction(ActionType type, QAction *action)
+void NetworkModelController::handleHideAction(ActionType type, QAction* action)
{
Q_UNUSED(action)
if (_messageFilter)
BufferSettings(_messageFilter->idString()).setMessageFilter(filter);
else {
- foreach(QModelIndex index, _indexList) {
+ foreach (QModelIndex index, _indexList) {
BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
if (!bufferId.isValid())
continue;
if (_messageFilter)
BufferSettings(_messageFilter->idString()).removeFilter();
else {
- foreach(QModelIndex index, _indexList) {
+ foreach (QModelIndex index, _indexList) {
BufferId bufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
if (!bufferId.isValid())
continue;
};
}
-
-void NetworkModelController::handleGeneralAction(ActionType type, QAction *action)
+void NetworkModelController::handleGeneralAction(ActionType type, QAction* action)
{
Q_UNUSED(action)
NetworkId networkId = indexList().at(0).data(NetworkModel::NetworkIdRole).value<NetworkId>();
switch (type) {
- case JoinChannel:
- {
+ case JoinChannel: {
QString channelName = contextItem();
QString channelPassword;
if (channelName.isEmpty()) {
}
if (!channelName.isEmpty()) {
if (!channelPassword.isEmpty())
- Client::instance()->userInput(BufferInfo::fakeStatusBuffer(networkId), QString("/JOIN %1 %2").arg(channelName).arg(channelPassword));
+ Client::instance()->userInput(BufferInfo::fakeStatusBuffer(networkId),
+ QString("/JOIN %1 %2").arg(channelName).arg(channelPassword));
else
Client::instance()->userInput(BufferInfo::fakeStatusBuffer(networkId), QString("/JOIN %1").arg(channelName));
}
}
}
-
-void NetworkModelController::handleNickAction(ActionType type, QAction *action)
+void NetworkModelController::handleNickAction(ActionType type, QAction* action)
{
- foreach(QModelIndex index, indexList()) {
+ foreach (QModelIndex index, indexList()) {
NetworkId networkId = index.data(NetworkModel::NetworkIdRole).value<NetworkId>();
if (!networkId.isValid())
continue;
case NickQuery:
Client::bufferModel()->switchToOrStartQuery(networkId, nick);
break;
- case NickIgnoreUser:
- {
- auto *ircUser = qobject_cast<IrcUser *>(index.data(NetworkModel::IrcUserRole).value<QObject *>());
+ case NickIgnoreUser: {
+ auto* ircUser = qobject_cast<IrcUser*>(index.data(NetworkModel::IrcUserRole).value<QObject*>());
if (!ircUser)
break;
Client::ignoreListManager()->requestAddIgnoreListItem(IgnoreListManager::SenderIgnore,
- action->property("ignoreRule").toString(),
- false, IgnoreListManager::SoftStrictness,
- IgnoreListManager::NetworkScope,
- ircUser->network()->networkName(), true);
+ action->property("ignoreRule").toString(),
+ false,
+ IgnoreListManager::SoftStrictness,
+ IgnoreListManager::NetworkScope,
+ ircUser->network()->networkName(),
+ true);
break;
}
- case NickIgnoreHost:
- {
- auto *ircUser = qobject_cast<IrcUser *>(index.data(NetworkModel::IrcUserRole).value<QObject *>());
+ case NickIgnoreHost: {
+ auto* ircUser = qobject_cast<IrcUser*>(index.data(NetworkModel::IrcUserRole).value<QObject*>());
if (!ircUser)
break;
Client::ignoreListManager()->requestAddIgnoreListItem(IgnoreListManager::SenderIgnore,
- action->property("ignoreRule").toString(),
- false, IgnoreListManager::SoftStrictness,
- IgnoreListManager::NetworkScope,
- ircUser->network()->networkName(), true);
+ action->property("ignoreRule").toString(),
+ false,
+ IgnoreListManager::SoftStrictness,
+ IgnoreListManager::NetworkScope,
+ ircUser->network()->networkName(),
+ true);
break;
}
- case NickIgnoreDomain:
- {
- auto *ircUser = qobject_cast<IrcUser *>(index.data(NetworkModel::IrcUserRole).value<QObject *>());
+ case NickIgnoreDomain: {
+ auto* ircUser = qobject_cast<IrcUser*>(index.data(NetworkModel::IrcUserRole).value<QObject*>());
if (!ircUser)
break;
Client::ignoreListManager()->requestAddIgnoreListItem(IgnoreListManager::SenderIgnore,
- action->property("ignoreRule").toString(),
- false, IgnoreListManager::SoftStrictness,
- IgnoreListManager::NetworkScope,
- ircUser->network()->networkName(), true);
+ action->property("ignoreRule").toString(),
+ false,
+ IgnoreListManager::SoftStrictness,
+ IgnoreListManager::NetworkScope,
+ ircUser->network()->networkName(),
+ true);
break;
}
case NickIgnoreCustom:
}
}
-
/***************************************************************************************************************
* JoinDlg
***************************************************************************************************************/
-NetworkModelController::JoinDlg::JoinDlg(const QModelIndex &index, QWidget *parent) : QDialog(parent)
+NetworkModelController::JoinDlg::JoinDlg(const QModelIndex& index, QWidget* parent)
+ : QDialog(parent)
{
setWindowIcon(icon::get("irc-join-channel"));
setWindowTitle(tr("Join Channel"));
- auto *layout = new QGridLayout(this);
+ auto* layout = new QGridLayout(this);
layout->addWidget(new QLabel(tr("Network:")), 0, 0);
layout->addWidget(networks = new QComboBox, 0, 1);
layout->addWidget(new QLabel(tr("Channel:")), 1, 0);
layout->addWidget(channel = new QLineEdit, 1, 1);
layout->addWidget(new QLabel(tr("Password:")), 2, 0);
layout->addWidget(password = new QLineEdit, 2, 1);
- layout->addWidget(buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel), 3, 0, 1, 2);
+ layout->addWidget(buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel), 3, 0, 1, 2);
setLayout(layout);
channel->setFocus();
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
connect(channel, &QLineEdit::textChanged, this, &JoinDlg::on_channel_textChanged);
- foreach(NetworkId id, Client::networkIds()) {
- const Network *net = Client::network(id);
+ foreach (NetworkId id, Client::networkIds()) {
+ const Network* net = Client::network(id);
if (net->isConnected()) {
networks->addItem(net->networkName(), QVariant::fromValue<NetworkId>(id));
}
NetworkId networkId = index.data(NetworkModel::NetworkIdRole).value<NetworkId>();
if (networkId.isValid()) {
networks->setCurrentIndex(networks->findText(Client::network(networkId)->networkName()));
- if (index.data(NetworkModel::BufferTypeRole) == BufferInfo::ChannelBuffer
- && !index.data(NetworkModel::ItemActiveRole).toBool())
+ if (index.data(NetworkModel::BufferTypeRole) == BufferInfo::ChannelBuffer && !index.data(NetworkModel::ItemActiveRole).toBool())
channel->setText(index.data(Qt::DisplayRole).toString());
}
}
}
-
NetworkId NetworkModelController::JoinDlg::networkId() const
{
return networks->itemData(networks->currentIndex()).value<NetworkId>();
}
-
QString NetworkModelController::JoinDlg::channelName() const
{
return channel->text();
}
-
QString NetworkModelController::JoinDlg::channelPassword() const
{
return password->text();
}
-
-void NetworkModelController::JoinDlg::on_channel_textChanged(const QString &text)
+void NetworkModelController::JoinDlg::on_channel_textChanged(const QString& text)
{
buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!text.isEmpty());
}
Q_OBJECT
public:
- NetworkModelController(QObject *parent = nullptr);
+ NetworkModelController(QObject* parent = nullptr);
// don't change enums without doublechecking masks etc. in code
- enum ActionType {
+ enum ActionType
+ {
// Network actions
NetworkMask = 0x0f,
NetworkConnect = 0x01,
HideBufferPermanently = 0x02000000
};
- inline Action *action(ActionType type) const;
+ inline Action* action(ActionType type) const;
public:
- enum ItemActiveState {
+ enum ItemActiveState
+ {
InactiveState = 0x01,
ActiveState = 0x02
};
virtual void disconnectedFromCore() {}
protected:
- inline ActionCollection *actionCollection() const;
+ inline ActionCollection* actionCollection() const;
inline QList<QModelIndex> indexList() const;
- inline MessageFilter *messageFilter() const;
+ inline MessageFilter* messageFilter() const;
inline QString contextItem() const; ///< Channel name or nick to provide context menu for
- void setIndexList(const QModelIndex &);
- void setIndexList(const QList<QModelIndex> &);
- void setMessageFilter(MessageFilter *);
- void setContextItem(const QString &);
+ void setIndexList(const QModelIndex&);
+ void setIndexList(const QList<QModelIndex>&);
+ void setMessageFilter(MessageFilter*);
+ void setContextItem(const QString&);
using ActionSlot = std::function<void(QAction*)>;
template<typename Receiver, typename Slot>
- ActionSlot buildActionSlot(Receiver *receiver, Slot slot)
+ ActionSlot buildActionSlot(Receiver* receiver, Slot slot)
{
static_assert(!std::is_same<Slot, const char*>::value, "Old-style slots not supported");
- return [receiver, slot = std::move(slot)](QAction *action) {
- (receiver->*slot)(action);
- };
+ return [receiver, slot = std::move(slot)](QAction* action) { (receiver->*slot)(action); };
}
void setSlot(ActionSlot slot);
- Action *registerAction(ActionType type, const QString &text, bool checkable = false);
- Action *registerAction(NetworkModelController::ActionType type, const QIcon &icon, const QString &text, bool checkable = false);
- bool checkRequirements(const QModelIndex &index, ItemActiveStates requiredActiveState = QFlags<ItemActiveState>(ActiveState | InactiveState));
+ Action* registerAction(ActionType type, const QString& text, bool checkable = false);
+ Action* registerAction(NetworkModelController::ActionType type, const QIcon& icon, const QString& text, bool checkable = false);
+ bool checkRequirements(const QModelIndex& index,
+ ItemActiveStates requiredActiveState = QFlags<ItemActiveState>(ActiveState | InactiveState));
- QString nickName(const QModelIndex &index) const;
- BufferId findQueryBuffer(const QModelIndex &index, const QString &predefinedNick = QString()) const;
- BufferId findQueryBuffer(NetworkId, const QString &nickName) const;
- void removeBuffers(const QModelIndexList &indexList);
+ QString nickName(const QModelIndex& index) const;
+ BufferId findQueryBuffer(const QModelIndex& index, const QString& predefinedNick = QString()) const;
+ BufferId findQueryBuffer(NetworkId, const QString& nickName) const;
+ void removeBuffers(const QModelIndexList& indexList);
protected slots:
- virtual void actionTriggered(QAction *);
+ virtual void actionTriggered(QAction*);
signals:
/**
* @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, const QString &, bool);
+ void showChannelList(NetworkId, const QString&, bool);
void showNetworkConfig(NetworkId);
void showIgnoreList(QString);
protected:
- virtual void handleNetworkAction(ActionType, QAction *);
- virtual void handleBufferAction(ActionType, QAction *);
- virtual void handleHideAction(ActionType, QAction *);
- virtual void handleNickAction(ActionType, QAction *action);
- virtual void handleGeneralAction(ActionType, QAction *);
- virtual void handleExternalAction(ActionType, QAction *);
+ virtual void handleNetworkAction(ActionType, QAction*);
+ virtual void handleBufferAction(ActionType, QAction*);
+ virtual void handleHideAction(ActionType, QAction*);
+ virtual void handleNickAction(ActionType, QAction* action);
+ virtual void handleGeneralAction(ActionType, QAction*);
+ virtual void handleExternalAction(ActionType, QAction*);
class JoinDlg;
private:
- NetworkModel *_model;
+ NetworkModel* _model;
- ActionCollection *_actionCollection;
- QHash<ActionType, Action *> _actionByType;
+ ActionCollection* _actionCollection;
+ QHash<ActionType, Action*> _actionByType;
QList<QModelIndex> _indexList;
- MessageFilter *_messageFilter{nullptr};
- QString _contextItem; ///< Channel name or nick to provide context menu for
+ MessageFilter* _messageFilter{nullptr};
+ QString _contextItem; ///< Channel name or nick to provide context menu for
ActionSlot _actionSlot;
};
-
//! Input dialog for joining a channel
class NetworkModelController::JoinDlg : public QDialog
{
Q_OBJECT
public:
- JoinDlg(const QModelIndex &index, QWidget *parent = nullptr);
+ JoinDlg(const QModelIndex& index, QWidget* parent = nullptr);
QString channelName() const;
QString channelPassword() const;
NetworkId networkId() const;
private slots:
- void on_channel_textChanged(const QString &);
+ void on_channel_textChanged(const QString&);
private:
- QComboBox *networks;
- QLineEdit *channel;
- QLineEdit *password;
- QDialogButtonBox *buttonBox;
+ QComboBox* networks;
+ QLineEdit* channel;
+ QLineEdit* password;
+ QDialogButtonBox* buttonBox;
};
-
// inlines
-ActionCollection *NetworkModelController::actionCollection() const { return _actionCollection; }
-Action *NetworkModelController::action(ActionType type) const { return _actionByType.value(type, 0); }
-QList<QModelIndex> NetworkModelController::indexList() const { return _indexList; }
-MessageFilter *NetworkModelController::messageFilter() const { return _messageFilter; }
-QString NetworkModelController::contextItem() const { return _contextItem; }
+ActionCollection* NetworkModelController::actionCollection() const
+{
+ return _actionCollection;
+}
+Action* NetworkModelController::action(ActionType type) const
+{
+ return _actionByType.value(type, 0);
+}
+QList<QModelIndex> NetworkModelController::indexList() const
+{
+ return _indexList;
+}
+MessageFilter* NetworkModelController::messageFilter() const
+{
+ return _messageFilter;
+}
+QString NetworkModelController::contextItem() const
+{
+ return _contextItem;
+}
#include "nickview.h"
#include <QApplication>
-#include <QHeaderView>
-#include <QScrollBar>
#include <QDebug>
+#include <QHeaderView>
#include <QMenu>
+#include <QScrollBar>
#include "buffermodel.h"
#include "client.h"
#include "contextmenuactionprovider.h"
#include "graphicalui.h"
+#include "networkmodel.h"
#include "nickview.h"
#include "nickviewfilter.h"
-#include "networkmodel.h"
#include "types.h"
-NickView::NickView(QWidget *parent)
+NickView::NickView(QWidget* parent)
: TreeViewTouch(parent)
{
setIndentation(10);
#endif
}
-
void NickView::init()
{
if (!model())
connect(selectionModel(), &QItemSelectionModel::selectionChanged, this, &NickView::selectionUpdated);
}
-
-void NickView::setModel(QAbstractItemModel *model_)
+void NickView::setModel(QAbstractItemModel* model_)
{
if (model())
disconnect(model(), nullptr, this, nullptr);
init();
}
-
-void NickView::rowsInserted(const QModelIndex &parent, int start, int end)
+void NickView::rowsInserted(const QModelIndex& parent, int start, int end)
{
TreeViewTouch::rowsInserted(parent, start, end);
if (model()->data(parent, NetworkModel::ItemTypeRole) == NetworkModel::UserCategoryItemType && !isExpanded(parent)) {
}
}
-
-void NickView::setRootIndex(const QModelIndex &index)
+void NickView::setRootIndex(const QModelIndex& index)
{
QAbstractItemView::setRootIndex(index);
if (index.isValid())
unanimatedExpandAll();
}
-
QModelIndexList NickView::selectedIndexes() const
{
QModelIndexList indexList = TreeViewTouch::selectedIndexes();
return indexList;
}
-
void NickView::unanimatedExpandAll()
{
// since of Qt Version 4.8.0 the default expandAll will not properly work if
setAnimated(wasAnimated);
}
-
-void NickView::showContextMenu(const QPoint &pos)
+void NickView::showContextMenu(const QPoint& pos)
{
Q_UNUSED(pos);
contextMenu.exec(QCursor::pos());
}
-
-void NickView::startQuery(const QModelIndex &index)
+void NickView::startQuery(const QModelIndex& index)
{
if (index.data(NetworkModel::ItemTypeRole) != NetworkModel::IrcUserItemType)
return;
- auto *ircUser = qobject_cast<IrcUser *>(index.data(NetworkModel::IrcUserRole).value<QObject *>());
+ auto* ircUser = qobject_cast<IrcUser*>(index.data(NetworkModel::IrcUserRole).value<QObject*>());
NetworkId networkId = index.data(NetworkModel::NetworkIdRole).value<NetworkId>();
if (!ircUser || !networkId.isValid())
return;
Q_OBJECT
public:
- NickView(QWidget *parent = nullptr);
+ NickView(QWidget* parent = nullptr);
protected:
- void rowsInserted(const QModelIndex &parent, int start, int end) override;
+ void rowsInserted(const QModelIndex& parent, int start, int end) override;
//! This reimplementation ensures that the current index is first in list
QModelIndexList selectedIndexes() const override;
void unanimatedExpandAll();
public slots:
- void setModel(QAbstractItemModel *model) override;
- void setRootIndex(const QModelIndex &index) override;
+ void setModel(QAbstractItemModel* model) override;
+ void setRootIndex(const QModelIndex& index) override;
void init();
- void showContextMenu(const QPoint &pos);
- void startQuery(const QModelIndex &modelIndex);
+ void showContextMenu(const QPoint& pos);
+ void startQuery(const QModelIndex& modelIndex);
signals:
void selectionUpdated();
private:
- friend class NickListWidget; // needs selectedIndexes()
+ friend class NickListWidget; // needs selectedIndexes()
};
/******************************************************************************************
* NickViewFilter
******************************************************************************************/
-NickViewFilter::NickViewFilter(const BufferId &bufferId, NetworkModel *parent)
- : QSortFilterProxyModel(parent),
- _bufferId(bufferId)
+NickViewFilter::NickViewFilter(const BufferId& bufferId, NetworkModel* parent)
+ : QSortFilterProxyModel(parent)
+ , _bufferId(bufferId)
{
setSourceModel(parent);
setDynamicSortFilter(true);
setSortRole(TreeModel::SortRole);
}
-
-bool NickViewFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
+bool NickViewFilter::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
// root node, networkindexes, the bufferindex of the buffer this filter is active for and it's children are accepted
if (!source_parent.isValid())
return (sourceModel()->data(source_child, NetworkModel::BufferIdRole).value<BufferId>() == _bufferId);
}
-
-QVariant NickViewFilter::data(const QModelIndex &index, int role) const
+QVariant NickViewFilter::data(const QModelIndex& index, int role) const
{
switch (role) {
case Qt::FontRole:
Q_OBJECT
public:
- NickViewFilter(const BufferId &bufferId, NetworkModel *parent = nullptr);
+ NickViewFilter(const BufferId& bufferId, NetworkModel* parent = nullptr);
- QVariant data(const QModelIndex &index, int role) const override;
- QVariant icon(const QModelIndex &index) const;
+ QVariant data(const QModelIndex& index, int role) const override;
+ QVariant icon(const QModelIndex& index) const;
protected:
- bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override;
- QVariant styleData(const QModelIndex &index, int role) const;
+ bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override;
+ QVariant styleData(const QModelIndex& index, int role) const;
private:
BufferId _bufferId;
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "qssparser.h"
+
#include <tuple>
#include <utility>
#include <QApplication>
-#include "qssparser.h"
-
QssParser::QssParser()
{
_palette = QApplication::palette();
_uiStyleColorRoles["sender-color-0f"] = UiStyle::ColorRole::SenderColor0f;
}
-
-void QssParser::processStyleSheet(QString &ss)
+void QssParser::processStyleSheet(QString& ss)
{
if (ss.isEmpty())
return;
static const QRegExp blockrx("((?:ChatLine|ChatListItem|NickListItem)[^{]*)\\{([^}]+)\\}");
pos = 0;
while ((pos = blockrx.indexIn(ss, pos)) >= 0) {
- //qDebug() << blockrx.cap(1) << blockrx.cap(2);
+ // qDebug() << blockrx.cap(1) << blockrx.cap(2);
QString declaration = blockrx.cap(1).trimmed();
QString contents = blockrx.cap(2).trimmed();
parseChatLineBlock(declaration, contents);
else if (declaration.startsWith("ChatListItem") || declaration.startsWith("NickListItem"))
parseListItemBlock(declaration, contents);
- //else
+ // else
// TODO: add moar here
ss.remove(pos, blockrx.matchedLength());
}
}
-
/******** Parse a whole block: declaration { contents } *******/
-void QssParser::parseChatLineBlock(const QString &decl, const QString &contents)
+void QssParser::parseChatLineBlock(const QString& decl, const QString& contents)
{
UiStyle::FormatType fmtType;
UiStyle::MessageLabel label;
if (fmtType == UiStyle::FormatType::Invalid)
return;
- _formats[fmtType|label].merge(parseFormat(contents));
+ _formats[fmtType | label].merge(parseFormat(contents));
}
-
-void QssParser::parseListItemBlock(const QString &decl, const QString &contents)
+void QssParser::parseListItemBlock(const QString& decl, const QString& contents)
{
UiStyle::ItemFormatType fmtType = parseItemFormatType(decl);
if (fmtType == UiStyle::ItemFormatType::Invalid)
_listItemFormats[fmtType].merge(parseFormat(contents));
}
-
// Palette { ... } specifies the application palette
// ColorGroups can be specified like pseudo states, chaining is OR (contrary to normal CSS handling):
// Palette:inactive:disabled { ... } applies to both the Inactive and the Disabled state
-void QssParser::parsePaletteBlock(const QString &decl, const QString &contents)
+void QssParser::parsePaletteBlock(const QString& decl, const QString& contents)
{
QList<QPalette::ColorGroup> colorGroups;
}
if (!rx.cap(1).isEmpty()) {
QStringList groups = rx.cap(1).split(':', QString::SkipEmptyParts);
- foreach(QString g, groups) {
+ foreach (QString g, groups) {
if ((g == "normal" || g == "active") && !colorGroups.contains(QPalette::Active))
colorGroups.append(QPalette::Active);
else if (g == "inactive" && !colorGroups.contains(QPalette::Inactive))
}
// Now let's go through the roles
- foreach(QString line, contents.split(';', QString::SkipEmptyParts)) {
+ foreach (QString line, contents.split(';', QString::SkipEmptyParts)) {
int idx = line.indexOf(':');
if (idx <= 0) {
qWarning() << Q_FUNC_INFO << tr("Invalid palette role assignment: %1").arg(line.trimmed());
if (_paletteColorRoles.contains(rolestr)) {
QBrush brush = parseBrush(brushstr);
if (colorGroups.count()) {
- foreach(QPalette::ColorGroup group, colorGroups)
- _palette.setBrush(group, _paletteColorRoles.value(rolestr), brush);
+ foreach (QPalette::ColorGroup group, colorGroups)
+ _palette.setBrush(group, _paletteColorRoles.value(rolestr), brush);
}
else
_palette.setBrush(_paletteColorRoles.value(rolestr), brush);
}
}
-
/******** Determine format types from a block declaration ********/
-std::pair<UiStyle::FormatType, UiStyle::MessageLabel> QssParser::parseFormatType(const QString &decl)
+std::pair<UiStyle::FormatType, UiStyle::MessageLabel> QssParser::parseFormatType(const QString& decl)
{
using FormatType = UiStyle::FormatType;
using MessageLabel = UiStyle::MessageLabel;
// Next up: conditional (formats, labels, nickhash)
static const QRegExp condRx(R"lit(\s*([\w\-]+)\s*=\s*"(\w+)"\s*)lit");
if (!conditions.isEmpty()) {
- foreach(const QString &cond, conditions.split(',', QString::SkipEmptyParts)) {
+ foreach (const QString& cond, conditions.split(',', QString::SkipEmptyParts)) {
if (!condRx.exactMatch(cond)) {
qWarning() << Q_FUNC_INFO << tr("Invalid condition %1").arg(cond);
return invalid;
return std::make_pair(fmtType, label);
}
-
// FIXME: Code duplication
-UiStyle::ItemFormatType QssParser::parseItemFormatType(const QString &decl)
+UiStyle::ItemFormatType QssParser::parseItemFormatType(const QString& decl)
{
using ItemFormatType = UiStyle::ItemFormatType;
if (!properties.isEmpty()) {
QHash<QString, QString> props;
static const QRegExp propRx(R"lit(\s*([\w\-]+)\s*=\s*"([\w\-]+)"\s*)lit");
- foreach(const QString &prop, properties.split(',', QString::SkipEmptyParts)) {
+ foreach (const QString& prop, properties.split(',', QString::SkipEmptyParts)) {
if (!propRx.exactMatch(prop)) {
qWarning() << Q_FUNC_INFO << tr("Invalid proplist %1").arg(prop);
return ItemFormatType::Invalid;
}
}
}
- else { // NickList
+ else { // NickList
fmtType |= ItemFormatType::NickViewItem;
if (!type.isEmpty()) {
if (type == "user") {
return fmtType;
}
-
/******** Parse a whole format attribute block ********/
-QTextCharFormat QssParser::parseFormat(const QString &qss)
+QTextCharFormat QssParser::parseFormat(const QString& qss)
{
QTextCharFormat format;
- foreach(QString line, qss.split(';', QString::SkipEmptyParts)) {
+ foreach (QString line, qss.split(';', QString::SkipEmptyParts)) {
int idx = line.indexOf(':');
if (idx <= 0) {
qWarning() << Q_FUNC_INFO << tr("Invalid property declaration: %1").arg(line.trimmed());
/******** Boolean value ********/
-bool QssParser::parseBoolean(const QString &str, bool *ok) const
+bool QssParser::parseBoolean(const QString& str, bool* ok) const
{
if (ok)
*ok = true;
/******** Brush ********/
-QBrush QssParser::parseBrush(const QString &str, bool *ok)
+QBrush QssParser::parseBrush(const QString& str, bool* ok)
{
if (ok)
*ok = false;
return QBrush(c);
}
- if (str.startsWith("palette")) { // Palette color role
+ if (str.startsWith("palette")) { // Palette color role
// Does the palette follow the expected format? For example:
// palette(marker-line)
// palette ( system-color-0f )
return QBrush();
}
-
-QColor QssParser::parseColor(const QString &str)
+QColor QssParser::parseColor(const QString& str)
{
if (str.startsWith("rgba")) {
ColorTuple tuple = parseColorTuple(str.mid(4));
return QColor();
}
-
// get a list of comma-separated int values or percentages (rel to 0-255)
-QssParser::ColorTuple QssParser::parseColorTuple(const QString &str)
+QssParser::ColorTuple QssParser::parseColorTuple(const QString& str)
{
ColorTuple result;
static const QRegExp rx(R"(\(((\s*[0-9]{1,3}%?\s*)(,\s*[0-9]{1,3}%?\s*)*)\))");
return ColorTuple();
}
QStringList values = rx.cap(1).split(',');
- foreach(QString v, values) {
+ foreach (QString v, values) {
qreal val;
bool perc = false;
bool ok;
if (!ok)
return ColorTuple();
if (perc)
- val = 255 * val/100;
+ val = 255 * val / 100;
result.append(val);
}
return result;
}
-
-QGradientStops QssParser::parseGradientStops(const QString &str_)
+QGradientStops QssParser::parseGradientStops(const QString& str_)
{
QString str = str_;
QGradientStops result;
- static const QString rxFloat("(0?\\.[0-9]+|[01])"); // values between 0 and 1
+ static const QString rxFloat("(0?\\.[0-9]+|[01])"); // values between 0 and 1
static const QRegExp rx(QString(R"(\s*,?\s*stop:\s*(%1)\s+([^:]+)(,\s*stop:|$))").arg(rxFloat));
int idx;
while ((idx = rx.indexIn(str)) == 0) {
return result;
}
-
/******** Font Properties ********/
-void QssParser::parseFont(const QString &value, QTextCharFormat *format)
+void QssParser::parseFont(const QString& value, QTextCharFormat* format)
{
- static const QRegExp rx("((?:(?:normal|italic|oblique|underline|strikethrough|bold|100|200|300|400|500|600|700|800|900) ){0,2}) ?(\\d+)(pt|px)? \"(.*)\"");
+ static const QRegExp rx(
+ "((?:(?:normal|italic|oblique|underline|strikethrough|bold|100|200|300|400|500|600|700|800|900) ){0,2}) ?(\\d+)(pt|px)? \"(.*)\"");
if (!rx.exactMatch(value)) {
qWarning() << Q_FUNC_INFO << tr("Invalid font specification: %1").arg(value);
return;
format->setFontStrikeOut(false);
format->setFontWeight(QFont::Normal);
QStringList proplist = rx.cap(1).split(' ', QString::SkipEmptyParts);
- foreach(QString prop, proplist) {
+ foreach (QString prop, proplist) {
if (prop == "normal")
- ; // pass
+ ; // pass
else if (prop == "italic")
format->setFontItalic(true);
else if (prop == "underline")
format->setFontUnderline(true);
else if (prop == "strikethrough")
format->setFontStrikeOut(true);
- else if(prop == "oblique")
+ else if (prop == "oblique")
// Oblique is not a property supported by QTextCharFormat
format->setFontItalic(true);
else if (prop == "bold")
format->setFontWeight(QFont::Bold);
- else { // number
+ else { // number
int w = prop.toInt();
- format->setFontWeight(qMin(w / 8, 99)); // taken from Qt's qss parser
+ format->setFontWeight(qMin(w / 8, 99)); // taken from Qt's qss parser
}
}
format->setFontFamily(rx.cap(4));
}
-
-void QssParser::parseFontStyle(const QString &value, QTextCharFormat *format)
+void QssParser::parseFontStyle(const QString& value, QTextCharFormat* format)
{
if (value == "normal")
format->setFontItalic(false);
format->setFontUnderline(true);
else if (value == "strikethrough")
format->setFontStrikeOut(true);
- else if(value == "oblique")
+ else if (value == "oblique")
// Oblique is not a property supported by QTextCharFormat
format->setFontItalic(true);
else {
}
}
-
-void QssParser::parseFontWeight(const QString &value, QTextCharFormat *format)
+void QssParser::parseFontWeight(const QString& value, QTextCharFormat* format)
{
if (value == "normal")
format->setFontWeight(QFont::Normal);
qWarning() << Q_FUNC_INFO << tr("Invalid font weight specification: %1").arg(value);
return;
}
- format->setFontWeight(qMin(w / 8, 99)); // taken from Qt's qss parser
+ format->setFontWeight(qMin(w / 8, 99)); // taken from Qt's qss parser
}
}
-
-void QssParser::parseFontSize(const QString &value, QTextCharFormat *format)
+void QssParser::parseFontSize(const QString& value, QTextCharFormat* format)
{
static const QRegExp rx("(\\d+)(pt|px)");
if (!rx.exactMatch(value)) {
format->setFontPointSize(rx.cap(1).toInt());
}
-
-void QssParser::parseFontFamily(const QString &value, QTextCharFormat *format)
+void QssParser::parseFontFamily(const QString& value, QTextCharFormat* format)
{
QString family = value;
if (family.startsWith('"') && family.endsWith('"')) {
public:
QssParser();
- void processStyleSheet(QString &sheet);
+ void processStyleSheet(QString& sheet);
inline QPalette palette() const { return _palette; }
inline QVector<QBrush> uiStylePalette() const { return _uiStylePalette; }
- inline const QHash<quint64, QTextCharFormat> &formats() const { return _formats; }
- inline const QHash<UiStyle::ItemFormatType, QTextCharFormat> &listItemFormats() const { return _listItemFormats; }
+ inline const QHash<quint64, QTextCharFormat>& formats() const { return _formats; }
+ inline const QHash<UiStyle::ItemFormatType, QTextCharFormat>& listItemFormats() const { return _listItemFormats; }
protected:
using ColorTuple = QList<qreal>;
- void parseChatLineBlock(const QString &decl, const QString &contents);
- void parsePaletteBlock(const QString &decl, const QString &contents);
- void parseListItemBlock(const QString &decl, const QString &contents);
+ void parseChatLineBlock(const QString& decl, const QString& contents);
+ void parsePaletteBlock(const QString& decl, const QString& contents);
+ void parseListItemBlock(const QString& decl, const QString& contents);
- std::pair<UiStyle::FormatType, UiStyle::MessageLabel> parseFormatType(const QString &decl);
- UiStyle::ItemFormatType parseItemFormatType(const QString &decl);
+ std::pair<UiStyle::FormatType, UiStyle::MessageLabel> parseFormatType(const QString& decl);
+ UiStyle::ItemFormatType parseItemFormatType(const QString& decl);
- QTextCharFormat parseFormat(const QString &qss);
+ QTextCharFormat parseFormat(const QString& qss);
// Parse boolean properties
- bool parseBoolean(const QString &str, bool *ok = nullptr) const;
+ bool parseBoolean(const QString& str, bool* ok = nullptr) const;
// Parse color/brush-related properties
- QBrush parseBrush(const QString &str, bool *ok = nullptr);
- QColor parseColor(const QString &str);
- ColorTuple parseColorTuple(const QString &str);
- QGradientStops parseGradientStops(const QString &str);
+ QBrush parseBrush(const QString& str, bool* ok = nullptr);
+ QColor parseColor(const QString& str);
+ ColorTuple parseColorTuple(const QString& str);
+ QGradientStops parseGradientStops(const QString& str);
// Parse font-related properties
- void parseFont(const QString &str, QTextCharFormat *format);
- void parseFontStyle(const QString &str, QTextCharFormat *format);
- void parseFontWeight(const QString &str, QTextCharFormat *format);
- void parseFontSize(const QString &str, QTextCharFormat *format);
- void parseFontFamily(const QString &str, QTextCharFormat *format);
+ void parseFont(const QString& str, QTextCharFormat* format);
+ void parseFontStyle(const QString& str, QTextCharFormat* format);
+ void parseFontWeight(const QString& str, QTextCharFormat* format);
+ void parseFontSize(const QString& str, QTextCharFormat* format);
+ void parseFontFamily(const QString& str, QTextCharFormat* format);
QHash<QString, QPalette::ColorRole> _paletteColorRoles;
QHash<QString, UiStyle::ColorRole> _uiStyleColorRoles;
#include "resizingstackedwidget.h"
-ResizingStackedWidget::ResizingStackedWidget(QWidget *parent) : QStackedWidget(parent)
+ResizingStackedWidget::ResizingStackedWidget(QWidget* parent)
+ : QStackedWidget(parent)
{
connect(this, &QStackedWidget::currentChanged, this, &ResizingStackedWidget::indexChanged);
}
-
QSize ResizingStackedWidget::sizeHint() const
{
- QWidget *widget = currentWidget();
+ QWidget* widget = currentWidget();
if (!widget)
return {};
return widget->sizeHint();
}
-
void ResizingStackedWidget::indexChanged(int index)
{
Q_UNUSED(index)
Q_OBJECT
public:
- ResizingStackedWidget(QWidget *parent = nullptr);
+ ResizingStackedWidget(QWidget* parent = nullptr);
QSize sizeHint() const override;
#include "settingspage.h"
+#include <utility>
+
#include <QCheckBox>
#include <QComboBox>
#include <QSpinBox>
#include <QVariant>
-#include <utility>
#include "fontselector.h"
#include "uisettings.h"
#include "widgethelpers.h"
-SettingsPage::SettingsPage(QString category, QString title, QWidget *parent)
- : QWidget(parent),
- _category(std::move(category)),
- _title(std::move(title)),
- _changed(false),
- _autoWidgetsChanged(false)
-{
-}
-
+SettingsPage::SettingsPage(QString category, QString title, QWidget* parent)
+ : QWidget(parent)
+ , _category(std::move(category))
+ , _title(std::move(title))
+ , _changed(false)
+ , _autoWidgetsChanged(false)
+{}
void SettingsPage::setChangedState(bool hasChanged_)
{
}
}
-
-void SettingsPage::load(QCheckBox *box, bool checked)
+void SettingsPage::load(QCheckBox* box, bool checked)
{
box->setProperty("storedValue", checked);
box->setChecked(checked);
}
-
-bool SettingsPage::hasChanged(QCheckBox *box)
+bool SettingsPage::hasChanged(QCheckBox* box)
{
return box->property("storedValue").toBool() != box->isChecked();
}
-
-void SettingsPage::load(QComboBox *box, int index)
+void SettingsPage::load(QComboBox* box, int index)
{
box->setProperty("storedValue", index);
box->setCurrentIndex(index);
}
-
-bool SettingsPage::hasChanged(QComboBox *box)
+bool SettingsPage::hasChanged(QComboBox* box)
{
return box->property("storedValue").toInt() != box->currentIndex();
}
-
-void SettingsPage::load(QSpinBox *box, int value)
+void SettingsPage::load(QSpinBox* box, int value)
{
box->setProperty("storedValue", value);
box->setValue(value);
}
-
-bool SettingsPage::hasChanged(QSpinBox *box)
+bool SettingsPage::hasChanged(QSpinBox* box)
{
return box->property("storedValue").toInt() != box->value();
}
-
-void SettingsPage::load(FontSelector *box, QFont value)
+void SettingsPage::load(FontSelector* box, QFont value)
{
box->setProperty("storedValue", value);
box->setSelectedFont(value);
}
-
-bool SettingsPage::hasChanged(FontSelector *box)
+bool SettingsPage::hasChanged(FontSelector* box)
{
return box->property("storedValue").value<QFont>() != box->selectedFont();
}
-
/*** Auto child widget handling ***/
void SettingsPage::initAutoWidgets()
}
}
-
-void SettingsPage::findAutoWidgets(QObject *parent, QObjectList *autoList) const
+void SettingsPage::findAutoWidgets(QObject* parent, QObjectList* autoList) const
{
- foreach(QObject *child, parent->children()) {
+ foreach (QObject* child, parent->children()) {
if (child->property("settingsKey").isValid())
autoList->append(child);
findAutoWidgets(child, autoList);
}
}
-
-QByteArray SettingsPage::autoWidgetPropertyName(QObject *widget) const
+QByteArray SettingsPage::autoWidgetPropertyName(QObject* widget) const
{
QByteArray prop;
if (widget->inherits("ColorButton"))
return prop;
}
-
-QString SettingsPage::autoWidgetSettingsKey(QObject *widget) const
+QString SettingsPage::autoWidgetSettingsKey(QObject* widget) const
{
QString key = widget->property("settingsKey").toString();
if (key.isEmpty())
return key;
}
-
void SettingsPage::autoWidgetHasChanged()
{
bool changed_ = false;
- foreach(QObject *widget, _autoWidgets) {
+ foreach (QObject* widget, _autoWidgets) {
QVariant curValue = widget->property(autoWidgetPropertyName(widget));
if (!curValue.isValid())
qWarning() << "SettingsPage::autoWidgetHasChanged(): Unknown property";
}
}
-
void SettingsPage::load()
{
UiSettings s("");
- foreach(QObject *widget, _autoWidgets) {
+ foreach (QObject* widget, _autoWidgets) {
QString key = autoWidgetSettingsKey(widget);
QVariant val;
if (key.isEmpty())
emit changed(hasChanged());
}
-
void SettingsPage::save()
{
UiSettings s("");
- foreach(QObject *widget, _autoWidgets) {
+ foreach (QObject* widget, _autoWidgets) {
QString key = autoWidgetSettingsKey(widget);
QVariant val = widget->property(autoWidgetPropertyName(widget));
widget->setProperty("storedValue", val);
emit changed(hasChanged());
}
-
void SettingsPage::defaults()
{
- foreach(QObject *widget, _autoWidgets) {
+ foreach (QObject* widget, _autoWidgets) {
QVariant val = widget->property("defaultValue");
widget->setProperty(autoWidgetPropertyName(widget), val);
}
autoWidgetHasChanged();
}
-
-QVariant SettingsPage::loadAutoWidgetValue(const QString &widgetName)
+QVariant SettingsPage::loadAutoWidgetValue(const QString& widgetName)
{
qWarning() << "Could not load value for SettingsPage widget" << widgetName;
return QVariant();
}
-
-void SettingsPage::saveAutoWidgetValue(const QString &widgetName, const QVariant &)
+void SettingsPage::saveAutoWidgetValue(const QString& widgetName, const QVariant&)
{
qWarning() << "Could not save value for SettingsPage widget" << widgetName;
}
Q_OBJECT
public:
- SettingsPage(QString category, QString name, QWidget *parent = nullptr);
+ SettingsPage(QString category, QString name, QWidget* parent = nullptr);
//! The category of this settings page.
inline virtual QString category() const { return _category; }
* enabled. You also need to provide an implementation of defaults() then.
*
* The default implementation returns false.
- */
+ */
inline virtual bool hasDefaults() const { return false; }
//! Check if there are changes in the page, compared to the state saved in permanent storage.
inline virtual bool aboutToSave() { return true; }
//! sets checked state depending on \checked and stores the value for later comparision
- static void load(QCheckBox *box, bool checked);
- static bool hasChanged(QCheckBox *box);
- static void load(QComboBox *box, int index);
- static bool hasChanged(QComboBox *box);
- static void load(QSpinBox *box, int value);
- static bool hasChanged(QSpinBox *box);
- static void load(FontSelector *box, QFont value);
- static bool hasChanged(FontSelector *box);
+ static void load(QCheckBox* box, bool checked);
+ static bool hasChanged(QCheckBox* box);
+ static void load(QComboBox* box, int index);
+ static bool hasChanged(QComboBox* box);
+ static void load(QSpinBox* box, int value);
+ static bool hasChanged(QSpinBox* box);
+ static void load(FontSelector* box, QFont value);
+ static bool hasChanged(FontSelector* box);
public slots:
//! Save settings to permanent storage.
protected:
void initAutoWidgets();
- virtual QVariant loadAutoWidgetValue(const QString &widgetName);
- virtual void saveAutoWidgetValue(const QString &widgetName, const QVariant &value);
+ virtual QVariant loadAutoWidgetValue(const QString& widgetName);
+ virtual void saveAutoWidgetValue(const QString& widgetName, const QVariant& value);
signals:
//! Emitted whenever the widget state changes.
void autoWidgetHasChanged();
private:
- void findAutoWidgets(QObject *parent, QObjectList *widgetList) const;
- QByteArray autoWidgetPropertyName(QObject *widget) const;
- QString autoWidgetSettingsKey(QObject *widget) const;
+ void findAutoWidgets(QObject* parent, QObjectList* widgetList) const;
+ QByteArray autoWidgetPropertyName(QObject* widget) const;
+ QString autoWidgetSettingsKey(QObject* widget) const;
QString _category, _title;
bool _changed, _autoWidgetsChanged;
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "styledlabel.h"
+
#include <QPainter>
#include <QTextDocument>
#include <QTextLayout>
#include "graphicalui.h"
-#include "styledlabel.h"
#include "uistyle.h"
-StyledLabel::StyledLabel(QWidget *parent)
- : QFrame(parent),
- _alignment(Qt::AlignVCenter|Qt::AlignLeft)
+StyledLabel::StyledLabel(QWidget* parent)
+ : QFrame(parent)
+ , _alignment(Qt::AlignVCenter | Qt::AlignLeft)
{
setMouseTracking(true);
_layout.setTextOption(opt);
}
-
-void StyledLabel::setCustomFont(const QFont &font)
+void StyledLabel::setCustomFont(const QFont& font)
{
setFont(font);
_layout.setFont(font);
setText(_layout.text());
}
-
void StyledLabel::setWrapMode(QTextOption::WrapMode mode)
{
if (_wrapMode == mode)
layout();
}
-
void StyledLabel::setAlignment(Qt::Alignment alignment)
{
if (_alignment == alignment)
layout();
}
-
void StyledLabel::setResizeMode(ResizeMode mode)
{
if (_resizeMode == mode)
setWrapMode(QTextOption::NoWrap);
}
-
-void StyledLabel::resizeEvent(QResizeEvent *event)
+void StyledLabel::resizeEvent(QResizeEvent* event)
{
QFrame::resizeEvent(event);
layout();
}
-
QSize StyledLabel::sizeHint() const
{
return _sizeHint;
}
-
void StyledLabel::updateSizeHint()
{
QSize sh;
}
}
-
-void StyledLabel::setText(const QString &text)
+void StyledLabel::setText(const QString& text)
{
- UiStyle *style = GraphicalUi::uiStyle();
+ UiStyle* style = GraphicalUi::uiStyle();
UiStyle::StyledString sstr = style->styleString(style->mircToInternal(text), UiStyle::FormatType::PlainMsg);
QList<QTextLayout::FormatRange> layoutList = style->toTextLayoutList(sstr.formatList, sstr.plainText.length(), UiStyle::MessageLabel::None);
// Mark URLs
_clickables = ClickableList::fromString(sstr.plainText);
- foreach(Clickable click, _clickables) {
+ foreach (Clickable click, _clickables) {
if (click.type() == Clickable::Url) {
QTextLayout::FormatRange range;
range.start = click.start();
endHoverMode();
}
-
void StyledLabel::updateToolTip()
{
- if (frameRect().width() - 2*frameWidth() < _layout.minimumWidth())
+ if (frameRect().width() - 2 * frameWidth() < _layout.minimumWidth())
setToolTip(QString("<qt>%1</qt>").arg(_layout.text().toHtmlEscaped())); // only rich text gets wordwrapped!
else
setToolTip(QString());
}
-
void StyledLabel::layout()
{
qreal h = 0;
qreal w = contentsRect().width();
_layout.beginLayout();
- forever {
+ forever
+ {
QTextLine line = _layout.createLine();
if (!line.isValid())
break;
update();
}
-
-void StyledLabel::paintEvent(QPaintEvent *e)
+void StyledLabel::paintEvent(QPaintEvent* e)
{
QFrame::paintEvent(e);
QPainter painter(this);
_layout.draw(&painter, QPointF(contentsRect().x(), y), _extraLayoutList);
}
-
-int StyledLabel::posToCursor(const QPointF &pos)
+int StyledLabel::posToCursor(const QPointF& pos)
{
if (pos.y() < 0 || pos.y() > height())
return -1;
return -1;
}
-
-void StyledLabel::mouseMoveEvent(QMouseEvent *event)
+void StyledLabel::mouseMoveEvent(QMouseEvent* event)
{
if (event->buttons() == Qt::NoButton) {
Clickable click = _clickables.atCursorPos(posToCursor(event->localPos()));
}
}
-
-void StyledLabel::enterEvent(QEvent *)
+void StyledLabel::enterEvent(QEvent*)
{
if (resizeMode() == ResizeOnHover)
setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
}
-
-void StyledLabel::leaveEvent(QEvent *)
+void StyledLabel::leaveEvent(QEvent*)
{
endHoverMode();
if (resizeMode() == ResizeOnHover)
setWrapMode(QTextOption::NoWrap);
}
-
-void StyledLabel::mousePressEvent(QMouseEvent *event)
+void StyledLabel::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton) {
Clickable click = _clickables.atCursorPos(posToCursor(event->localPos()));
}
}
-
void StyledLabel::setHoverMode(int start, int length)
{
if (_extraLayoutList.count() >= 1 && _extraLayoutList.first().start == start && _extraLayoutList.first().length == length)
update();
}
-
void StyledLabel::endHoverMode()
{
_extraLayoutList.clear();
Q_OBJECT
public:
- enum ResizeMode {
+ enum ResizeMode
+ {
NoResize,
DynamicResize,
ResizeOnHover
};
- StyledLabel(QWidget *parent = nullptr);
+ StyledLabel(QWidget* parent = nullptr);
- void setText(const QString &text);
- void setCustomFont(const QFont &font);
+ void setText(const QString& text);
+ void setCustomFont(const QFont& font);
QSize sizeHint() const override;
- //virtual QSize minimumSizeHint() const;
+ // virtual QSize minimumSizeHint() const;
inline QTextOption::WrapMode wrapMode() const { return _wrapMode; }
void setWrapMode(QTextOption::WrapMode mode);
void setResizeMode(ResizeMode);
signals:
- void clickableActivated(const Clickable &click);
+ void clickableActivated(const Clickable& click);
protected:
- void paintEvent(QPaintEvent *event) override;
- void resizeEvent(QResizeEvent *event) override;
- void enterEvent(QEvent *) override;
- void leaveEvent(QEvent *) override;
- void mouseMoveEvent(QMouseEvent *event) override;
- void mousePressEvent(QMouseEvent *event) override;
-
- int posToCursor(const QPointF &pos);
+ void paintEvent(QPaintEvent* event) override;
+ void resizeEvent(QResizeEvent* event) override;
+ void enterEvent(QEvent*) override;
+ void leaveEvent(QEvent*) override;
+ void mouseMoveEvent(QMouseEvent* event) override;
+ void mousePressEvent(QMouseEvent* event) override;
+
+ int posToCursor(const QPointF& pos);
private:
QSize _sizeHint;
#include "tabcompleter.h"
+#include <QRegExp>
+
+#include "action.h"
+#include "actioncollection.h"
#include "buffermodel.h"
#include "client.h"
+#include "graphicalui.h"
#include "ircchannel.h"
#include "ircuser.h"
#include "multilineedit.h"
#include "network.h"
#include "networkmodel.h"
#include "uisettings.h"
-#include "action.h"
-#include "actioncollection.h"
-#include "graphicalui.h"
-
-#include <QRegExp>
-const Network *TabCompleter::_currentNetwork;
+const Network* TabCompleter::_currentNetwork;
BufferId TabCompleter::_currentBufferId;
QString TabCompleter::_currentBufferName;
TabCompleter::Type TabCompleter::_completionType;
-TabCompleter::TabCompleter(MultiLineEdit *_lineEdit)
- : QObject(_lineEdit),
- _lineEdit(_lineEdit),
- _enabled(false),
- _nickSuffix(": ")
+TabCompleter::TabCompleter(MultiLineEdit* _lineEdit)
+ : QObject(_lineEdit)
+ , _lineEdit(_lineEdit)
+ , _enabled(false)
+ , _nickSuffix(": ")
{
// This Action just serves as a container for the custom shortcut and isn't actually handled;
// apparently, using tab as an Action shortcut in an input widget is unreliable on some platforms (e.g. OS/2)
_lineEdit->installEventFilter(this);
- ActionCollection *coll = GraphicalUi::actionCollection("General");
- QAction *a = coll->addAction("TabCompletionKey", new Action(tr("Tab completion"), coll, this, &TabCompleter::onTabCompletionKey, QKeySequence(Qt::Key_Tab)));
- a->setEnabled(false); // avoid catching the shortcut
+ ActionCollection* coll = GraphicalUi::actionCollection("General");
+ QAction* a = coll->addAction("TabCompletionKey",
+ new Action(tr("Tab completion"), coll, this, &TabCompleter::onTabCompletionKey, QKeySequence(Qt::Key_Tab)));
+ a->setEnabled(false); // avoid catching the shortcut
}
-
void TabCompleter::onTabCompletionKey()
{
// do nothing; we use the event filter instead
}
-
void TabCompleter::buildCompletionList()
{
// ensure a safe state in case we return early.
// channel completion - add all channels of the current network to the map
if (tabAbbrev.startsWith('#')) {
_completionType = ChannelTab;
- foreach(IrcChannel *ircChannel, _currentNetwork->ircChannels()) {
+ foreach (IrcChannel* ircChannel, _currentNetwork->ircChannels()) {
if (regex.indexIn(ircChannel->name()) > -1)
_completionMap[ircChannel->name()] = ircChannel->name();
}
// user completion
_completionType = UserTab;
switch (static_cast<BufferInfo::Type>(currentIndex.data(NetworkModel::BufferTypeRole).toInt())) {
- case BufferInfo::ChannelBuffer:
- { // scope is needed for local var declaration
- IrcChannel *channel = _currentNetwork->ircChannel(_currentBufferName);
+ case BufferInfo::ChannelBuffer: { // scope is needed for local var declaration
+ IrcChannel* channel = _currentNetwork->ircChannel(_currentBufferName);
if (!channel)
return;
- foreach(IrcUser *ircUser, channel->ircUsers()) {
+ foreach (IrcUser* ircUser, channel->ircUsers()) {
if (regex.indexIn(ircUser->nick()) > -1)
_completionMap[ircUser->nick().toLower()] = ircUser->nick();
}
- }
- break;
+ } break;
case BufferInfo::QueryBuffer:
if (regex.indexIn(_currentBufferName) > -1)
_completionMap[_currentBufferName.toLower()] = _currentBufferName;
_lastCompletionLength = tabAbbrev.length();
}
-
void TabCompleter::complete()
{
TabCompletionSettings s;
}
}
-
void TabCompleter::reset()
{
_enabled = false;
}
-
-bool TabCompleter::eventFilter(QObject *obj, QEvent *event)
+bool TabCompleter::eventFilter(QObject* obj, QEvent* event)
{
if (obj != _lineEdit || event->type() != QEvent::KeyPress)
return QObject::eventFilter(obj, event);
- auto *keyEvent = static_cast<QKeyEvent *>(event);
+ auto* keyEvent = static_cast<QKeyEvent*>(event);
if (keyEvent->key() == GraphicalUi::actionCollection("General")->action("TabCompletionKey")->shortcut()[0])
complete();
return false;
}
-
// this determines the sort order
-bool TabCompleter::CompletionKey::operator<(const CompletionKey &other) const
+bool TabCompleter::CompletionKey::operator<(const CompletionKey& other) const
{
switch (_completionType) {
- case UserTab:
- {
- IrcUser *thisUser = _currentNetwork->ircUser(this->contents);
+ case UserTab: {
+ IrcUser* thisUser = _currentNetwork->ircUser(this->contents);
if (thisUser && _currentNetwork->isMe(thisUser))
return false;
- IrcUser *thatUser = _currentNetwork->ircUser(other.contents);
+ IrcUser* thatUser = _currentNetwork->ircUser(other.contents);
if (thatUser && _currentNetwork->isMe(thatUser))
return true;
if (thisTime.isValid() || thatTime.isValid())
return thisTime > thatTime;
- }
- break;
+ } break;
case ChannelTab:
if (QString::compare(_currentBufferName, this->contents, Qt::CaseInsensitive) == 0)
return true;
#include "uisupport-export.h"
+#include <QMap>
#include <QPointer>
#include <QString>
-#include <QMap>
#include "types.h"
Q_OBJECT
public:
- enum Type {
+ enum Type
+ {
UserTab = 0x01,
ChannelTab = 0x02
};
- explicit TabCompleter(MultiLineEdit *inputLine_);
+ explicit TabCompleter(MultiLineEdit* inputLine_);
void reset();
void complete();
- bool eventFilter(QObject *obj, QEvent *event) override;
+ bool eventFilter(QObject* obj, QEvent* event) override;
public slots:
void onTabCompletionKey();
private:
-
- struct CompletionKey {
- inline CompletionKey(const QString &n) { contents = n; }
- bool operator<(const CompletionKey &other) const;
+ struct CompletionKey
+ {
+ inline CompletionKey(const QString& n) { contents = n; }
+ bool operator<(const CompletionKey& other) const;
QString contents;
};
bool _enabled;
QString _nickSuffix;
- static const Network *_currentNetwork;
+ static const Network* _currentNetwork;
static BufferId _currentBufferId;
static QString _currentBufferName;
static Type _completionType;
#include "icon.h"
-ToolBarActionProvider::ToolBarActionProvider(QObject *parent)
+ToolBarActionProvider::ToolBarActionProvider(QObject* parent)
: NetworkModelController(parent)
{
registerAction(NetworkConnectAllWithDropdown, icon::get("network-connect"), tr("Connect"))->setToolTip(tr("Connect to IRC"));
registerAction(BufferPart, icon::get("irc-close-channel"), tr("Part"))->setToolTip(tr("Leave currently selected channel"));
registerAction(JoinChannel, icon::get("irc-join-channel"), tr("Join"))->setToolTip(tr("Join a channel"));
- registerAction(NickQuery, icon::get("mail-message-new"), tr("Query"))->setToolTip(tr("Start a private conversation")); // fix icon
- registerAction(NickWhois, icon::get("im-user"), tr("Whois"))->setToolTip(tr("Request user information")); // fix icon
+ registerAction(NickQuery, icon::get("mail-message-new"), tr("Query"))->setToolTip(tr("Start a private conversation")); // fix icon
+ registerAction(NickWhois, icon::get("im-user"), tr("Whois"))->setToolTip(tr("Request user information")); // fix icon
registerAction(NickOp, icon::get("irc-operator"), tr("Op"))->setToolTip(tr("Give operator privileges to user"));
registerAction(NickDeop, icon::get("irc-remove-operator"), tr("Deop"))->setToolTip(tr("Take operator privileges from user"));
updateStates();
}
-
void ToolBarActionProvider::disconnectedFromCore()
{
_currentBuffer = QModelIndex();
NetworkModelController::disconnectedFromCore();
}
-
void ToolBarActionProvider::updateStates()
{
- action(BufferPart)->setEnabled(_currentBuffer.isValid()
- && _currentBuffer.data(NetworkModel::BufferTypeRole) == BufferInfo::ChannelBuffer
- && _currentBuffer.data(NetworkModel::ItemActiveRole).toBool());
+ action(BufferPart)
+ ->setEnabled(_currentBuffer.isValid() && _currentBuffer.data(NetworkModel::BufferTypeRole) == BufferInfo::ChannelBuffer
+ && _currentBuffer.data(NetworkModel::ItemActiveRole).toBool());
}
-
-void ToolBarActionProvider::addActions(QToolBar *bar, ToolBarType type)
+void ToolBarActionProvider::addActions(QToolBar* bar, ToolBarType type)
{
switch (type) {
case MainToolBar:
}
}
-
-void ToolBarActionProvider::onCurrentBufferChanged(const QModelIndex &index)
+void ToolBarActionProvider::onCurrentBufferChanged(const QModelIndex& index)
{
_currentBuffer = index;
updateStates();
}
-
-void ToolBarActionProvider::onNickSelectionChanged(const QModelIndexList &indexList)
+void ToolBarActionProvider::onNickSelectionChanged(const QModelIndexList& indexList)
{
_selectedNicks = indexList;
updateStates();
}
-
// override those to set indexes right
-void ToolBarActionProvider::handleNetworkAction(ActionType type, QAction *action)
+void ToolBarActionProvider::handleNetworkAction(ActionType type, QAction* action)
{
setIndexList(_currentBuffer);
NetworkModelController::handleNetworkAction(type, action);
}
-
-void ToolBarActionProvider::handleBufferAction(ActionType type, QAction *action)
+void ToolBarActionProvider::handleBufferAction(ActionType type, QAction* action)
{
setIndexList(_currentBuffer);
NetworkModelController::handleBufferAction(type, action);
}
-
-void ToolBarActionProvider::handleNickAction(ActionType type, QAction *action)
+void ToolBarActionProvider::handleNickAction(ActionType type, QAction* action)
{
setIndexList(_selectedNicks);
NetworkModelController::handleNickAction(type, action);
}
-
-void ToolBarActionProvider::handleGeneralAction(ActionType type, QAction *action)
+void ToolBarActionProvider::handleGeneralAction(ActionType type, QAction* action)
{
setIndexList(_currentBuffer);
NetworkModelController::handleGeneralAction(type, action);
}
-
void ToolBarActionProvider::networkCreated(NetworkId id)
{
- const Network *net = Client::network(id);
- Action *act = new Action(net->networkName(), this);
+ const Network* net = Client::network(id);
+ Action* act = new Action(net->networkName(), this);
_networkActions[id] = act;
act->setObjectName(QString("NetworkAction-%1").arg(id.toInt()));
act->setData(QVariant::fromValue<NetworkId>(id));
networkUpdated(net);
}
-
void ToolBarActionProvider::networkRemoved(NetworkId id)
{
- Action *act = _networkActions.take(id);
+ Action* act = _networkActions.take(id);
if (act)
act->deleteLater();
}
-
-void ToolBarActionProvider::networkUpdated(const Network *net)
+void ToolBarActionProvider::networkUpdated(const Network* net)
{
if (!net)
- net = qobject_cast<const Network *>(sender());
+ net = qobject_cast<const Network*>(sender());
if (!net)
return;
- Action *act = _networkActions.value(net->networkId());
+ Action* act = _networkActions.value(net->networkId());
if (!act)
return;
_networksConnectMenu->removeAction(act);
_networksDisconnectMenu->removeAction(act);
- QMenu *newMenu = net->connectionState() != Network::Disconnected ? _networksDisconnectMenu : _networksConnectMenu;
+ QMenu* newMenu = net->connectionState() != Network::Disconnected ? _networksDisconnectMenu : _networksConnectMenu;
act->setText(net->networkName());
const int lastidx = newMenu->actions().count() - 2;
- QAction *beforeAction = newMenu->actions().at(lastidx);
+ QAction* beforeAction = newMenu->actions().at(lastidx);
for (int i = 0; i < newMenu->actions().count() - 2; i++) {
- QAction *action = newMenu->actions().at(i);
+ QAction* action = newMenu->actions().at(i);
if (net->networkName().localeAwareCompare(action->text()) < 0) {
beforeAction = action;
break;
action(JoinChannel)->setEnabled(_networksDisconnectMenu->actions().count() > 2);
}
-
void ToolBarActionProvider::connectOrDisconnectNet()
{
- auto *act = qobject_cast<QAction *>(sender());
+ auto* act = qobject_cast<QAction*>(sender());
if (!act)
return;
- const Network *net = Client::network(act->data().value<NetworkId>());
+ const Network* net = Client::network(act->data().value<NetworkId>());
if (!net)
return;
- if (net->connectionState() == Network::Disconnected) net->requestConnect();
- else net->requestDisconnect();
+ if (net->connectionState() == Network::Disconnected)
+ net->requestConnect();
+ else
+ net->requestDisconnect();
}
-
-//void ToolBarActionProvider::
+// void ToolBarActionProvider::
Q_OBJECT
public:
- ToolBarActionProvider(QObject *parent = nullptr);
+ ToolBarActionProvider(QObject* parent = nullptr);
- enum ToolBarType {
+ enum ToolBarType
+ {
MainToolBar,
ChatViewToolBar,
NickToolBar
};
- void addActions(QToolBar *, ToolBarType type);
+ void addActions(QToolBar*, ToolBarType type);
public slots:
void disconnectedFromCore() override;
- void onCurrentBufferChanged(const QModelIndex &);
- void onNickSelectionChanged(const QModelIndexList &);
+ void onCurrentBufferChanged(const QModelIndex&);
+ void onNickSelectionChanged(const QModelIndexList&);
protected:
- void handleNetworkAction(ActionType, QAction *) override;
- void handleBufferAction(ActionType, QAction *) override;
- void handleNickAction(ActionType, QAction *) override;
- void handleGeneralAction(ActionType, QAction *) override;
+ void handleNetworkAction(ActionType, QAction*) override;
+ void handleBufferAction(ActionType, QAction*) override;
+ void handleNickAction(ActionType, QAction*) override;
+ void handleGeneralAction(ActionType, QAction*) override;
private slots:
void networkCreated(NetworkId id);
void networkRemoved(NetworkId id);
- void networkUpdated(const Network *net = nullptr);
+ void networkUpdated(const Network* net = nullptr);
void connectOrDisconnectNet();
void updateStates();
private:
QMenu *_networksConnectMenu, *_networksDisconnectMenu;
- QHash<NetworkId, Action *> _networkActions;
+ QHash<NetworkId, Action*> _networkActions;
QModelIndex _currentBuffer;
QModelIndexList _selectedNicks;
};
#include <QScrollBar>
#include <QTouchEvent>
-
-TreeViewTouch::TreeViewTouch(QWidget *parent)
+TreeViewTouch::TreeViewTouch(QWidget* parent)
: QTreeView(parent)
{
setAttribute(Qt::WA_AcceptTouchEvents);
}
-
-bool TreeViewTouch::event(QEvent *event) {
- if (event->type() == QEvent::TouchBegin && ((QTouchEvent*)event)->device()->type()==QTouchDevice::TouchScreen) {
+bool TreeViewTouch::event(QEvent* event)
+{
+ if (event->type() == QEvent::TouchBegin && ((QTouchEvent*)event)->device()->type() == QTouchDevice::TouchScreen) {
// Register that we may be scrolling, set the scroll mode to scroll-per-pixel
// and accept the event (return true) so that we will receive TouchUpdate and TouchEnd/TouchCancel
_touchScrollInProgress = true;
return QTreeView::event(event);
}
-
-void TreeViewTouch::mousePressEvent(QMouseEvent *event) {
+void TreeViewTouch::mousePressEvent(QMouseEvent* event)
+{
if (!_touchScrollInProgress)
QTreeView::mousePressEvent(event);
}
-
-void TreeViewTouch::mouseMoveEvent(QMouseEvent *event) {
+void TreeViewTouch::mouseMoveEvent(QMouseEvent* event)
+{
if (!_touchScrollInProgress)
QTreeView::mouseMoveEvent(event);
}
#include <QTreeView>
/**
-* This class handles Touch Events for TreeViews
-*/
+ * This class handles Touch Events for TreeViews
+ */
class UISUPPORT_EXPORT TreeViewTouch : public QTreeView
{
Q_OBJECT
public:
- explicit TreeViewTouch(QWidget *parent = nullptr);
+ explicit TreeViewTouch(QWidget* parent = nullptr);
protected:
-
/**
- * Handles Events
- *
- * @param[in,out] an event
- * @returns true if event got handled, false if event got ignored
- */
- bool event(QEvent *event) override;
+ * Handles Events
+ *
+ * @param[in,out] an event
+ * @returns true if event got handled, false if event got ignored
+ */
+ bool event(QEvent* event) override;
/**
- * Handles Mouse Move Events
- *
- * Suppresses Events during Touch-Scroll
- *
- * @param[in,out] An Event
- */
- void mouseMoveEvent(QMouseEvent *event) override;
+ * Handles Mouse Move Events
+ *
+ * Suppresses Events during Touch-Scroll
+ *
+ * @param[in,out] An Event
+ */
+ void mouseMoveEvent(QMouseEvent* event) override;
/**
- * Handles Mouse Press Events
- *
- * Suppresses Events during Touch-Scroll
- *
- * @param[in,out] An Event
- */
- void mousePressEvent(QMouseEvent *event) override;
+ * Handles Mouse Press Events
+ *
+ * Suppresses Events during Touch-Scroll
+ *
+ * @param[in,out] An Event
+ */
+ void mousePressEvent(QMouseEvent* event) override;
private:
bool _touchScrollInProgress = false;
UiSettings::UiSettings(QString group)
: ClientSettings(std::move(group))
-{
-}
-
+{}
-void UiSettings::setValue(const QString &key, const QVariant &data)
+void UiSettings::setValue(const QString& key, const QVariant& data)
{
setLocalValue(key, data);
}
-
-QVariant UiSettings::value(const QString &key, const QVariant &def) const
+QVariant UiSettings::value(const QString& key, const QVariant& def) const
{
return localValue(key, def);
}
-
-bool UiSettings::valueExists(const QString &key) const
+bool UiSettings::valueExists(const QString& key) const
{
return localKeyExists(key);
}
-
-void UiSettings::remove(const QString &key)
+void UiSettings::remove(const QString& key)
{
removeLocalKey(key);
}
UiStyleSettings::UiStyleSettings()
: UiSettings("UiStyle")
-{
-}
-
+{}
-UiStyleSettings::UiStyleSettings(const QString &subGroup)
+UiStyleSettings::UiStyleSettings(const QString& subGroup)
: UiSettings(QString("UiStyle/%1").arg(subGroup))
-{
-}
-
+{}
-void UiStyleSettings::setCustomFormat(UiStyle::FormatType ftype, const QTextCharFormat &format)
+void UiStyleSettings::setCustomFormat(UiStyle::FormatType ftype, const QTextCharFormat& format)
{
setLocalValue(QString("Format/%1").arg(static_cast<quint32>(ftype)), format);
}
-
QTextCharFormat UiStyleSettings::customFormat(UiStyle::FormatType ftype) const
{
return localValue(QString("Format/%1").arg(static_cast<quint32>(ftype)), QTextFormat()).value<QTextFormat>().toCharFormat();
}
-
void UiStyleSettings::removeCustomFormat(UiStyle::FormatType ftype)
{
removeLocalKey(QString("Format/%1").arg(static_cast<quint32>(ftype)));
}
-
QList<UiStyle::FormatType> UiStyleSettings::availableFormats() const
{
QList<UiStyle::FormatType> formats;
QStringList list = localChildKeys("Format");
- foreach(QString type, list) {
+ foreach (QString type, list) {
formats << (UiStyle::FormatType)type.toInt();
}
return formats;
}
-
/**************************************************************************
* SessionSettings
**************************************************************************/
SessionSettings::SessionSettings(QString sessionId, QString group)
: UiSettings(std::move(group))
, _sessionId(std::move(sessionId))
-{
-}
+{}
-
-void SessionSettings::setValue(const QString &key, const QVariant &data)
+void SessionSettings::setValue(const QString& key, const QVariant& data)
{
setLocalValue(QString("%1/%2").arg(_sessionId, key), data);
}
-
-QVariant SessionSettings::value(const QString &key, const QVariant &def) const
+QVariant SessionSettings::value(const QString& key, const QVariant& def) const
{
return localValue(QString("%1/%2").arg(_sessionId, key), def);
}
-
-void SessionSettings::removeKey(const QString &key)
+void SessionSettings::removeKey(const QString& key)
{
removeLocalKey(QString("%1/%2").arg(_sessionId, key));
}
-
void SessionSettings::cleanup()
{
QStringList sessions = localChildGroups();
QString str;
SessionSettings s(sessionId());
- foreach(str, sessions) {
+ foreach (str, sessions) {
// load session and check age
s.setSessionId(str);
if (s.sessionAge() > 3) {
}
}
-
QString SessionSettings::sessionId() const
{
return _sessionId;
}
-
void SessionSettings::setSessionId(QString sessionId)
{
_sessionId = std::move(sessionId);
}
-
int SessionSettings::sessionAge()
{
QVariant val = localValue(QString("%1/_sessionAge").arg(_sessionId), 0);
}
else {
// no int saved, delete session
- //qDebug() << QString("deleting invalid session %1 (invalid session age found)").arg(_sessionId);
+ // qDebug() << QString("deleting invalid session %1 (invalid session age found)").arg(_sessionId);
removeSession();
}
return 10;
}
-
void SessionSettings::removeSession()
{
QStringList keys = localChildKeys(sessionId());
- foreach(QString k, keys) {
+ foreach (QString k, keys) {
removeKey(k);
}
}
-
void SessionSettings::setSessionAge(int age)
{
setValue(QString("_sessionAge"), age);
}
-
void SessionSettings::sessionAging()
{
QStringList sessions = localChildGroups();
QString str;
SessionSettings s(sessionId());
- foreach(str, sessions) {
+ foreach (str, sessions) {
// load session and check age
s.setSessionId(str);
- s.setSessionAge(s.sessionAge()+1);
+ s.setSessionAge(s.sessionAge() + 1);
}
}
-
/**************************************************************************
* ShortcutSettings
**************************************************************************/
ShortcutSettings::ShortcutSettings()
: UiSettings("Shortcuts")
-{
-}
-
+{}
void ShortcutSettings::clear()
{
- for (auto &&key : allLocalKeys()) {
+ for (auto&& key : allLocalKeys()) {
removeLocalKey(key);
}
}
-
QStringList ShortcutSettings::savedShortcuts() const
{
return localChildKeys();
}
-
-QKeySequence ShortcutSettings::loadShortcut(const QString &name) const
+QKeySequence ShortcutSettings::loadShortcut(const QString& name) const
{
return localValue(name, QKeySequence()).value<QKeySequence>();
}
-
-void ShortcutSettings::saveShortcut(const QString &name, const QKeySequence &seq)
+void ShortcutSettings::saveShortcut(const QString& name, const QKeySequence& seq)
{
setLocalValue(name, seq);
}
public:
UiSettings(QString group = "Ui");
- virtual void setValue(const QString &key, const QVariant &data);
- virtual QVariant value(const QString &key, const QVariant &def = {}) const;
+ virtual void setValue(const QString& key, const QVariant& data);
+ virtual QVariant value(const QString& key, const QVariant& def = {}) const;
/**
* Gets if a value exists in settings
* @param[in] key ID of local settings key
* @returns True if key exists in settings, otherwise false
*/
- bool valueExists(const QString &key) const;
+ bool valueExists(const QString& key) const;
- void remove(const QString &key);
+ void remove(const QString& key);
};
-
class UISUPPORT_EXPORT UiStyleSettings : public UiSettings
{
public:
UiStyleSettings();
- UiStyleSettings(const QString &subGroup);
+ UiStyleSettings(const QString& subGroup);
- void setCustomFormat(UiStyle::FormatType, const QTextCharFormat &format);
+ void setCustomFormat(UiStyle::FormatType, const QTextCharFormat& format);
QTextCharFormat customFormat(UiStyle::FormatType) const;
void removeCustomFormat(UiStyle::FormatType);
QList<UiStyle::FormatType> availableFormats() const;
};
-
class UISUPPORT_EXPORT SessionSettings : public UiSettings
{
public:
SessionSettings(QString sessionId, QString group = "Session");
- void setValue(const QString &key, const QVariant &data) override;
- QVariant value(const QString &key, const QVariant &def = {}) const override;
+ void setValue(const QString& key, const QVariant& data) override;
+ QVariant value(const QString& key, const QVariant& def = {}) const override;
- void removeKey(const QString &key);
+ void removeKey(const QString& key);
void removeSession();
void cleanup();
QString _sessionId;
};
-
class UISUPPORT_EXPORT ShortcutSettings : public UiSettings
{
public:
QStringList savedShortcuts() const;
- void saveShortcut(const QString &name, const QKeySequence &shortcut);
- QKeySequence loadShortcut(const QString &name) const;
+ void saveShortcut(const QString& name, const QKeySequence& shortcut);
+ QKeySequence loadShortcut(const QString& name) const;
};
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
+#include "uistyle.h"
+
#include <utility>
#include <vector>
#include "icon.h"
#include "qssparser.h"
#include "quassel.h"
-#include "uistyle.h"
#include "uisettings.h"
#include "util.h"
QHash<QString, UiStyle::FormatType> UiStyle::_formatCodes;
-bool UiStyle::_useCustomTimestampFormat; /// If true, use the custom timestamp format
-QString UiStyle::_timestampFormatString; /// Timestamp format
-QString UiStyle::_systemTimestampFormatString; /// Cached copy of system locale timestamp format
-UiStyle::SenderPrefixMode UiStyle::_senderPrefixDisplay; /// Display of prefix modes before sender
-bool UiStyle::_showSenderBrackets; /// If true, show brackets around sender names
+bool UiStyle::_useCustomTimestampFormat; /// If true, use the custom timestamp format
+QString UiStyle::_timestampFormatString; /// Timestamp format
+QString UiStyle::_systemTimestampFormatString; /// Cached copy of system locale timestamp format
+UiStyle::SenderPrefixMode UiStyle::_senderPrefixDisplay; /// Display of prefix modes before sender
+bool UiStyle::_showSenderBrackets; /// If true, show brackets around sender names
namespace {
// Extended mIRC colors as defined in https://modern.ircdocs.horse/formatting.html#colors-16-98
QColor extendedMircColor(int number)
{
- static const std::vector<QColor> colorMap = {
- "#470000", "#472100", "#474700", "#324700", "#004700", "#00472c", "#004747", "#002747", "#000047", "#2e0047", "#470047", "#47002a",
- "#740000", "#743a00", "#747400", "#517400", "#007400", "#007449", "#007474", "#004074", "#000074", "#4b0074", "#740074", "#740045",
- "#b50000", "#b56300", "#b5b500", "#7db500", "#00b500", "#00b571", "#00b5b5", "#0063b5", "#0000b5", "#7500b5", "#b500b5", "#b5006b",
- "#ff0000", "#ff8c00", "#ffff00", "#b2ff00", "#00ff00", "#00ffa0", "#00ffff", "#008cff", "#0000ff", "#a500ff", "#ff00ff", "#ff0098",
- "#ff5959", "#ffb459", "#ffff71", "#cfff60", "#6fff6f", "#65ffc9", "#6dffff", "#59b4ff", "#5959ff", "#c459ff", "#ff66ff", "#ff59bc",
- "#ff9c9c", "#ffd39c", "#ffff9c", "#e2ff9c", "#9cff9c", "#9cffdb", "#9cffff", "#9cd3ff", "#9c9cff", "#dc9cff", "#ff9cff", "#ff94d3",
- "#000000", "#131313", "#282828", "#363636", "#4d4d4d", "#656565", "#818181", "#9f9f9f", "#bcbcbc", "#e2e2e2", "#ffffff"
- };
+ static const std::vector<QColor> colorMap = {"#470000", "#472100", "#474700", "#324700", "#004700", "#00472c", "#004747", "#002747",
+ "#000047", "#2e0047", "#470047", "#47002a", "#740000", "#743a00", "#747400", "#517400",
+ "#007400", "#007449", "#007474", "#004074", "#000074", "#4b0074", "#740074", "#740045",
+ "#b50000", "#b56300", "#b5b500", "#7db500", "#00b500", "#00b571", "#00b5b5", "#0063b5",
+ "#0000b5", "#7500b5", "#b500b5", "#b5006b", "#ff0000", "#ff8c00", "#ffff00", "#b2ff00",
+ "#00ff00", "#00ffa0", "#00ffff", "#008cff", "#0000ff", "#a500ff", "#ff00ff", "#ff0098",
+ "#ff5959", "#ffb459", "#ffff71", "#cfff60", "#6fff6f", "#65ffc9", "#6dffff", "#59b4ff",
+ "#5959ff", "#c459ff", "#ff66ff", "#ff59bc", "#ff9c9c", "#ffd39c", "#ffff9c", "#e2ff9c",
+ "#9cff9c", "#9cffdb", "#9cffff", "#9cd3ff", "#9c9cff", "#dc9cff", "#ff9cff", "#ff94d3",
+ "#000000", "#131313", "#282828", "#363636", "#4d4d4d", "#656565", "#818181", "#9f9f9f",
+ "#bcbcbc", "#e2e2e2", "#ffffff"};
if (number < 16)
return {};
size_t index = number - 16;
return (index < colorMap.size() ? colorMap[index] : QColor{});
}
-}
+} // namespace
-UiStyle::UiStyle(QObject *parent)
+UiStyle::UiStyle(QObject* parent)
: QObject(parent)
, _channelJoinedIcon{icon::get("irc-channel-active")}
, _channelPartedIcon{icon::get("irc-channel-inactive")}
loadStyleSheet();
}
-
UiStyle::~UiStyle()
{
qDeleteAll(_metricsCache);
}
-
void UiStyle::reload()
{
loadStyleSheet();
}
-
void UiStyle::loadStyleSheet()
{
qDeleteAll(_metricsCache);
emit changed();
}
-
-QString UiStyle::loadStyleSheet(const QString &styleSheet, bool shouldExist)
+QString UiStyle::loadStyleSheet(const QString& styleSheet, bool shouldExist)
{
QString ss = styleSheet;
if (ss.startsWith("file:///")) {
return ss;
}
-
void UiStyle::updateSystemTimestampFormat()
{
// Does the system locale use AM/PM designators? For example:
if (regExpMatchAMPM.exactMatch(QLocale().timeFormat(QLocale::ShortFormat))) {
// AM/PM style used
_systemTimestampFormatString = " h:mm:ss ap";
- } else {
+ }
+ else {
// 24-hour style used
_systemTimestampFormatString = " hh:mm:ss";
}
// ChatScene::updateTimestampHasBrackets() to true or false as needed!
}
-
// FIXME The following should trigger a reload/refresh of the chat view.
void UiStyle::setUseCustomTimestampFormat(bool enabled)
{
}
}
-void UiStyle::setTimestampFormatString(const QString &format)
+void UiStyle::setTimestampFormatString(const QString& format)
{
if (_timestampFormatString != format) {
_timestampFormatString = format;
}
}
-
-void UiStyle::allowMircColorsChanged(const QVariant &v)
+void UiStyle::allowMircColorsChanged(const QVariant& v)
{
_allowMircColors = v.toBool();
emit changed();
}
-
/******** ItemView Styling *******/
-void UiStyle::showItemViewIconsChanged(const QVariant &v)
+void UiStyle::showItemViewIconsChanged(const QVariant& v)
{
_showBufferViewIcons = _showNickViewIcons = v.toBool();
}
-
-QVariant UiStyle::bufferViewItemData(const QModelIndex &index, int role) const
+QVariant UiStyle::bufferViewItemData(const QModelIndex& index, int role) const
{
BufferInfo::Type type = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).toInt();
bool isActive = index.data(NetworkModel::ItemActiveRole).toBool();
return itemData(role, fmt);
}
-
-QVariant UiStyle::nickViewItemData(const QModelIndex &index, int role) const
+QVariant UiStyle::nickViewItemData(const QModelIndex& index, int role) const
{
NetworkModel::ItemType type = (NetworkModel::ItemType)index.data(NetworkModel::ItemTypeRole).toInt();
return QVariant();
switch (type) {
- case NetworkModel::UserCategoryItemType:
- {
+ case NetworkModel::UserCategoryItemType: {
int categoryId = index.data(TreeModel::SortRole).toInt();
if (categoryId <= _opIconLimit)
return _categoryOpIcon;
return itemData(role, fmt);
}
-
-QVariant UiStyle::itemData(int role, const QTextCharFormat &format) const
+QVariant UiStyle::itemData(int role, const QTextCharFormat& format) const
{
switch (role) {
case Qt::FontRole:
}
}
-
/******** Caching *******/
QTextCharFormat UiStyle::parsedFormat(quint64 key) const
namespace {
// Create unique key for given Format object and message label
-QString formatKey(const UiStyle::Format &format, UiStyle::MessageLabel label)
+QString formatKey(const UiStyle::Format& format, UiStyle::MessageLabel label)
{
- return QString::number(format.type | label, 16)
- + (format.foreground.isValid() ? format.foreground.name() : "#------")
- + (format.background.isValid() ? format.background.name() : "#------");
+ return QString::number(format.type | label, 16) + (format.foreground.isValid() ? format.foreground.name() : "#------")
+ + (format.background.isValid() ? format.background.name() : "#------");
}
-}
+} // namespace
-QTextCharFormat UiStyle::cachedFormat(const Format &format, MessageLabel messageLabel) const
+QTextCharFormat UiStyle::cachedFormat(const Format& format, MessageLabel messageLabel) const
{
return _formatCache.value(formatKey(format, messageLabel), QTextCharFormat());
}
-
-void UiStyle::setCachedFormat(const QTextCharFormat &charFormat, const Format &format, MessageLabel messageLabel) const
+void UiStyle::setCachedFormat(const QTextCharFormat& charFormat, const Format& format, MessageLabel messageLabel) const
{
_formatCache[formatKey(format, messageLabel)] = charFormat;
}
-
-QFontMetricsF *UiStyle::fontMetrics(FormatType ftype, MessageLabel label) const
+QFontMetricsF* UiStyle::fontMetrics(FormatType ftype, MessageLabel label) const
{
// QFontMetricsF is not assignable, so we need to store pointers :/
quint64 key = ftype | label;
return (_metricsCache[key] = new QFontMetricsF(format({ftype, {}, {}}, label).font()));
}
-
/******** Generate formats ********/
// NOTE: This and the following functions are intimately tied to the values in FormatType. Don't change this
// until you _really_ know what you do!
-QTextCharFormat UiStyle::format(const Format &format, MessageLabel label) const
+QTextCharFormat UiStyle::format(const Format& format, MessageLabel label) const
{
if (format.type == FormatType::Invalid)
return {};
return charFormat;
}
-
-void UiStyle::mergeFormat(QTextCharFormat &charFormat, const Format &format, MessageLabel label) const
+void UiStyle::mergeFormat(QTextCharFormat& charFormat, const Format& format, MessageLabel label) const
{
mergeSubElementFormat(charFormat, format.type & 0x00ff, label);
// TODO: allow combinations for mirc formats and colors (each), e.g. setting a special format for "bold and italic"
// or "foreground 01 and background 03"
- if ((format.type & 0xfff00) != FormatType::Base) { // element format
+ if ((format.type & 0xfff00) != FormatType::Base) { // element format
for (quint32 mask = 0x00100; mask <= 0x80000; mask <<= 1) {
if ((format.type & mask) != FormatType::Base) {
mergeSubElementFormat(charFormat, format.type & (mask | 0xff), label);
}
}
-
// Merge a subelement format into an existing message format
-void UiStyle::mergeSubElementFormat(QTextCharFormat &fmt, FormatType ftype, MessageLabel label) const
+void UiStyle::mergeSubElementFormat(QTextCharFormat& fmt, FormatType ftype, MessageLabel label) const
{
quint64 key = ftype | label;
- fmt.merge(parsedFormat(key & 0x0000ffffffffff00ull)); // label + subelement
- fmt.merge(parsedFormat(key & 0x0000ffffffffffffull)); // label + subelement + msgtype
- fmt.merge(parsedFormat(key & 0xffffffffffffff00ull)); // label + subelement + nickhash
- fmt.merge(parsedFormat(key & 0xffffffffffffffffull)); // label + subelement + nickhash + msgtype
+ fmt.merge(parsedFormat(key & 0x0000ffffffffff00ull)); // label + subelement
+ fmt.merge(parsedFormat(key & 0x0000ffffffffffffull)); // label + subelement + msgtype
+ fmt.merge(parsedFormat(key & 0xffffffffffffff00ull)); // label + subelement + nickhash
+ fmt.merge(parsedFormat(key & 0xffffffffffffffffull)); // label + subelement + nickhash + msgtype
}
-
-void UiStyle::mergeColors(QTextCharFormat &charFormat, const Format &format, MessageLabel label) const
+void UiStyle::mergeColors(QTextCharFormat& charFormat, const Format& format, MessageLabel label) const
{
bool allowFg = charFormat.property(static_cast<int>(FormatProperty::AllowForegroundOverride)).toBool();
bool allowBg = charFormat.property(static_cast<int>(FormatProperty::AllowBackgroundOverride)).toBool();
charFormat.setBackground(format.background);
}
-
UiStyle::FormatType UiStyle::formatType(Message::Type msgType)
{
switch (msgType) {
case Message::Invite:
return FormatType::InviteMsg;
}
- //Q_ASSERT(false); // we need to handle all message types
+ // Q_ASSERT(false); // we need to handle all message types
qWarning() << Q_FUNC_INFO << "Unknown message type:" << msgType;
return FormatType::ErrorMsg;
}
-
-UiStyle::FormatType UiStyle::formatType(const QString &code)
+UiStyle::FormatType UiStyle::formatType(const QString& code)
{
if (_formatCodes.contains(code))
return _formatCodes.value(code);
return FormatType::Invalid;
}
-
QString UiStyle::formatCode(FormatType ftype)
{
return _formatCodes.key(ftype);
}
-
-QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList &formatList, int textLength, MessageLabel messageLabel) const
+QList<QTextLayout::FormatRange> UiStyle::toTextLayoutList(const FormatList& formatList, int textLength, MessageLabel messageLabel) const
{
QList<QTextLayout::FormatRange> formatRanges;
QTextLayout::FormatRange range;
return formatRanges;
}
-
// This method expects a well-formatted string, there is no error checking!
// Since we create those ourselves, we should be pretty safe that nobody does something crappy here.
-UiStyle::StyledString UiStyle::styleString(const QString &s_, FormatType baseFormat)
+UiStyle::StyledString UiStyle::styleString(const QString& s_, FormatType baseFormat)
{
QString s = s_;
StyledString result;
}
Format curfmt{baseFormat, {}, {}};
- QChar fgChar{'f'}; // character to indicate foreground color, changed when reversing
+ QChar fgChar{'f'}; // character to indicate foreground color, changed when reversing
- int pos = 0; quint16 length = 0;
+ int pos = 0;
+ quint16 length = 0;
for (;;) {
pos = s.indexOf('%', pos);
- if (pos < 0) break;
- if (s[pos+1] == '%') { // escaped %, we just remove one and continue
+ if (pos < 0)
+ break;
+ if (s[pos + 1] == '%') { // escaped %, we just remove one and continue
s.remove(pos, 1);
pos++;
continue;
}
- if (s[pos+1] == 'D' && s[pos+2] == 'c') { // mIRC color code
- if (s[pos+3] == '-') { // color off
+ if (s[pos + 1] == 'D' && s[pos + 2] == 'c') { // mIRC color code
+ if (s[pos + 3] == '-') { // color off
curfmt.type &= 0x003fffff;
curfmt.foreground = QColor{};
curfmt.background = QColor{};
length = 4;
}
else {
- quint32 color = 10 * s[pos+4].digitValue() + s[pos+5].digitValue();
+ quint32 color = 10 * s[pos + 4].digitValue() + s[pos + 5].digitValue();
// Color values 0-15 are traditional mIRC colors, defined in the stylesheet and thus going through the format engine
// Larger color values are hardcoded and applied separately (cf. https://modern.ircdocs.horse/formatting.html#colors-16-98)
- if (s[pos+3] == fgChar) {
+ if (s[pos + 3] == fgChar) {
if (color < 16) {
// Traditional mIRC color, defined in the stylesheet
curfmt.type &= 0xf0ffffff;
length = 6;
}
}
- else if (s[pos+1] == 'D' && s[pos+2] == 'h') { // Hex color
- QColor color{s.mid(pos+4, 7)};
- if (s[pos+3] == fgChar) {
+ else if (s[pos + 1] == 'D' && s[pos + 2] == 'h') { // Hex color
+ QColor color{s.mid(pos + 4, 7)};
+ if (s[pos + 3] == fgChar) {
curfmt.type &= 0xf0bfffff; // mask out mIRC foreground color
curfmt.foreground = std::move(color);
}
}
length = 11;
}
- else if (s[pos+1] == 'O') { // reset formatting
- curfmt.type &= 0x000000ff; // we keep message type-specific formatting
+ else if (s[pos + 1] == 'O') { // reset formatting
+ curfmt.type &= 0x000000ff; // we keep message type-specific formatting
curfmt.foreground = QColor{};
curfmt.background = QColor{};
fgChar = 'f';
length = 2;
}
- else if (s[pos+1] == 'R') { // Reverse colors
+ else if (s[pos + 1] == 'R') { // Reverse colors
fgChar = (fgChar == 'f' ? 'b' : 'f');
auto orig = static_cast<quint32>(curfmt.type & 0xffc00000);
curfmt.type &= 0x003fffff;
- curfmt.type |= (orig & 0x00400000) <<1;
- curfmt.type |= (orig & 0x0f000000) <<4;
- curfmt.type |= (orig & 0x00800000) >>1;
- curfmt.type |= (orig & 0xf0000000) >>4;
+ curfmt.type |= (orig & 0x00400000) << 1;
+ curfmt.type |= (orig & 0x0f000000) << 4;
+ curfmt.type |= (orig & 0x00800000) >> 1;
+ curfmt.type |= (orig & 0xf0000000) >> 4;
std::swap(curfmt.foreground, curfmt.background);
length = 2;
}
- else { // all others are toggles
- QString code = QString("%") + s[pos+1];
- if (s[pos+1] == 'D') code += s[pos+2];
+ else { // all others are toggles
+ QString code = QString("%") + s[pos + 1];
+ if (s[pos + 1] == 'D')
+ code += s[pos + 2];
FormatType ftype = formatType(code);
if (ftype == FormatType::Invalid) {
pos++;
return result;
}
-
-QString UiStyle::mircToInternal(const QString &mirc_)
+QString UiStyle::mircToInternal(const QString& mirc_)
{
QString mirc;
mirc.reserve(mirc_.size());
- foreach (const QChar &c, mirc_) {
+ foreach (const QChar& c, mirc_) {
if ((c < '\x20' || c == '\x7f') && c != '\x03' && c != '\x04') {
switch (c.unicode()) {
- case '\x02':
- mirc += "%B";
- break;
- case '\x0f':
- mirc += "%O";
- break;
- case '\x09':
- mirc += " ";
- break;
- case '\x11':
- // Monospace not supported yet
- break;
- case '\x12':
- case '\x16':
- mirc += "%R";
- break;
- case '\x1d':
- mirc += "%I";
- break;
- case '\x1e':
- mirc += "%S";
- break;
- case '\x1f':
- mirc += "%U";
- break;
- case '\x7f':
- mirc += QChar(0x2421);
- break;
- default:
- mirc += QChar(0x2400 + c.unicode());
+ case '\x02':
+ mirc += "%B";
+ break;
+ case '\x0f':
+ mirc += "%O";
+ break;
+ case '\x09':
+ mirc += " ";
+ break;
+ case '\x11':
+ // Monospace not supported yet
+ break;
+ case '\x12':
+ case '\x16':
+ mirc += "%R";
+ break;
+ case '\x1d':
+ mirc += "%I";
+ break;
+ case '\x1e':
+ mirc += "%S";
+ break;
+ case '\x1f':
+ mirc += "%U";
+ break;
+ case '\x7f':
+ mirc += QChar(0x2421);
+ break;
+ default:
+ mirc += QChar(0x2400 + c.unicode());
}
- } else {
+ }
+ else {
if (c == '%')
mirc += c;
mirc += c;
num.prepend('0');
ins = QString("%Dcf%1").arg(num);
- if (i+1 < l && mirc[i] == ',' && mirc[i+1].isDigit()) {
+ if (i + 1 < l && mirc[i] == ',' && mirc[i + 1].isDigit()) {
i++;
num = mirc[i++];
if (i < l && mirc[i].isDigit())
else {
ins = "%Dc-";
}
- mirc.replace(pos, i-pos, ins);
+ mirc.replace(pos, i - pos, ins);
}
}
return mirc;
}
-
QString UiStyle::systemTimestampFormatString()
{
if (_systemTimestampFormatString.isEmpty()) {
return _systemTimestampFormatString;
}
-
QString UiStyle::timestampFormatString()
{
if (useCustomTimestampFormat()) {
return _timestampFormatString;
- } else {
+ }
+ else {
return systemTimestampFormatString();
}
}
-
/***********************************************************************************/
-UiStyle::StyledMessage::StyledMessage(const Message &msg)
+UiStyle::StyledMessage::StyledMessage(const Message& msg)
: Message(msg)
{
switch (type()) {
- // Don't compute the sender hash for message types without a nickname embedded
- case Message::Server:
- case Message::Info:
- case Message::Error:
- case Message::DayChange:
- case Message::Topic:
- case Message::Invite:
- // Don't compute the sender hash for messages with multiple nicks
- // Fixing this without breaking themes would be.. complex.
- case Message::NetsplitJoin:
- case Message::NetsplitQuit:
- case Message::Kick:
- // Don't compute the sender hash for message types that are not yet completed elsewhere
- case Message::Kill:
- _senderHash = 0x00;
- break;
- default:
- // Compute the sender hash for all other message types
- _senderHash = 0xff;
- break;
+ // Don't compute the sender hash for message types without a nickname embedded
+ case Message::Server:
+ case Message::Info:
+ case Message::Error:
+ case Message::DayChange:
+ case Message::Topic:
+ case Message::Invite:
+ // Don't compute the sender hash for messages with multiple nicks
+ // Fixing this without breaking themes would be.. complex.
+ case Message::NetsplitJoin:
+ case Message::NetsplitQuit:
+ case Message::Kick:
+ // Don't compute the sender hash for message types that are not yet completed elsewhere
+ case Message::Kill:
+ _senderHash = 0x00;
+ break;
+ default:
+ // Compute the sender hash for all other message types
+ _senderHash = 0xff;
+ break;
}
}
-
void UiStyle::StyledMessage::style() const
{
QString user = userFromMask(sender());
QString nick = nickFromMask(sender());
QString txt = UiStyle::mircToInternal(contents());
QString bufferName = bufferInfo().bufferName();
- bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
- host.replace('%', "%%"); // hostnames too...
- user.replace('%', "%%"); // and the username...
- nick.replace('%', "%%"); // ... and then there's totally RFC-violating servers like justin.tv m(
+ bufferName.replace('%', "%%"); // well, you _can_ have a % in a buffername apparently... -_-
+ host.replace('%', "%%"); // hostnames too...
+ user.replace('%', "%%"); // and the username...
+ nick.replace('%', "%%"); // ... and then there's totally RFC-violating servers like justin.tv m(
const int maxNetsplitNicks = 15;
QString t;
switch (type()) {
case Message::Plain:
- t = QString("%1").arg(txt); break;
+ t = QString("%1").arg(txt);
+ break;
case Message::Notice:
- t = QString("%1").arg(txt); break;
+ t = QString("%1").arg(txt);
+ break;
case Message::Action:
t = QString("%DN%1%DN %2").arg(nick).arg(txt);
break;
case Message::Nick:
//: Nick Message
- if (nick == contents()) t = tr("You are now known as %DN%1%DN").arg(txt);
- else t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
+ if (nick == contents())
+ t = tr("You are now known as %DN%1%DN").arg(txt);
+ else
+ t = tr("%DN%1%DN is now known as %DN%2%DN").arg(nick, txt);
break;
case Message::Mode:
//: Mode Message
- if (nick.isEmpty()) t = tr("User mode: %DM%1%DM").arg(txt);
- else t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
+ if (nick.isEmpty())
+ t = tr("User mode: %DM%1%DM").arg(txt);
+ else
+ t = tr("Mode %DM%1%DM by %DN%2%DN").arg(txt, nick);
break;
case Message::Join:
//: Join Message
- t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName); break;
+ t = tr("%DN%1%DN %DH(%2@%3)%DH has joined %DC%4%DC").arg(nick, user, host, bufferName);
+ break;
case Message::Part:
//: Part Message
t = tr("%DN%1%DN %DH(%2@%3)%DH has left %DC%4%DC").arg(nick, user, host, bufferName);
- if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
+ if (!txt.isEmpty())
+ t = QString("%1 (%2)").arg(t).arg(txt);
break;
case Message::Quit:
//: Quit Message
t = tr("%DN%1%DN %DH(%2@%3)%DH has quit").arg(nick, user, host);
- if (!txt.isEmpty()) t = QString("%1 (%2)").arg(t).arg(txt);
+ if (!txt.isEmpty())
+ t = QString("%1 (%2)").arg(t).arg(txt);
break;
- case Message::Kick:
- {
+ case Message::Kick: {
QString victim = txt.section(" ", 0, 0);
QString kickmsg = txt.section(" ", 1);
//: Kick Message
t = tr("%DN%1%DN has kicked %DN%2%DN from %DC%3%DC").arg(nick).arg(victim).arg(bufferName);
- if (!kickmsg.isEmpty()) t = QString("%1 (%2)").arg(t).arg(kickmsg);
- }
- break;
- //case Message::Kill: FIXME
+ if (!kickmsg.isEmpty())
+ t = QString("%1 (%2)").arg(t).arg(kickmsg);
+ } break;
+ // case Message::Kill: FIXME
case Message::Server:
- t = QString("%1").arg(txt); break;
+ t = QString("%1").arg(txt);
+ break;
case Message::Info:
- t = QString("%1").arg(txt); break;
+ t = QString("%1").arg(txt);
+ break;
case Message::Error:
- t = QString("%1").arg(txt); break;
- case Message::DayChange:
- {
+ t = QString("%1").arg(txt);
+ break;
+ case Message::DayChange: {
//: Day Change Message
t = tr("{Day changed to %1}").arg(timestamp().date().toString(Qt::DefaultLocaleLongDate));
- }
- break;
+ } break;
case Message::Topic:
- t = QString("%1").arg(txt); break;
- case Message::NetsplitJoin:
- {
+ t = QString("%1").arg(txt);
+ break;
+ case Message::NetsplitJoin: {
QStringList users = txt.split("#:#");
QStringList servers = users.takeLast().split(" ");
if (users.count() <= maxNetsplitNicks)
t.append(QString("%DN%1%DN").arg(users.join(", ")));
else
- t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
- }
- break;
- case Message::NetsplitQuit:
- {
+ t.append(tr("%DN%1%DN (%2 more)")
+ .arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", "))
+ .arg(users.count() - maxNetsplitNicks));
+ } break;
+ case Message::NetsplitQuit: {
QStringList users = txt.split("#:#");
QStringList servers = users.takeLast().split(" ");
if (users.count() <= maxNetsplitNicks)
t.append(QString("%DN%1%DN").arg(users.join(", ")));
else
- t.append(tr("%DN%1%DN (%2 more)").arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", ")).arg(users.count() - maxNetsplitNicks));
- }
- break;
+ t.append(tr("%DN%1%DN (%2 more)")
+ .arg(static_cast<QStringList>(users.mid(0, maxNetsplitNicks)).join(", "))
+ .arg(users.count() - maxNetsplitNicks));
+ } break;
case Message::Invite:
- t = QString("%1").arg(txt); break;
+ t = QString("%1").arg(txt);
+ break;
default:
t = QString("[%1]").arg(txt);
}
_contents = UiStyle::styleString(t, UiStyle::formatType(type()));
}
-
-const QString &UiStyle::StyledMessage::plainContents() const
+const QString& UiStyle::StyledMessage::plainContents() const
{
if (_contents.plainText.isNull())
style();
return _contents.plainText;
}
-
-const UiStyle::FormatList &UiStyle::StyledMessage::contentsFormatList() const
+const UiStyle::FormatList& UiStyle::StyledMessage::contentsFormatList() const
{
if (_contents.plainText.isNull())
style();
return _contents.formatList;
}
-
QString UiStyle::StyledMessage::decoratedTimestamp() const
{
return timestamp().toLocalTime().toString(UiStyle::timestampFormatString());
}
-
QString UiStyle::StyledMessage::plainSender() const
{
switch (type()) {
}
}
-
QString UiStyle::StyledMessage::decoratedSender() const
{
QString _senderPrefixes;
return QString("%1%2").arg(_senderPrefixes, plainSender());
}
-
// FIXME hardcoded to 16 sender hashes
quint8 UiStyle::StyledMessage::senderHash() const
{
if (type() == Message::Nick) {
// New nickname is given as contents. Change to that.
nick = stripFormatCodes(contents()).toLower();
- } else {
+ }
+ else {
// Just use the sender directly
nick = nickFromMask(sender()).toLower();
}
return qHash(static_cast<quint32>(key), seed);
}
-
UiStyle::FormatType operator|(UiStyle::FormatType lhs, UiStyle::FormatType rhs)
{
return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
}
-
UiStyle::FormatType& operator|=(UiStyle::FormatType& lhs, UiStyle::FormatType rhs)
{
lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
return lhs;
}
-
UiStyle::FormatType operator|(UiStyle::FormatType lhs, quint32 rhs)
{
return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | rhs);
}
-
-UiStyle::FormatType& operator|=(UiStyle::FormatType &lhs, quint32 rhs)
+UiStyle::FormatType& operator|=(UiStyle::FormatType& lhs, quint32 rhs)
{
lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) | rhs);
return lhs;
}
-
UiStyle::FormatType operator&(UiStyle::FormatType lhs, UiStyle::FormatType rhs)
{
return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & static_cast<quint32>(rhs));
}
-
-UiStyle::FormatType& operator&=(UiStyle::FormatType &lhs, UiStyle::FormatType rhs)
+UiStyle::FormatType& operator&=(UiStyle::FormatType& lhs, UiStyle::FormatType rhs)
{
lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & static_cast<quint32>(rhs));
return lhs;
}
-
UiStyle::FormatType operator&(UiStyle::FormatType lhs, quint32 rhs)
{
return static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & rhs);
}
-
-UiStyle::FormatType& operator&=(UiStyle::FormatType &lhs, quint32 rhs)
+UiStyle::FormatType& operator&=(UiStyle::FormatType& lhs, quint32 rhs)
{
lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) & rhs);
return lhs;
}
-
-UiStyle::FormatType& operator^=(UiStyle::FormatType &lhs, UiStyle::FormatType rhs)
+UiStyle::FormatType& operator^=(UiStyle::FormatType& lhs, UiStyle::FormatType rhs)
{
lhs = static_cast<UiStyle::FormatType>(static_cast<quint32>(lhs) ^ static_cast<quint32>(rhs));
return lhs;
}
-
UiStyle::MessageLabel operator|(UiStyle::MessageLabel lhs, UiStyle::MessageLabel rhs)
{
return static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
}
-
-UiStyle::MessageLabel& operator|=(UiStyle::MessageLabel &lhs, UiStyle::MessageLabel rhs)
+UiStyle::MessageLabel& operator|=(UiStyle::MessageLabel& lhs, UiStyle::MessageLabel rhs)
{
lhs = static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
return lhs;
}
-
UiStyle::MessageLabel operator&(UiStyle::MessageLabel lhs, quint32 rhs)
{
return static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) & rhs);
}
-
-UiStyle::MessageLabel& operator&=(UiStyle::MessageLabel &lhs, UiStyle::MessageLabel rhs)
+UiStyle::MessageLabel& operator&=(UiStyle::MessageLabel& lhs, UiStyle::MessageLabel rhs)
{
lhs = static_cast<UiStyle::MessageLabel>(static_cast<quint32>(lhs) & static_cast<quint32>(rhs));
return lhs;
}
-
quint64 operator|(UiStyle::FormatType lhs, UiStyle::MessageLabel rhs)
{
return static_cast<quint64>(lhs) | (static_cast<quint64>(rhs) << 32ull);
}
-
UiStyle::ItemFormatType operator|(UiStyle::ItemFormatType lhs, UiStyle::ItemFormatType rhs)
{
return static_cast<UiStyle::ItemFormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
}
-
-UiStyle::ItemFormatType& operator|=(UiStyle::ItemFormatType &lhs, UiStyle::ItemFormatType rhs)
+UiStyle::ItemFormatType& operator|=(UiStyle::ItemFormatType& lhs, UiStyle::ItemFormatType rhs)
{
lhs = static_cast<UiStyle::ItemFormatType>(static_cast<quint32>(lhs) | static_cast<quint32>(rhs));
return lhs;
/***********************************************************************************/
-QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList)
+QDataStream& operator<<(QDataStream& out, const UiStyle::FormatList& formatList)
{
out << static_cast<quint16>(formatList.size());
auto it = formatList.cbegin();
while (it != formatList.cend()) {
- out << it->first
- << static_cast<quint32>(it->second.type)
- << it->second.foreground
- << it->second.background;
+ out << it->first << static_cast<quint32>(it->second.type) << it->second.foreground << it->second.background;
++it;
}
return out;
}
-
-QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList)
+QDataStream& operator>>(QDataStream& in, UiStyle::FormatList& formatList)
{
quint16 cnt;
in >> cnt;
QColor foreground;
QColor background;
in >> pos >> ftype >> foreground >> background;
- formatList.emplace_back(std::make_pair(quint16{pos}, UiStyle::Format{static_cast<UiStyle::FormatType>(ftype), foreground, background}));
+ formatList.emplace_back(
+ std::make_pair(quint16{pos}, UiStyle::Format{static_cast<UiStyle::FormatType>(ftype), foreground, background}));
}
return in;
}
#include <QFontMetricsF>
#include <QHash>
#include <QIcon>
+#include <QPalette>
#include <QTextCharFormat>
#include <QTextLayout>
-#include <QPalette>
#include <QVector>
#include "bufferinfo.h"
Q_ENUMS(SenderPrefixModes)
public:
- UiStyle(QObject *parent = nullptr);
+ UiStyle(QObject* parent = nullptr);
~UiStyle() override;
//! This enumerates the possible formats a text element may have. */
* methods in this class (in particular mergedFormat())!
* Also, we _do_ rely on certain properties of these values in styleString() and friends!
*/
- enum class FormatType : quint32 {
+ enum class FormatType : quint32
+ {
Base = 0x00000000,
Invalid = 0xffffffff,
// URL is special, we want that to take precedence over the rest...
Url = 0x00080000
- // mIRC Colors - we assume those to be present only in plain contents
- // foreground: 0x0.400000
- // background: 0x.0800000
+ // mIRC Colors - we assume those to be present only in plain contents
+ // foreground: 0x0.400000
+ // background: 0x.0800000
};
- enum class MessageLabel : quint32 {
- None = 0x00000000,
- OwnMsg = 0x00000001,
- Highlight = 0x00000002,
- Selected = 0x00000004,
- Hovered = 0x00000008,
- Last = Hovered
+ enum class MessageLabel : quint32
+ {
+ None = 0x00000000,
+ OwnMsg = 0x00000001,
+ Highlight = 0x00000002,
+ Selected = 0x00000004,
+ Hovered = 0x00000008,
+ Last = Hovered
};
- enum class ItemFormatType : quint32 {
- None = 0x00000000,
+ enum class ItemFormatType : quint32
+ {
+ None = 0x00000000,
BufferViewItem = 0x00000001,
NickViewItem = 0x00000002,
Invalid = 0xffffffff
};
- enum class FormatProperty {
+ enum class FormatProperty
+ {
AllowForegroundOverride = QTextFormat::UserProperty,
AllowBackgroundOverride
};
- enum class ColorRole {
+ enum class ColorRole
+ {
MarkerLine,
// Sender colors (16 + self)
// These aren't used directly to avoid having storing all of the sender color options in the
SenderColor0d,
SenderColor0e,
SenderColor0f,
- NumRoles // must be last!
+ NumRoles // must be last!
};
/// Display of sender prefix modes
- enum class SenderPrefixMode {
- NoModes = 0, ///< Hide sender modes
- HighestMode = 1, ///< Show the highest active sender mode
- AllModes = 2 ///< Show all active sender modes
+ enum class SenderPrefixMode
+ {
+ NoModes = 0, ///< Hide sender modes
+ HighestMode = 1, ///< Show the highest active sender mode
+ AllModes = 2 ///< Show all active sender modes
};
// Do not change SenderPrefixMode numbering without also adjusting
// ChatViewSettingsPage::initSenderPrefixComboBox() and chatviewsettingspage.ui "defaultValue"
- struct Format {
+ struct Format
+ {
FormatType type;
QColor foreground;
QColor background;
using FormatList = std::vector<std::pair<quint16, Format>>;
- struct StyledString {
+ struct StyledString
+ {
QString plainText;
- FormatList formatList; // starting pos, ftypes
+ FormatList formatList; // starting pos, ftypes
};
class StyledMessage;
* @see ../qtui/settingspages/chatviewsettingspage.ui
* @see UiStyle::ColorRole
*/
- const QList<QColor> defaultSenderColors = QList<QColor> {
- QColor(204, 0, 0), ///< Sender00
- QColor( 0, 108, 173), ///< Sender01
- QColor( 77, 153, 0), ///< Sender02
- QColor(102, 0, 204), ///< Sender03
- QColor(166, 125, 0), ///< Sender04
- QColor( 0, 153, 39), ///< Sender05
- QColor( 0, 48, 192), ///< Sender06
- QColor(204, 0, 154), ///< Sender07
- QColor(185, 70, 0), ///< Sender08
+ const QList<QColor> defaultSenderColors = QList<QColor>{
+ QColor(204, 0 , 0 ), ///< Sender00
+ QColor(0 , 108, 173), ///< Sender01
+ QColor(77 , 153, 0 ), ///< Sender02
+ QColor(102, 0 , 204), ///< Sender03
+ QColor(166, 125, 0 ), ///< Sender04
+ QColor(0 , 153, 39 ), ///< Sender05
+ QColor(0 , 48 , 192), ///< Sender06
+ QColor(204, 0 , 154), ///< Sender07
+ QColor(185, 70 , 0 ), ///< Sender08
QColor(134, 153, 0), ///< Sender09
- QColor( 20, 153, 0), ///< Sender10
- QColor( 0, 153, 96), ///< Sender11
- QColor( 0, 108, 173), ///< Sender12
- QColor( 0, 153, 204), ///< Sender13
- QColor(179, 0, 204), ///< Sender14
- QColor(204, 0, 77), ///< Sender15
+ QColor(20 , 153, 0), ///< Sender10
+ QColor(0 , 153, 96), ///< Sender11
+ QColor(0 , 108, 173), ///< Sender12
+ QColor(0 , 153, 204), ///< Sender13
+ QColor(179, 0 , 204), ///< Sender14
+ QColor(204, 0 , 77 ), ///< Sender15
};
// Explicitly declare QList<QColor> type for defaultSenderColors, otherwise error C2797
// "list initialization inside member initializer list" will occur in Windows builds with Visual
const QColor defaultSenderColorSelf = QColor(0, 0, 0);
static FormatType formatType(Message::Type msgType);
- static StyledString styleString(const QString &string, FormatType baseFormat = FormatType::Base);
- static QString mircToInternal(const QString &);
+ static StyledString styleString(const QString& string, FormatType baseFormat = FormatType::Base);
+ static QString mircToInternal(const QString&);
/**
* Gets if a custom timestamp format is used.
*/
static QString timestampFormatString();
- QTextCharFormat format(const Format &format, MessageLabel messageLabel) const;
- QFontMetricsF *fontMetrics(FormatType formatType, MessageLabel messageLabel) const;
+ QTextCharFormat format(const Format& format, MessageLabel messageLabel) const;
+ QFontMetricsF* fontMetrics(FormatType formatType, MessageLabel messageLabel) const;
- QList<QTextLayout::FormatRange> toTextLayoutList(const FormatList &, int textLength, MessageLabel messageLabel) const;
+ QList<QTextLayout::FormatRange> toTextLayoutList(const FormatList&, int textLength, MessageLabel messageLabel) const;
- inline const QBrush &brush(ColorRole role) const { return _uiStylePalette.at((int)role); }
- inline void setBrush(ColorRole role, const QBrush &brush) { _uiStylePalette[(int)role] = brush; }
+ inline const QBrush& brush(ColorRole role) const { return _uiStylePalette.at((int)role); }
+ inline void setBrush(ColorRole role, const QBrush& brush) { _uiStylePalette[(int)role] = brush; }
- QVariant bufferViewItemData(const QModelIndex &networkModelIndex, int role) const;
- QVariant nickViewItemData(const QModelIndex &networkModelIndex, int role) const;
+ QVariant bufferViewItemData(const QModelIndex& networkModelIndex, int role) const;
+ QVariant nickViewItemData(const QModelIndex& networkModelIndex, int role) const;
public slots:
void reload();
protected:
void loadStyleSheet();
- QString loadStyleSheet(const QString &name, bool shouldExist = false);
+ QString loadStyleSheet(const QString& name, bool shouldExist = false);
QTextCharFormat parsedFormat(quint64 key) const;
- QTextCharFormat cachedFormat(const Format &format, MessageLabel messageLabel) const;
- void setCachedFormat(const QTextCharFormat &charFormat, const Format &format, MessageLabel messageLabel) const;
- void mergeFormat(QTextCharFormat &charFormat, const Format &format, MessageLabel messageLabel) const;
- void mergeSubElementFormat(QTextCharFormat &charFormat, FormatType formatType, MessageLabel messageLabel) const;
- void mergeColors(QTextCharFormat &charFormat, const Format &format, MessageLabel messageLabel) const;
+ QTextCharFormat cachedFormat(const Format& format, MessageLabel messageLabel) const;
+ void setCachedFormat(const QTextCharFormat& charFormat, const Format& format, MessageLabel messageLabel) const;
+ void mergeFormat(QTextCharFormat& charFormat, const Format& format, MessageLabel messageLabel) const;
+ void mergeSubElementFormat(QTextCharFormat& charFormat, FormatType formatType, MessageLabel messageLabel) const;
+ void mergeColors(QTextCharFormat& charFormat, const Format& format, MessageLabel messageLabel) const;
- static FormatType formatType(const QString &code);
+ static FormatType formatType(const QString& code);
static QString formatCode(FormatType);
/**
*
* @param[in] format Timestamp format string
*/
- static void setTimestampFormatString(const QString &format);
+ static void setTimestampFormatString(const QString& format);
/**
* Updates the local setting cache of how to display sender prefix modes
*
*/
static void enableSenderBrackets(bool enabled);
- QVariant itemData(int role, const QTextCharFormat &format) const;
+ QVariant itemData(int role, const QTextCharFormat& format) const;
private slots:
- void allowMircColorsChanged(const QVariant &);
- void showItemViewIconsChanged(const QVariant &);
+ void allowMircColorsChanged(const QVariant&);
+ void showItemViewIconsChanged(const QVariant&);
private:
QVector<QBrush> _uiStylePalette;
QBrush _markerLineBrush;
QHash<quint64, QTextCharFormat> _formats;
mutable QHash<QString, QTextCharFormat> _formatCache;
- mutable QHash<quint64, QFontMetricsF *> _metricsCache;
+ mutable QHash<quint64, QFontMetricsF*> _metricsCache;
QHash<UiStyle::ItemFormatType, QTextCharFormat> _listItemFormats;
static QHash<QString, FormatType> _formatCodes;
- static bool _useCustomTimestampFormat; ///< If true, use the custom timestamp format
- static QString _systemTimestampFormatString; ///< Cached copy of system locale timestamp format
- static QString _timestampFormatString; ///< Timestamp format string
- static UiStyle::SenderPrefixMode _senderPrefixDisplay; ///< Prefix mode display before sender
- static bool _showSenderBrackets; ///< If true, show brackets around sender names
+ static bool _useCustomTimestampFormat; ///< If true, use the custom timestamp format
+ static QString _systemTimestampFormatString; ///< Cached copy of system locale timestamp format
+ static QString _timestampFormatString; ///< Timestamp format string
+ static UiStyle::SenderPrefixMode _senderPrefixDisplay; ///< Prefix mode display before sender
+ static bool _showSenderBrackets; ///< If true, show brackets around sender names
QIcon _channelJoinedIcon;
QIcon _channelPartedIcon;
bool _allowMircColors;
};
-
class UISUPPORT_EXPORT UiStyle::StyledMessage : public Message
{
Q_DECLARE_TR_FUNCTIONS(UiStyle::StyledMessage)
public:
- explicit StyledMessage(const Message &message);
+ explicit StyledMessage(const Message& message);
QString decoratedTimestamp() const;
- QString plainSender() const; //!< Nickname (no decorations) for Plain and Notice, empty else
+ QString plainSender() const; //!< Nickname (no decorations) for Plain and Notice, empty else
QString decoratedSender() const;
- const QString &plainContents() const;
+ const QString& plainContents() const;
- const FormatList &contentsFormatList() const;
+ const FormatList& contentsFormatList() const;
quint8 senderHash() const;
// ---- Operators for dealing with enums ----------------------------------------------------------
UISUPPORT_EXPORT UiStyle::FormatType operator|(UiStyle::FormatType lhs, UiStyle::FormatType rhs);
-UISUPPORT_EXPORT UiStyle::FormatType& operator|=(UiStyle::FormatType &lhs, UiStyle::FormatType rhs);
+UISUPPORT_EXPORT UiStyle::FormatType& operator|=(UiStyle::FormatType& lhs, UiStyle::FormatType rhs);
UISUPPORT_EXPORT UiStyle::FormatType operator|(UiStyle::FormatType lhs, quint32 rhs);
-UISUPPORT_EXPORT UiStyle::FormatType& operator|=(UiStyle::FormatType &lhs, quint32 rhs);
+UISUPPORT_EXPORT UiStyle::FormatType& operator|=(UiStyle::FormatType& lhs, quint32 rhs);
UISUPPORT_EXPORT UiStyle::FormatType operator&(UiStyle::FormatType lhs, UiStyle::FormatType rhs);
-UISUPPORT_EXPORT UiStyle::FormatType& operator&=(UiStyle::FormatType &lhs, UiStyle::FormatType rhs);
+UISUPPORT_EXPORT UiStyle::FormatType& operator&=(UiStyle::FormatType& lhs, UiStyle::FormatType rhs);
UISUPPORT_EXPORT UiStyle::FormatType operator&(UiStyle::FormatType lhs, quint32 rhs);
-UISUPPORT_EXPORT UiStyle::FormatType& operator&=(UiStyle::FormatType &lhs, quint32 rhs);
-UISUPPORT_EXPORT UiStyle::FormatType& operator^=(UiStyle::FormatType &lhs, UiStyle::FormatType rhs);
+UISUPPORT_EXPORT UiStyle::FormatType& operator&=(UiStyle::FormatType& lhs, quint32 rhs);
+UISUPPORT_EXPORT UiStyle::FormatType& operator^=(UiStyle::FormatType& lhs, UiStyle::FormatType rhs);
UISUPPORT_EXPORT UiStyle::MessageLabel operator|(UiStyle::MessageLabel lhs, UiStyle::MessageLabel rhs);
-UISUPPORT_EXPORT UiStyle::MessageLabel& operator|=(UiStyle::MessageLabel &lhs, UiStyle::MessageLabel rhs);
+UISUPPORT_EXPORT UiStyle::MessageLabel& operator|=(UiStyle::MessageLabel& lhs, UiStyle::MessageLabel rhs);
UISUPPORT_EXPORT UiStyle::MessageLabel operator&(UiStyle::MessageLabel lhs, quint32 rhs);
-UISUPPORT_EXPORT UiStyle::MessageLabel& operator&=(UiStyle::MessageLabel &lhs, UiStyle::MessageLabel rhs);
+UISUPPORT_EXPORT UiStyle::MessageLabel& operator&=(UiStyle::MessageLabel& lhs, UiStyle::MessageLabel rhs);
// Shifts the label into the upper half of the return value
UISUPPORT_EXPORT quint64 operator|(UiStyle::FormatType lhs, UiStyle::MessageLabel rhs);
UISUPPORT_EXPORT UiStyle::ItemFormatType operator|(UiStyle::ItemFormatType lhs, UiStyle::ItemFormatType rhs);
-UISUPPORT_EXPORT UiStyle::ItemFormatType& operator|=(UiStyle::ItemFormatType &lhs, UiStyle::ItemFormatType rhs);
+UISUPPORT_EXPORT UiStyle::ItemFormatType& operator|=(UiStyle::ItemFormatType& lhs, UiStyle::ItemFormatType rhs);
// ---- Allow for FormatList in QVariant ----------------------------------------------------------
-QDataStream &operator<<(QDataStream &out, const UiStyle::FormatList &formatList);
-QDataStream &operator>>(QDataStream &in, UiStyle::FormatList &formatList);
+QDataStream& operator<<(QDataStream& out, const UiStyle::FormatList& formatList);
+QDataStream& operator>>(QDataStream& in, UiStyle::FormatList& formatList);
Q_DECLARE_METATYPE(UiStyle::FormatList)
Q_DECLARE_METATYPE(UiStyle::MessageLabel)
* Contains all supported widget changed signals.
*/
static const auto supportedWidgetChangedSignals = std::make_tuple(
- &ColorButton::colorChanged,
- &FontSelector::fontChanged,
- &QAbstractButton::toggled,
- selectOverload<int>(&QComboBox::currentIndexChanged),
- selectOverload<double>(&QDoubleSpinBox::valueChanged),
- &QGroupBox::toggled,
- &QLineEdit::textChanged,
- selectOverload<int>(&QSpinBox::valueChanged),
- &QTextEdit::textChanged
+ &ColorButton::colorChanged,
+ &FontSelector::fontChanged,
+ &QAbstractButton::toggled,
+ selectOverload<int>(&QComboBox::currentIndexChanged),
+ selectOverload<double>(&QDoubleSpinBox::valueChanged),
+ &QGroupBox::toggled,
+ &QLineEdit::textChanged,
+ selectOverload<int>(&QSpinBox::valueChanged),
+ &QTextEdit::textChanged
);
/**
* Tries to find a changed signal that matches the given widget type, and connects that to the given receiver/slot.
*/
-template<typename Receiver, typename Slot, std::size_t ...Is>
+template<typename Receiver, typename Slot, std::size_t... Is>
bool tryConnectChangedSignal(const QObject* widget, const Receiver* receiver, Slot slot, std::index_sequence<Is...>)
{
// Tries to cast the given QObject to the given signal's class type, and connects to receiver/slot if successful.
// If *alreadyConnected is true, just returns false to prevent multiple connections.
static const auto tryConnect = [](const QObject* object, auto sig, auto receiver, auto slot, bool* alreadyConnected) {
if (!*alreadyConnected) {
- auto widget = qobject_cast<const typename MemberFunction<decltype(sig)>::ClassType *>(object);
+ auto widget = qobject_cast<const typename MemberFunction<decltype(sig)>::ClassType*>(object);
if (widget) {
*alreadyConnected = QObject::connect(widget, sig, receiver, slot);
return *alreadyConnected;
// Unpack the tuple and try to connect to each contained signal in order
bool alreadyConnected{false};
- auto results = { tryConnect(widget, std::get<Is>(supportedWidgetChangedSignals), receiver, slot, &alreadyConnected)... };
+ auto results = {tryConnect(widget, std::get<Is>(supportedWidgetChangedSignals), receiver, slot, &alreadyConnected)...};
return std::any_of(results.begin(), results.end(), [](bool result) { return result; });
}
-} //detail
+} // namespace detail
/**
* Connects the given widget's changed signal to the given receiver/context and slot.
template<typename Receiver, typename Slot>
bool connectToWidgetChangedSignal(const QObject* widget, const Receiver* receiver, Slot slot)
{
- return detail::tryConnectChangedSignal(widget, receiver, slot,
+ return detail::tryConnectChangedSignal(widget,
+ receiver,
+ slot,
std::make_index_sequence<std::tuple_size<decltype(detail::supportedWidgetChangedSignals)>::value>{});
}
{
bool success = true;
for (auto&& widget : widgets) {
- success &= detail::tryConnectChangedSignal(widget, receiver, slot,
- std::make_index_sequence<std::tuple_size<decltype(detail::supportedWidgetChangedSignals)>::value>{});
+ success &= detail::tryConnectChangedSignal(widget,
+ receiver,
+ slot,
+ std::make_index_sequence<
+ std::tuple_size<decltype(detail::supportedWidgetChangedSignals)>::value>{});
}
return success;
}