diff --git a/KTp/Declarative/contact-pin.cpp b/KTp/Declarative/contact-pin.cpp index 7ab0363..3412526 100644 --- a/KTp/Declarative/contact-pin.cpp +++ b/KTp/Declarative/contact-pin.cpp @@ -1,80 +1,80 @@ /* Copyright (C) 2012 Aleix Pol This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact-pin.h" #include #include #include "pinned-contacts-model.h" ContactPin::ContactPin(QObject *parent) : QObject(parent) - , m_model(0) + , m_model(nullptr) { } Tp::AccountPtr ContactPin::account() const { return m_account; } KTp::ContactPtr ContactPin::contact() const { return m_contact; } PinnedContactsModel* ContactPin::model() const { return m_model; } bool ContactPin::isPinned() const { bool ret = false; if (m_model && m_account && m_contact) { QModelIndex idx = m_model->indexForContact(m_contact); ret = idx.isValid(); } return ret; } void ContactPin::toggle() { Q_ASSERT(m_model && m_account && m_contact); m_model->setPinning(m_account, m_contact, !isPinned()); Q_EMIT pinnedChanged(); } void ContactPin::setAccount(const Tp::AccountPtr &account) { Q_ASSERT(account); m_account = account; Q_EMIT pinnedChanged(); } void ContactPin::setContact(const KTp::ContactPtr &contact) { m_contact = contact; Q_EMIT pinnedChanged(); } void ContactPin::setModel(PinnedContactsModel *model) { m_model = model; Q_EMIT pinnedChanged(); } diff --git a/KTp/Declarative/contact-pin.h b/KTp/Declarative/contact-pin.h index 96e4e36..40131f0 100644 --- a/KTp/Declarative/contact-pin.h +++ b/KTp/Declarative/contact-pin.h @@ -1,58 +1,58 @@ /* Copyright (C) 2012 Aleix Pol This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CONTACTPIN_H #define CONTACTPIN_H #include #include "KTp/types.h" class PinnedContactsModel; class ContactPin : public QObject { Q_OBJECT Q_PROPERTY(KTp::ContactPtr contact READ contact WRITE setContact) Q_PROPERTY(Tp::AccountPtr account READ account WRITE setAccount) Q_PROPERTY(PinnedContactsModel *model READ model WRITE setModel) Q_PROPERTY(bool pinned READ isPinned NOTIFY pinnedChanged) public: - explicit ContactPin(QObject *parent = 0); + explicit ContactPin(QObject *parent = nullptr); KTp::ContactPtr contact() const; Tp::AccountPtr account() const; PinnedContactsModel* model() const; bool isPinned() const; void setContact(const KTp::ContactPtr &contact); void setAccount(const Tp::AccountPtr &account); void setModel(PinnedContactsModel *model); Q_SCRIPTABLE void toggle(); Q_SIGNALS: void pinnedChanged(); private: PinnedContactsModel *m_model; KTp::ContactPtr m_contact; Tp::AccountPtr m_account; }; #endif // CONTACTPIN_H diff --git a/KTp/Declarative/conversation.cpp b/KTp/Declarative/conversation.cpp index 80be403..a6be0e9 100644 --- a/KTp/Declarative/conversation.cpp +++ b/KTp/Declarative/conversation.cpp @@ -1,327 +1,327 @@ /* Copyright (C) 2011 Lasath Fernando Copyright (C) 2016 Martin Klapetek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "conversation.h" #include "messages-model.h" #include #include #include #include #include "debug.h" #include "channel-delegator.h" class Conversation::ConversationPrivate { public: ConversationPrivate() { - messages = 0; + messages = nullptr; delegated = false; valid = false; isGroupChat = false; } MessagesModel *messages; //stores if the conversation has been delegated to another client and we are only observing the channel //and not handling it. bool delegated; bool valid; Tp::AccountPtr account; QTimer *pausedStateTimer; KPeople::PersonData *personData; // May be null for group chats. KTp::ContactPtr targetContact; bool isGroupChat; }; Conversation::Conversation(const Tp::TextChannelPtr &channel, const Tp::AccountPtr &account, QObject *parent) : QObject(parent), d (new ConversationPrivate) { qCDebug(KTP_DECLARATIVE); d->valid = false; d->isGroupChat = false; d->account = account; connect(d->account.data(), SIGNAL(connectionChanged(Tp::ConnectionPtr)), SLOT(onAccountConnectionChanged(Tp::ConnectionPtr))); d->messages = new MessagesModel(account, this); connect(d->messages, &MessagesModel::unreadCountChanged, this, &Conversation::unreadMessagesChanged); connect(d->messages, &MessagesModel::lastMessageChanged, this, &Conversation::lastMessageChanged); setTextChannel(channel); d->delegated = false; d->pausedStateTimer = new QTimer(this); d->pausedStateTimer->setSingleShot(true); connect(d->pausedStateTimer, SIGNAL(timeout()), this, SLOT(onChatPausedTimerExpired())); } Conversation::Conversation(const QString &contactId, const Tp::AccountPtr &account, QObject *parent) : QObject(parent), d(new ConversationPrivate) { d->valid = true; d->isGroupChat = false; d->account = account; d->personData = new KPeople::PersonData(QStringLiteral("ktp://") + d->account->objectPath().mid(35) + QStringLiteral("?") + contactId); d->messages = new MessagesModel(account, this); connect(d->messages, &MessagesModel::unreadCountChanged, this, &Conversation::unreadMessagesChanged); connect(d->messages, &MessagesModel::lastMessageChanged, this, &Conversation::lastMessageChanged); d->messages->setContactData(contactId, d->personData->name()); Q_EMIT avatarChanged(); Q_EMIT titleChanged(); Q_EMIT presenceIconChanged(); Q_EMIT validityChanged(d->valid); } void Conversation::setTextChannel(const Tp::TextChannelPtr &channel) { if (d->messages->account().isNull()) { d->messages->setAccount(d->account); } if (d->messages->textChannel() != channel) { d->messages->setTextChannel(channel); d->valid = channel->isValid(); connect(channel.data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)), SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString))); connect(channel.data(), &Tp::TextChannel::chatStateChanged, this, &Conversation::contactTypingChanged); if (channel->targetContact().isNull()) { d->isGroupChat = true; } else { d->isGroupChat = false; d->targetContact = KTp::ContactPtr::qObjectCast(channel->targetContact()); d->personData = new KPeople::PersonData(QStringLiteral("ktp://") + d->account->objectPath().mid(35) + QStringLiteral("?") + d->targetContact->id()); connect(d->targetContact.constData(), SIGNAL(aliasChanged(QString)), SIGNAL(titleChanged())); connect(d->targetContact.constData(), SIGNAL(presenceChanged(Tp::Presence)), SIGNAL(presenceIconChanged())); connect(d->targetContact.constData(), SIGNAL(avatarDataChanged(Tp::AvatarData)), SIGNAL(avatarChanged())); } Q_EMIT avatarChanged(); Q_EMIT titleChanged(); Q_EMIT presenceIconChanged(); Q_EMIT validityChanged(d->valid); } } Tp::TextChannelPtr Conversation::textChannel() const { return d->messages->textChannel(); } MessagesModel* Conversation::messages() const { return d->messages; } QString Conversation::title() const { if (d->isGroupChat) { QString roomName = textChannel()->targetId(); return roomName.left(roomName.indexOf(QLatin1Char('@'))); } else { return d->personData->name(); } } QIcon Conversation::presenceIcon() const { if (d->isGroupChat) { return KTp::Presence(Tp::Presence::available()).icon(); } else if (!d->targetContact.isNull()) { return KTp::Presence(d->targetContact->presence()).icon(); } return QIcon(); } QIcon Conversation::avatar() const { if (d->isGroupChat) { return QIcon(); } else { const QString path = d->targetContact->avatarData().fileName; QIcon icon; if (!path.isEmpty()) { icon = QIcon(path); } if (icon.availableSizes().isEmpty()) { icon = QIcon::fromTheme(QStringLiteral("im-user")); } return icon; } } KTp::ContactPtr Conversation::targetContact() const { if (d->isGroupChat) { return KTp::ContactPtr(); } else { return d->targetContact; } } Tp::AccountPtr Conversation::account() const { return d->account; } Tp::Account* Conversation::accountObject() const { if (!d->account.isNull()) { return d->account.data(); } - return 0; + return nullptr; } bool Conversation::isValid() const { return d->valid; } void Conversation::onChannelInvalidated(Tp::DBusProxy *proxy, const QString &errorName, const QString &errorMessage) { qCDebug(KTP_DECLARATIVE) << proxy << errorName << ":" << errorMessage; d->valid = false; Q_EMIT validityChanged(d->valid); } void Conversation::onAccountConnectionChanged(const Tp::ConnectionPtr& connection) { //if we have reconnected and we were handling the channel if (connection && ! d->delegated) { //general convention is to never use ensureAndHandle when we already have a client registrar //ensureAndHandle will implicity create a new temporary client registrar which is a waste //it's also more code to get the new channel //However, we cannot use use ensureChannel as normal because without being able to pass a preferredHandler //we need a preferredHandler so that this handler is the one that ends up with the channel if multi handlers are active //we do not know the name that this handler is currently registered with Tp::PendingChannel *pendingChannel = d->account->ensureAndHandleTextChat(textChannel()->targetId()); connect(pendingChannel, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onCreateChannelFinished(Tp::PendingOperation*))); } } void Conversation::onCreateChannelFinished(Tp::PendingOperation* op) { Tp::PendingChannel *pendingChannelOp = qobject_cast(op); Tp::TextChannelPtr textChannel = Tp::TextChannelPtr::dynamicCast(pendingChannelOp->channel()); if (textChannel) { setTextChannel(textChannel); } } void Conversation::delegateToProperClient() { ChannelDelegator::delegateChannel(d->account, d->messages->textChannel()); d->delegated = true; Q_EMIT conversationCloseRequested(); } void Conversation::requestClose() { qCDebug(KTP_DECLARATIVE); if (!d->messages->textChannel().isNull()) { d->messages->textChannel()->requestClose(); } } void Conversation::updateTextChanged(const QString &message) { if (!message.isEmpty()) { //if the timer is active, it means the user is continuously typing if (d->pausedStateTimer->isActive()) { //just restart the timer and don't spam with chat state changes d->pausedStateTimer->start(5000); } else { //if the user has just typed some text, set state to Composing and start the timer d->messages->textChannel()->requestChatState(Tp::ChannelChatStateComposing); d->pausedStateTimer->start(5000); } } else { //if the user typed no text/cleared the input field, set Active and stop the timer d->messages->textChannel()->requestChatState(Tp::ChannelChatStateActive); d->pausedStateTimer->stop(); } } void Conversation::onChatPausedTimerExpired() { d->messages->textChannel()->requestChatState(Tp::ChannelChatStatePaused); } Conversation::~Conversation() { qCDebug(KTP_DECLARATIVE); //if we are not handling the channel do nothing. if (!d->delegated) { d->messages->textChannel()->requestClose(); } delete d; } bool Conversation::hasUnreadMessages() const { if (d->messages) { return d->messages->unreadCount() > 0; } return false; } KPeople::PersonData* Conversation::personData() const { return d->personData; } bool Conversation::isContactTyping() const { if (d->messages->textChannel()) { return d->messages->textChannel()->chatState(d->targetContact) == Tp::ChannelChatStateComposing; } return false; } bool Conversation::canSendMessages() const { if (d->messages && d->messages->textChannel()) { return true; } return false; } diff --git a/KTp/Declarative/conversation.h b/KTp/Declarative/conversation.h index cbaad99..1930364 100644 --- a/KTp/Declarative/conversation.h +++ b/KTp/Declarative/conversation.h @@ -1,113 +1,113 @@ /* Copyright (C) 2011 Lasath Fernando Copyright (C) 2016 Martin Klapetek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CONVERSATION_H #define CONVERSATION_H #include #include #include #include #include #include "messages-model.h" class MessagesModel; class Conversation : public QObject { Q_OBJECT Q_PROPERTY(MessagesModel *messages READ messages CONSTANT) Q_PROPERTY(bool valid READ isValid NOTIFY validityChanged) Q_PROPERTY(QString title READ title NOTIFY titleChanged) Q_PROPERTY(QIcon presenceIcon READ presenceIcon NOTIFY presenceIconChanged) Q_PROPERTY(QIcon avatar READ avatar NOTIFY avatarChanged) Q_PROPERTY(Tp::Account *account READ accountObject CONSTANT) Q_PROPERTY(KTp::ContactPtr targetContact READ targetContact CONSTANT) Q_PROPERTY(KPeople::PersonData *personData READ personData CONSTANT) Q_PROPERTY(bool hasUnreadMessages READ hasUnreadMessages NOTIFY unreadMessagesChanged) Q_PROPERTY(bool isContactTyping READ isContactTyping NOTIFY contactTypingChanged) Q_PROPERTY(bool canSendMessages READ canSendMessages NOTIFY canSendMessagesChanged) public: - Conversation(const Tp::TextChannelPtr &channel, const Tp::AccountPtr &account, QObject *parent = 0); - Conversation(const QString &contactId, const Tp::AccountPtr &account, QObject *parent = 0); + Conversation(const Tp::TextChannelPtr &channel, const Tp::AccountPtr &account, QObject *parent = nullptr); + Conversation(const QString &contactId, const Tp::AccountPtr &account, QObject *parent = nullptr); ~Conversation() override; void setTextChannel(const Tp::TextChannelPtr &channel); Tp::TextChannelPtr textChannel() const; /** * Useful for offline history retrieving (as there's no text channel when offline) */ void setContactData(const QString &contactId, const QString &contactAlias); MessagesModel* messages() const; QString title() const; QIcon presenceIcon() const; QIcon avatar() const; /** * Target contact of this conversation. May be null if conversation is a group chat. */ KTp::ContactPtr targetContact() const; Tp::AccountPtr account() const; Tp::Account* accountObject() const; KPeople::PersonData* personData() const; bool isValid() const; bool hasUnreadMessages() const; bool isContactTyping() const; bool canSendMessages() const; Q_SIGNALS: void validityChanged(bool isValid); void avatarChanged(); void titleChanged(); void presenceIconChanged(); void conversationCloseRequested(); void unreadMessagesChanged(); void lastMessageChanged(); void contactTypingChanged(); void canSendMessagesChanged(); public Q_SLOTS: void delegateToProperClient(); void requestClose(); void updateTextChanged(const QString &message); private Q_SLOTS: void onChannelInvalidated(Tp::DBusProxy *proxy, const QString &errorName, const QString &errorMessage); void onAccountConnectionChanged(const Tp::ConnectionPtr &connection); void onCreateChannelFinished(Tp::PendingOperation *op); void onChatPausedTimerExpired(); private: class ConversationPrivate; ConversationPrivate *d; }; Q_DECLARE_METATYPE(Conversation*) #endif // CONVERSATION_H diff --git a/KTp/Declarative/conversations-model.h b/KTp/Declarative/conversations-model.h index 071781b..0673a17 100644 --- a/KTp/Declarative/conversations-model.h +++ b/KTp/Declarative/conversations-model.h @@ -1,82 +1,82 @@ /* Copyright (C) 2011 Lasath Fernando This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CONVERSATIONS_MODEL_H #define CONVERSATIONS_MODEL_H #include #include #include class Conversation; class ConversationsModel : public QAbstractListModel, public Tp::AbstractClientHandler { Q_OBJECT Q_PROPERTY(int totalUnreadCount READ totalUnreadCount NOTIFY totalUnreadCountChanged) Q_PROPERTY(int activeChatIndex READ activeChatIndex NOTIFY activeChatIndexChanged) public: - explicit ConversationsModel(QObject *parent = 0); + explicit ConversationsModel(QObject *parent = nullptr); ~ConversationsModel() override; QHash roleNames() const Q_DECL_OVERRIDE; QVariant data (const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; int rowCount (const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; /** @returns the sum of all unread messages among all conversations */ int totalUnreadCount() const; /** @returns the index of the active chat, ie one the user is interacting with */ int activeChatIndex() const; enum role { ConversationRole = Qt::UserRole }; Q_INVOKABLE void closeAllConversations(); void handleChannels(const Tp::MethodInvocationContextPtr<> &context, const Tp::AccountPtr &account, const Tp::ConnectionPtr &connection, const QList &channels, const QList &channelRequests, const QDateTime &userActionTime, const HandlerInfo &handlerInfo) override; bool bypassApproval() const override; public Q_SLOTS: int nextActiveConversation(int first); private: void removeConversation(Conversation *conversation); class ConversationsModelPrivate; ConversationsModelPrivate *d; private Q_SLOTS: void onConversationCloseRequested(); Q_SIGNALS: void totalUnreadCountChanged(); void activeChatIndexChanged(); }; #endif // CONVERSATIONS_MODEL_H diff --git a/KTp/Declarative/filtered-pinned-contacts-proxy-model.h b/KTp/Declarative/filtered-pinned-contacts-proxy-model.h index a866690..e5abe88 100644 --- a/KTp/Declarative/filtered-pinned-contacts-proxy-model.h +++ b/KTp/Declarative/filtered-pinned-contacts-proxy-model.h @@ -1,34 +1,34 @@ /* Copyright (C) 2012 Aleix Pol This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef FILTEREDPINNEDCONTACTSPROXYMODEL_H #define FILTEREDPINNEDCONTACTSPROXYMODEL_H #include class FilteredPinnedContactsProxyModel : public QSortFilterProxyModel { Q_OBJECT Q_PROPERTY(QAbstractItemModel* sourceModel READ sourceModel WRITE setSourceModel) public: - FilteredPinnedContactsProxyModel(QObject* parent = 0); + FilteredPinnedContactsProxyModel(QObject* parent = nullptr); bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; }; #endif // FILTEREDPINNEDCONTACTSPROXYMODEL_H diff --git a/KTp/Declarative/mainlogmodel.h b/KTp/Declarative/mainlogmodel.h index 041ed8f..c292d31 100644 --- a/KTp/Declarative/mainlogmodel.h +++ b/KTp/Declarative/mainlogmodel.h @@ -1,148 +1,148 @@ /* Copyright (C) 2016 Martin Klapetek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MAINLOGMODEL_H #define MAINLOGMODEL_H #include #include #include #include #include #include #include #include class Conversation; class MainLogModel; // Cause of ObserverProxy class LogItem { public: QDateTime messageDateTime; QString message; QString accountObjectPath; QString targetContact; Conversation *conversation; }; /** * The reason for this class is that an Observer and a Handler cannot * be registered under the same client name if the Observer is not to * be autostarted and only monitor things once the app is executed. * * So this is a tiny proxy class that gets registered as SpaceBarObserverProxy * and forwards all observerChannels calls to the model which then merges * them with the existing conversations */ class ObserverProxy : public QObject, public Tp::AbstractClientObserver { Q_OBJECT public: ObserverProxy(MainLogModel *model); void observeChannels(const Tp::MethodInvocationContextPtr<> &context, const Tp::AccountPtr &account, const Tp::ConnectionPtr &connection, const QList &channels, const Tp::ChannelDispatchOperationPtr &dispatchOperation, const QList &requestsSatisfied, const Tp::AbstractClientObserver::ObserverInfo &observerInfo) override; private: MainLogModel *m_model; }; //----------------------------------------------------------------------------- class MainLogModel : public QAbstractListModel, public Tp::AbstractClientHandler { Q_OBJECT public: enum Role { ContactDisplayNameRole = Qt::DisplayRole, ContactIdRole = Qt::UserRole, PersonUriRole, AccountIdRole, LastMessageDateRole, LastMessageTextRole, ConversationRole, HasUnreadMessagesRole, UnreadMessagesCountRole, UserRole = Qt::UserRole + 0x1000 ///< in case it's needed to extend, use this one to start from }; Q_ENUMS(Role) - MainLogModel(QObject *parent = 0); + MainLogModel(QObject *parent = nullptr); ~MainLogModel() override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; QHash roleNames() const override; Q_INVOKABLE bool canChat(const QString &accountId) const; Q_INVOKABLE void startChat(const QString &accountId, const QString &contactId); Q_INVOKABLE void setAccountManager(const Tp::AccountManagerPtr &accountManager); Q_INVOKABLE QVariant data(int index, QByteArray role) const; Q_INVOKABLE QObject* observerProxy() const; void handleChannels(const Tp::MethodInvocationContextPtr<> &context, const Tp::AccountPtr &account, const Tp::ConnectionPtr &connection, const QList &channels, const QList &channelRequests, const QDateTime &userActionTime, const HandlerInfo &handlerInfo) override; bool bypassApproval() const override; Q_SIGNALS: void newRequestedChannel(const QModelIndex &index); private Q_SLOTS: void handleChannel(const Tp::AccountPtr &account, const Tp::TextChannelPtr &channel); void onConversationChanged(); private: void setupSignals(Conversation *conversation) const; void processQueryResults(QSqlQuery query); QHash m_conversations; // This is a hash with keys "accountId + contactId" QList m_logItems; QSqlQuery m_query; QSqlDatabase m_db; Tp::AccountManagerPtr m_accountManager; ObserverProxy *m_observerProxy; // This is true when mission control autostarted the app // on an incoming channel; the model will emit newRequestedChannel() // for the first incoming channel even though it was not requested // This is useful to switch the application directly to the new // message bool m_openIncomingChannel; friend class ObserverProxy; }; Q_DECLARE_METATYPE(Tp::ChannelDispatchOperationPtr) #endif diff --git a/KTp/Declarative/messages-model.h b/KTp/Declarative/messages-model.h index 5b6b0e0..7b954cd 100644 --- a/KTp/Declarative/messages-model.h +++ b/KTp/Declarative/messages-model.h @@ -1,121 +1,121 @@ /* Copyright (C) 2011 Lasath Fernando This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MESSAGES_MODEL_H #define MESSAGES_MODEL_H #include #include #include #include class MessagesModel : public QAbstractListModel { Q_OBJECT Q_ENUMS(MessageType) Q_ENUMS(DeliveryStatus) Q_PROPERTY(bool visibleToUser READ isVisibleToUser WRITE setVisibleToUser NOTIFY visibleToUserChanged) Q_PROPERTY(int unreadCount READ unreadCount NOTIFY unreadCountChanged) Q_PROPERTY(bool shouldStartOpened READ shouldStartOpened CONSTANT) public: - MessagesModel(const Tp::AccountPtr &account, QObject *parent = 0); + MessagesModel(const Tp::AccountPtr &account, QObject *parent = nullptr); ~MessagesModel() override; enum Roles { TextRole = Qt::UserRole, //String TypeRole, //MessagesModel::MessageType (for now!) TimeRole, //QDateTime SenderIdRole, //string SenderAliasRole, //string SenderAvatarRole, //pixmap DeliveryStatusRole, //MessagesModel::DeliveryStatus DeliveryReportReceiveTimeRole, //QDateTime PreviousMessageTypeRole, // allows for painting the messages as grouped NextMessageTypeRole, }; enum MessageType { MessageTypeIncoming, MessageTypeOutgoing, MessageTypeAction, MessageTypeNotice }; enum DeliveryStatus { DeliveryStatusUnknown, DeliveryStatusDelivered, DeliveryStatusRead, // implies DeliveryStatusDelivered DeliveryStatusFailed }; QHash roleNames() const Q_DECL_OVERRIDE; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; Tp::TextChannelPtr textChannel() const; void setTextChannel(const Tp::TextChannelPtr &channel); Tp::AccountPtr account() const; void setAccount(const Tp::AccountPtr &account); /** * Useful for offline history retrieving (as there's no text channel when offline) */ void setContactData(const QString &contactId, const QString &contactAlias); bool isVisibleToUser() const; void setVisibleToUser(bool visible); int unreadCount() const; void acknowledgeAllMessages(); bool shouldStartOpened() const; QString lastMessage() const; QDateTime lastMessageDateTime() const; Q_SIGNALS: void visibleToUserChanged(bool visible); void unreadCountChanged(int unreadMesssagesCount); void lastMessageChanged(); public Q_SLOTS: void fetchMoreHistory(); void sendNewMessage(const QString &message); private Q_SLOTS: void onMessageReceived(const Tp::ReceivedMessage &message); void onMessageSent(const Tp::Message &message, Tp::MessageSendingFlags flags, const QString &messageToken); void onPendingMessageRemoved(); bool verifyPendingOperation(Tp::PendingOperation *op); void onHistoryFetched(const QList &messages); private: void setupChannelSignals(const Tp::TextChannelPtr &channel); void removeChannelSignals(const Tp::TextChannelPtr &channel); class MessagesModelPrivate; MessagesModelPrivate *d; }; #endif // CONVERSATION_MODEL_H diff --git a/KTp/Declarative/pinned-contacts-model.cpp b/KTp/Declarative/pinned-contacts-model.cpp index 918fa02..50a3b14 100644 --- a/KTp/Declarative/pinned-contacts-model.cpp +++ b/KTp/Declarative/pinned-contacts-model.cpp @@ -1,277 +1,277 @@ /* Copyright (C) 2012 Aleix Pol This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pinned-contacts-model.h" #include "conversations-model.h" #include "conversation.h" #include #include #include #include #include #include #include #include #include "debug.h" #include "KTp/presence.h" #include "KTp/contact.h" #include "KTp/persistent-contact.h" class PinnedContactsModelPrivate { public: PinnedContactsModelPrivate() { - conversations = 0; + conversations = nullptr; } QList m_pins; ConversationsModel *conversations; QStringList pinsToString() const { QStringList ret; Q_FOREACH(const KTp::PersistentContactPtr &p, m_pins) { ret += p->accountId(); ret += p->contactId(); } return ret; } }; PinnedContactsModel::PinnedContactsModel(QObject *parent) : QAbstractListModel(parent) , d(new PinnedContactsModelPrivate) { connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)), SIGNAL(countChanged())); connect(this, SIGNAL(rowsRemoved(QModelIndex,int,int)), SIGNAL(countChanged())); } PinnedContactsModel::~PinnedContactsModel() { delete d; } QHash PinnedContactsModel::roleNames() const { QHash roles = QAbstractListModel::roleNames(); roles[PresenceIconRole] = "presenceIcon"; roles[AvailabilityRole] = "available"; roles[ContactRole] = "contact"; roles[AccountRole] = "account"; roles[AlreadyChattingRole] = "alreadyChatting"; return roles; } QStringList PinnedContactsModel::state() const { return d->pinsToString(); } void PinnedContactsModel::setState(const QStringList &pins) { for (int i = 0; i < pins.count(); i += 2) { appendContactPin(KTp::PersistentContact::create(pins[0], pins[1])); } } QModelIndex PinnedContactsModel::indexForContact(const KTp::ContactPtr &contact) const { for (int i = 0; i < d->m_pins.size() && contact; i++) { if (d->m_pins[i]->contactId() == contact->id()) { return index(i); } } return QModelIndex(); } void PinnedContactsModel::setPinning(const Tp::AccountPtr &account, const KTp::ContactPtr &contact, bool newState) { QModelIndex idx = indexForContact(contact); bool found = idx.isValid(); if (newState && !found) { KTp::PersistentContactPtr p = KTp::PersistentContact::create(account->uniqueIdentifier(), contact->id()); appendContactPin(p); } else if (!newState && found) { removeContactPin(d->m_pins[idx.row()]); } } QVariant PinnedContactsModel::data(const QModelIndex &index, int role) const { if (index.isValid()) { KTp::PersistentContactPtr p = d->m_pins[index.row()]; switch(role) { case Qt::DisplayRole: if (p->contact()) { return p->contact()->alias(); } break; case PresenceIconRole: if (p->contact()) { return KTp::Presence(p->contact()->presence()).icon(); } else { return KTp::Presence(Tp::Presence::offline()).icon(); } break; case AvailabilityRole: if (!p->contact()) { return false; } else { return p->contact()->presence().type() != Tp::ConnectionPresenceTypeOffline && p->contact()->presence().type() != Tp::ConnectionPresenceTypeError && p->contact()->presence().type() != Tp::ConnectionPresenceTypeUnset && p->contact()->presence().type() != Tp::ConnectionPresenceTypeUnknown; } case ContactRole: return QVariant::fromValue(p->contact()); case AccountRole: return QVariant::fromValue(p->account()); case AlreadyChattingRole: { if (!p->contact() || !d->conversations) { return false; } bool found = false; for (int i = 0; !found && i < d->conversations->rowCount(); i++) { QModelIndex idx = d->conversations->index(i, 0); KTp::ContactPtr contact = idx.data(ConversationsModel::ConversationRole).value()->targetContact(); found |= contact->id() == p->contact()->id(); } return found; } case Qt::DecorationRole: { QIcon icon; if (p->contact()) { QString file = p->contact()->avatarData().fileName; if (!file.isEmpty()) { icon = QIcon::fromTheme(file); } } if (icon.isNull()) { icon = QIcon::fromTheme(QStringLiteral("im-user")); } return icon; } } } return QVariant(); } int PinnedContactsModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) { return 0; } return d->m_pins.count(); } void PinnedContactsModel::removeContactPin(const KTp::PersistentContactPtr &pin) { int row = d->m_pins.indexOf(pin); if (row >= 0) { beginRemoveRows(QModelIndex(), row, row); d->m_pins.removeAt(row); endRemoveRows(); Q_EMIT stateChanged(); } else qWarning() << "trying to remove missing pin" << pin->contactId(); } void PinnedContactsModel::appendContactPin(const KTp::PersistentContactPtr &pin) { auto samePin = [pin](const KTp::PersistentContactPtr &p) -> bool { return p->contactId() == pin->contactId(); }; if (std::find_if(d->m_pins.constBegin(), d->m_pins.constEnd(), samePin) != d->m_pins.constEnd()) { return; } int s = d->m_pins.size(); beginInsertRows(QModelIndex(), s, s); d->m_pins += pin; endInsertRows(); if (pin->contact()) { contactChanged(pin->contact()); } connect(pin.data(), SIGNAL(contactChanged(KTp::ContactPtr)), SLOT(contactChanged(KTp::ContactPtr))); Q_EMIT stateChanged(); } void PinnedContactsModel::contactChanged(const KTp::ContactPtr &contact) { if (contact) { connect(contact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)), SLOT(contactDataChanged())); connect(contact.data(), SIGNAL(aliasChanged(QString)), SLOT(contactDataChanged())); connect(contact.data(), SIGNAL(presenceChanged(Tp::Presence)), SLOT(contactDataChanged())); } QModelIndex index = indexForContact(contact); Q_EMIT dataChanged(index, index); } void PinnedContactsModel::contactDataChanged() { KTp::Contact *c = qobject_cast(sender()); QModelIndex index = indexForContact(KTp::ContactPtr(c)); Q_EMIT dataChanged(index, index); } void PinnedContactsModel::setConversationsModel(ConversationsModel *model) { beginResetModel(); if (d->conversations) { disconnect(d->conversations, &QAbstractItemModel::rowsAboutToBeRemoved, this, &PinnedContactsModel::conversationsStateChanged); disconnect(d->conversations, &QAbstractItemModel::rowsInserted, this, &PinnedContactsModel::conversationsStateChanged); } d->conversations = model; if (model) { connect(d->conversations, &QAbstractItemModel::rowsAboutToBeRemoved, this, &PinnedContactsModel::conversationsStateChanged); connect(d->conversations, &QAbstractItemModel::rowsInserted, this, &PinnedContactsModel::conversationsStateChanged); } endResetModel(); } void PinnedContactsModel::conversationsStateChanged(const QModelIndex &parent, int start, int end) { for (int i = start; i <= end; i++) { QModelIndex idx = d->conversations->index(i, 0, parent); Conversation *conv = idx.data(ConversationsModel::ConversationRole).value(); QString contactId = conv->targetContact()->id(); Q_FOREACH (const KTp::PersistentContactPtr &p, d->m_pins) { if (p->contactId() == contactId) { QModelIndex contactIdx = indexForContact(p->contact()); //We need to delay the dataChanged until the next event loop, when endRowsRemoved has been called QMetaObject::invokeMethod(this, "dataChanged", Qt::QueuedConnection, Q_ARG(QModelIndex, contactIdx), Q_ARG(QModelIndex, contactIdx)); } } } } ConversationsModel* PinnedContactsModel::conversationsModel() const { return d->conversations; } diff --git a/KTp/Declarative/pinned-contacts-model.h b/KTp/Declarative/pinned-contacts-model.h index 620a174..9a3e7f8 100644 --- a/KTp/Declarative/pinned-contacts-model.h +++ b/KTp/Declarative/pinned-contacts-model.h @@ -1,80 +1,80 @@ /* Copyright (C) 2012 Aleix Pol This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef PINNEDCONTACTSMODEL_H #define PINNEDCONTACTSMODEL_H #include #include #include #include class ConversationsModel; class PinnedContactsModelPrivate; class PinnedContactsModel : public QAbstractListModel { Q_OBJECT Q_PROPERTY(ConversationsModel *conversations READ conversationsModel WRITE setConversationsModel) Q_PROPERTY(QStringList state READ state WRITE setState NOTIFY stateChanged) Q_PROPERTY(int count READ rowCount NOTIFY countChanged) public: - explicit PinnedContactsModel(QObject *parent = 0); + explicit PinnedContactsModel(QObject *parent = nullptr); ~PinnedContactsModel() override; enum role { PresenceIconRole = Qt::UserRole + 1, AvailabilityRole, ContactRole, AccountRole, AlreadyChattingRole }; QHash roleNames() const Q_DECL_OVERRIDE; QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; Q_SLOT void setPinning(const Tp::AccountPtr &account, const KTp::ContactPtr &contact, bool newState); QModelIndex indexForContact(const KTp::ContactPtr &contact) const; ConversationsModel* conversationsModel() const; void setConversationsModel(ConversationsModel *model); QStringList state() const; void setState(const QStringList &state); private Q_SLOTS: void contactDataChanged(); void contactChanged(const KTp::ContactPtr &contact); void conversationsStateChanged(const QModelIndex &parent, int start, int end); Q_SIGNALS: void countChanged(); void stateChanged(); private: void appendContactPin(const KTp::PersistentContactPtr &pin); void removeContactPin(const KTp::PersistentContactPtr &pin); PinnedContactsModelPrivate * const d; }; #endif // PINNEDCONTACTSMODEL_H diff --git a/KTp/Declarative/telepathy-manager.h b/KTp/Declarative/telepathy-manager.h index 5c8b484..e866aa4 100644 --- a/KTp/Declarative/telepathy-manager.h +++ b/KTp/Declarative/telepathy-manager.h @@ -1,178 +1,178 @@ /* Copyright (C) 2013 David Edmundson Copyright (C) 2013 Aleix Pol This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TELEPATHYMANAGER_H #define TELEPATHYMANAGER_H #include #include #include #include #include namespace Tp { class PendingChannelRequest; } class TelepathyManager : public QObject { Q_OBJECT Q_PROPERTY(Tp::AccountManagerPtr accountManager READ accountManager CONSTANT) /** @returns whether there's a ktp-dialout-ui executable */ Q_PROPERTY(bool canDial READ canDial) /** @returns whether there's a ktp-send-file executable */ Q_PROPERTY(bool canSendFiles READ canSendFiles) Q_PROPERTY(bool ready READ isReady NOTIFY ready) public: - TelepathyManager(QObject *parent=0); + TelepathyManager(QObject *parent=nullptr); ~TelepathyManager() override; /** Returns the account manager*/ Tp::AccountManagerPtr accountManager(); /** Add features to ObjectFactories that allow for all TextChannel features * This must be called before becomeReady() */ Q_INVOKABLE void addTextChatFeatures(); /** Add features to ObjectFactories that allow for all features needed for a contact list * This must be called before becomeReady() */ Q_INVOKABLE void addContactListFeatures(); /** Add all useful ObjectFactory features * This must be called before becomeReady() */ Q_INVOKABLE void addAllFeatures(); /** Call Tp::AccountManager::becomeReady */ Q_INVOKABLE void becomeReady(); /** Register an abstractClient to clientRegistrar * @arg client. Clients must subclass AbstractClient and QObject in their implementation to be used in QML * * @arg clientName * The client name MUST be a non-empty string of ASCII digits, letters, dots and/or underscores, starting with a letter, and without sets of two consecutive dots or a dot followed by a digit. * * See ClientRegistrar::registerClient for details * * @return whether registration was successful * */ Q_INVOKABLE bool registerClient(QObject *client, const QString &clientName); Q_INVOKABLE bool unregisterClient(QObject* client); bool canDial() const; bool canSendFiles() const; bool isReady() const; /** Opens UI to start an audio call */ Q_INVOKABLE void openDialUi() const; /** Opens UI to send a file */ Q_INVOKABLE void openSendFileUi() const; /** Opens UI to add a new contact */ Q_INVOKABLE void addContact(); /** Opens UI to join a chat room */ Q_INVOKABLE void joinChatRoom(); /** Opens UI to show the KDE Telepathy settings module */ Q_INVOKABLE void showSettingsKCM(); /** Toggles the visibility of the ktp-contact-list program */ Q_INVOKABLE void toggleContactList(); public Q_SLOTS: /** Start a text chat using the default KTp text application @arg account the account to start the channel from @arg contact the contact to start the channel with @arg delegateToPreferredHandler whether any existing handlers should release handling the channel and pass control to the requested handler */ Tp::PendingChannelRequest* startChat(const Tp::AccountPtr &account, const KTp::ContactPtr &contact, bool delegateToPreferredHandler = true); /** Start a text chat using the preffered client @arg account the account to start the channel from @arg contact the contact to start the channel with @arg preferredHandler the preferred client */ Tp::PendingChannelRequest* startChat(const Tp::AccountPtr &account, const KTp::ContactPtr &contact, const QString &preferredHandler); /** Start an audio call using the default KTp call application @arg account the account to start the channel from @arg contact the contact to start the channel with */ Tp::PendingChannelRequest* startAudioCall(const Tp::AccountPtr &account, const KTp::ContactPtr &contact); /** Start an audio call using the default KTp call application @arg account the account to start the channel from @arg contact the contact to start the channel with */ Tp::PendingChannelRequest* startAudioVideoCall(const Tp::AccountPtr &account, const KTp::ContactPtr &contact); /** Start a file transfer using the default KTp file transfer application @arg account the account to start the channel from @arg contact the contact to start the channel with */ Tp::PendingOperation* startFileTransfer(const Tp::AccountPtr &account, const KTp::ContactPtr &contact, const QUrl& url); /** Open logs using the default KTp log application @arg account the account to start the channel from @arg contact the contact to start the channel with */ void openLogViewer(const Tp::AccountPtr &account, const KTp::ContactPtr &contact); private Q_SLOTS: void contactlistDBusAccessed(QDBusPendingCallWatcher*); Q_SIGNALS: void ready(); private: Tp::AccountManagerPtr m_accountManager; Tp::ClientRegistrarPtr m_clientRegistrar; Tp::AccountFactoryPtr m_accountFactory; Tp::ContactFactoryPtr m_contactFactory; Tp::ConnectionFactoryPtr m_connectionFactory; Tp::ChannelFactoryPtr m_channelFactory; bool m_isReady; }; #endif // DECLARATIVEKTPACTIONS_H diff --git a/KTp/Logger/abstract-logger-plugin.h b/KTp/Logger/abstract-logger-plugin.h index 8ae9848..690d030 100644 --- a/KTp/Logger/abstract-logger-plugin.h +++ b/KTp/Logger/abstract-logger-plugin.h @@ -1,166 +1,166 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef KTP_ABSTRACTLOGGERPLUGIN_H #define KTP_ABSTRACTLOGGERPLUGIN_H #include #include #include namespace KTp { class PendingLoggerDates; class PendingLoggerLogs; class PendingLoggerEntities; class PendingLoggerSearch; class LogEntity; /** * @brief An interface for all KTp Logger plugins * * @since 0.7 * @author Daniel Vrátil */ class KTPCOMMONINTERNALS_EXPORT AbstractLoggerPlugin : public QObject { Q_OBJECT public: /** * Constructor. */ - explicit AbstractLoggerPlugin(QObject *parent = 0); + explicit AbstractLoggerPlugin(QObject *parent = nullptr); /** * Destructor. */ ~AbstractLoggerPlugin() override; /** * Queries all available plugins that handle given @p account for list of dates * with logs of user's chat with @p entity. * * @param account Account to query * @param entity Entity * @return Returns KTp::PendingLoggerDates operation that will emit finished() * signal when all backends are finished. */ virtual KTp::PendingLoggerDates* queryDates(const Tp::AccountPtr &account, const KTp::LogEntity &entity) = 0; /** * Queries all available plugins that handle given @p account for list of * logs of chats with @p entity. * * @param account Account to query * @param entity Entity whose logs should be retrieved * @param date Specific date for which to retrieve logs * @return Returns KTp::PendingLoggerLogs operation that will emit finished() * signal when all backends are finished. */ virtual KTp::PendingLoggerLogs* queryLogs(const Tp::AccountPtr &account, const KTp::LogEntity &entity, const QDate &date) = 0; /** * Queries all available plugins that handle given @p account for list of * entities for which they have conversation logs. * * @param account Account to query * @return Returns KTp::PendingLoggerEntities operation that will emit finished() * signal when all backends are finished. */ virtual KTp::PendingLoggerEntities* queryEntities(const Tp::AccountPtr &account) = 0; /** * Returnes whether plugin handles logs for given @p account. * * For example, a dedicated Facebook plugin will handle only accounts that * represent Facebook accounts, therefore it makes no sense to query it for * logs from GTalk account for instance. * * By default this method returns true, which means that plugin supports any * kind of account. */ virtual bool handlesAccount(const Tp::AccountPtr &account); /** * Removes all logs for given @p account from all available plugins that * handle it. * * @param account Account of which to remove logs */ virtual void clearAccountLogs(const Tp::AccountPtr &account) = 0; /** * Removes all logs for given @p entity from all available plugins that * handle the @p account. * * @param account Account to query * @param entity Entity whose logs to remove */ virtual void clearContactLogs(const Tp::AccountPtr &account, const KTp::LogEntity &entity) = 0; /** * Searches all logs for given @p term. * * @param term Term to search * @return Returns KTp::PendingLoggerSearch operation that will emit finished() * when all results are available */ virtual KTp::PendingLoggerSearch* search(const QString &term) = 0; /** * Sets a new Tp::AccountManager to be used by the plugin. * * The @p accountManager is expected to be in ready state. * * @param accountManager An Tp::AccountManager in the ready state. */ virtual void setAccountManager(const Tp::AccountManagerPtr &accountManager); /** * Returns the set Tp::AccountManager or an empty pointer if none was set. */ virtual Tp::AccountManagerPtr accountManager() const; /** * Checks whether there are any logs for given @p account and @p contact. * * For easy use this method is synchronous and can block for a while in case * of a slower plugin. * * @param account Account to query * @param contact Contact to query * @return Returns whether there are any logs for given person */ virtual bool logsExist(const Tp::AccountPtr &account, const KTp::LogEntity &contact) = 0; private: class Private; Private * const d; }; } // namespace KTp #endif // KTP_ABSTRACTLOGGERPLUGIN_H diff --git a/KTp/Logger/log-manager.cpp b/KTp/Logger/log-manager.cpp index 3042514..c802120 100644 --- a/KTp/Logger/log-manager.cpp +++ b/KTp/Logger/log-manager.cpp @@ -1,171 +1,171 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "log-manager.h" #include "log-manager-private.h" #include "abstract-logger-plugin.h" #include "log-entity.h" #include "pending-logger-dates-impl.h" #include "pending-logger-logs-impl.h" #include "pending-logger-entities-impl.h" #include "pending-logger-search-impl.h" #include #include #include #include "debug.h" using namespace KTp; #define KTP_LOGGER_PLUGIN_VERSION "1" -LogManager* LogManager::Private::s_logManagerInstance = 0; +LogManager* LogManager::Private::s_logManagerInstance = nullptr; void LogManager::Private::loadPlugins() { const KService::List services = KServiceTypeTrader::self()->query( QLatin1String("KTpLogger/Plugin"), QLatin1String("[X-KTp-PluginInfo-Version] == " KTP_LOGGER_PLUGIN_VERSION)); const KPluginInfo::List pluginInfos = KPluginInfo::fromServices(services); Q_FOREACH (const KPluginInfo &pluginInfo, pluginInfos) { const KService::Ptr service = pluginInfo.service(); KPluginFactory *factory = KPluginLoader(service->library()).factory(); if (factory) { qCDebug(KTP_LOGGER) << "loaded factory :" << factory; AbstractLoggerPlugin *plugin = factory->create(q); if (plugin) { qCDebug(KTP_LOGGER) << "loaded logger plugin : " << plugin; plugins << plugin; } } else { qCWarning(KTP_LOGGER) << "error loading plugin :" << service->library(); } } } LogManager::Private::Private(LogManager *parent): q(parent) { loadPlugins(); } LogManager* LogManager::instance() { - if (Private::s_logManagerInstance == 0) { + if (Private::s_logManagerInstance == nullptr) { Private::s_logManagerInstance = new LogManager(); } return Private::s_logManagerInstance; } LogManager::LogManager(): AbstractLoggerPlugin(), d(new Private(this)) { } LogManager::~LogManager() { delete d; } Tp::AccountManagerPtr LogManager::accountManager() const { if (d->plugins.isEmpty()) { return Tp::AccountManagerPtr(); } return d->plugins.first()->accountManager(); } void LogManager::setAccountManager(const Tp::AccountManagerPtr &accountManager) { Q_FOREACH (KTp::AbstractLoggerPlugin *plugin, d->plugins) { plugin->setAccountManager(accountManager); } } PendingLoggerDates* LogManager::queryDates(const Tp::AccountPtr &account, const KTp::LogEntity &entity) { return new PendingLoggerDatesImpl(account, entity, this); } PendingLoggerLogs* LogManager::queryLogs(const Tp::AccountPtr &account, const KTp::LogEntity &entity, const QDate &date) { return new PendingLoggerLogsImpl(account, entity, date, this); } PendingLoggerEntities* LogManager::queryEntities(const Tp::AccountPtr& account) { return new PendingLoggerEntitiesImpl(account, this); } void LogManager::clearAccountLogs(const Tp::AccountPtr &account) { Q_FOREACH (KTp::AbstractLoggerPlugin *plugin, d->plugins) { if (!plugin->handlesAccount(account)) { continue; } plugin->clearAccountLogs(account); } } void LogManager::clearContactLogs(const Tp::AccountPtr &account, const KTp::LogEntity &entity) { Q_FOREACH (KTp::AbstractLoggerPlugin *plugin, d->plugins) { if (!plugin->handlesAccount(account)) { continue; } plugin->clearContactLogs(account, entity); } } PendingLoggerSearch* LogManager::search(const QString& term) { return new PendingLoggerSearchImpl(term, this); } bool LogManager::logsExist(const Tp::AccountPtr &account, const KTp::LogEntity &contact) { Q_FOREACH (KTp::AbstractLoggerPlugin *plugin, d->plugins) { if (!plugin->handlesAccount(account)) { continue; } if (plugin->logsExist(account, contact)) { return true; } } return false; } using namespace KTp; diff --git a/KTp/Logger/pending-logger-dates-impl.h b/KTp/Logger/pending-logger-dates-impl.h index ad0081f..be24bc3 100644 --- a/KTp/Logger/pending-logger-dates-impl.h +++ b/KTp/Logger/pending-logger-dates-impl.h @@ -1,42 +1,42 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef PENDINGLOGGERDATESIMPL_H #define PENDINGLOGGERDATESIMPL_H #include "pending-logger-dates.h" class PendingLoggerDatesImpl : public KTp::PendingLoggerDates { Q_OBJECT public: explicit PendingLoggerDatesImpl(const Tp::AccountPtr &account, const KTp::LogEntity &entity, - QObject* parent = 0); + QObject* parent = nullptr); ~PendingLoggerDatesImpl() override; private Q_SLOTS: void operationFinished(KTp::PendingLoggerOperation *op); private: QList mRunningOps; }; #endif // PENDINGLOGGERDATESIMPL_H diff --git a/KTp/Logger/pending-logger-dates.h b/KTp/Logger/pending-logger-dates.h index dc8bce8..28d0225 100644 --- a/KTp/Logger/pending-logger-dates.h +++ b/KTp/Logger/pending-logger-dates.h @@ -1,82 +1,82 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef KTP_PENDINGLOGGERDATES_H #define KTP_PENDINGLOGGERDATES_H #include #include #include namespace KTp { class LogEntity; /** * @brief An operation that will retrieve list of dates for which there are any * logs in each backend and merges them together. * * The operation will emit finished(KTp::PendingLoggerOperation*) signal when * all dates were retrieved. When an error occurs in any backend hasError() * will be set to true. Use error() to retrieve the error message. * * @since 0.7 * @author Daniel Vrátil */ class KTPCOMMONINTERNALS_EXPORT PendingLoggerDates : public KTp::PendingLoggerOperation { Q_OBJECT public: /** * Destructor. */ ~PendingLoggerDates() override; /** * Returns account for which the dates are queried. */ Tp::AccountPtr account() const; /** * Returns entity for which the dates are queried. */ KTp::LogEntity entity() const; /** * Returns list of retrieved dates. The list is always sort in ascending * order. */ QList dates() const; protected: explicit PendingLoggerDates(const Tp::AccountPtr &account, const KTp::LogEntity &entity, - QObject *parent = 0); + QObject *parent = nullptr); void setDates(const QList &dates); class Private; Private * const d; }; } // namespace KTp #endif // KTP_PENDINGLOGGERDATES_H diff --git a/KTp/Logger/pending-logger-entities-impl.h b/KTp/Logger/pending-logger-entities-impl.h index 106ffb5..268cc5b 100644 --- a/KTp/Logger/pending-logger-entities-impl.h +++ b/KTp/Logger/pending-logger-entities-impl.h @@ -1,41 +1,41 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef PENDINGLOGGERENTITIESIMPL_H #define PENDINGLOGGERENTITIESIMPL_H #include "pending-logger-entities.h" class PendingLoggerEntitiesImpl: public KTp::PendingLoggerEntities { Q_OBJECT public: explicit PendingLoggerEntitiesImpl(const Tp::AccountPtr &account, - QObject *parent = 0); + QObject *parent = nullptr); ~PendingLoggerEntitiesImpl() override; private Q_SLOTS: void operationFinished(KTp::PendingLoggerOperation *op); private: QList mRunningOps; }; #endif // PENDINGLOGGERENTITIESIMPL_H diff --git a/KTp/Logger/pending-logger-entities.h b/KTp/Logger/pending-logger-entities.h index b170cf3..318b14b 100644 --- a/KTp/Logger/pending-logger-entities.h +++ b/KTp/Logger/pending-logger-entities.h @@ -1,74 +1,74 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef KTP_PENDINGLOGGERENTITIES_H #define KTP_PENDINGLOGGERENTITIES_H #include #include #include #include namespace KTp { /** * @brief An operation that will retrieve list of entities for which there are any * logs in each backend and merges them together. * * The operation will emit finished(KTp::PendingLoggerOperation*) signal when * all entities were retrieved. When an error occurs in any backend hasError() * will be set to true. Use error() to retrieve the error message. * * @since 0.7 * @author Daniel Vrátil */ class KTPCOMMONINTERNALS_EXPORT PendingLoggerEntities : public KTp::PendingLoggerOperation { Q_OBJECT public: /** * Destructor. */ ~PendingLoggerEntities() override; /** * Returns account for which the entities are being queried. */ Tp::AccountPtr account() const; /** * Returns list of fetched entities. */ QList entities() const; protected: - explicit PendingLoggerEntities(const Tp::AccountPtr &account, QObject* parent = 0); + explicit PendingLoggerEntities(const Tp::AccountPtr &account, QObject* parent = nullptr); void appendEntities(const QList &entities); void appendEntity(const KTp::LogEntity &entity); class Private; Private * const d; }; } // namespace KTp #endif // KTP_PENDINGLOGGERENTITIES_H diff --git a/KTp/Logger/pending-logger-logs-impl.h b/KTp/Logger/pending-logger-logs-impl.h index b00bca2..fa8056c 100644 --- a/KTp/Logger/pending-logger-logs-impl.h +++ b/KTp/Logger/pending-logger-logs-impl.h @@ -1,43 +1,43 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef PENDINGLOGGERLOGSIMPL_H #define PENDINGLOGGERLOGSIMPL_H #include "pending-logger-logs.h" class PendingLoggerLogsImpl : public KTp::PendingLoggerLogs { Q_OBJECT public: explicit PendingLoggerLogsImpl(const Tp::AccountPtr &account, const KTp::LogEntity &entity, const QDate &date, - QObject *parent = 0); + QObject *parent = nullptr); ~PendingLoggerLogsImpl() override; private Q_SLOTS: void operationFinished(KTp::PendingLoggerOperation *op); private: QList mRunningOps; }; #endif // PENDINGLOGGERLOGSIMPL_H diff --git a/KTp/Logger/pending-logger-logs.h b/KTp/Logger/pending-logger-logs.h index 1e90416..fda8a51 100644 --- a/KTp/Logger/pending-logger-logs.h +++ b/KTp/Logger/pending-logger-logs.h @@ -1,87 +1,87 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef KTP_PENDINGLOGGERLOGS_H #define KTP_PENDINGLOGGERLOGS_H #include #include #include #include namespace KTp { /** * @brief An operation that will retrieve list of chat logs for given account, * entity and date from all backends. * * The operation will emit finished(KTp::PendingLoggerOperation*) signal when * all logs were retrieved. When an error occurs in any backend hasError() * will be set to true. Use error() to retrieve the error message. * * @since 0.7 * @author Daniel Vrátil */ class KTPCOMMONINTERNALS_EXPORT PendingLoggerLogs : public KTp::PendingLoggerOperation { Q_OBJECT public: /** * Destructor. */ ~PendingLoggerLogs() override; /** * Returns account for which logs are being queried. */ Tp::AccountPtr account() const; /** * Returns entity for which logs are being queried. */ KTp::LogEntity entity() const; /** * Returns date for which logs are being queried. */ QDate date() const; /** * Returns list of retrieved log messages. */ QList logs() const; protected: explicit PendingLoggerLogs(const Tp::AccountPtr &account, const KTp::LogEntity &entity, const QDate &date, - QObject* parent = 0); + QObject* parent = nullptr); void appendLogs(const QList &logs); class Private; Private * const d; }; } // namespace KTp #endif // KTP_PENDINGLOGGERLOGS_H diff --git a/KTp/Logger/pending-logger-operation.h b/KTp/Logger/pending-logger-operation.h index 9a5a9a8..155025a 100644 --- a/KTp/Logger/pending-logger-operation.h +++ b/KTp/Logger/pending-logger-operation.h @@ -1,60 +1,60 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef KTP_PENDINGLOGGEROPERATION_H #define KTP_PENDINGLOGGEROPERATION_H #include #include namespace KTp { class AbstractLoggerPlugin; class LogManager; class KTPCOMMONINTERNALS_EXPORT PendingLoggerOperation : public QObject { Q_OBJECT public: ~PendingLoggerOperation() override; bool hasError() const; QString error() const; Q_SIGNALS: void finished(KTp::PendingLoggerOperation *self); protected: - explicit PendingLoggerOperation(QObject *parent = 0); + explicit PendingLoggerOperation(QObject *parent = nullptr); void setError(const QString &error); void emitFinished(); QList plugins() const; private: class Private; Private * const d; Q_PRIVATE_SLOT(d, void __k__doEmitFinished()); }; } #endif // KTP_PENDINGLOGGEROPERATION_H diff --git a/KTp/Logger/pending-logger-search-impl.h b/KTp/Logger/pending-logger-search-impl.h index 23fca6a..e49316f 100644 --- a/KTp/Logger/pending-logger-search-impl.h +++ b/KTp/Logger/pending-logger-search-impl.h @@ -1,45 +1,45 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef PENDINGLOGGERSEARCHIMPL_H #define PENDINGLOGGERSEARCHIMPL_H #include namespace Tpl { class PendingOperation; } class PendingLoggerSearchImpl : public KTp::PendingLoggerSearch { Q_OBJECT public: - explicit PendingLoggerSearchImpl(const QString& term, QObject* parent = 0); + explicit PendingLoggerSearchImpl(const QString& term, QObject* parent = nullptr); ~PendingLoggerSearchImpl() override; public Q_SLOTS: void operationFinished(KTp::PendingLoggerOperation *operation); private: QList mRunningOps; }; #endif // PENDINGLOGGERSEARCHIMPL_H diff --git a/KTp/Logger/pending-logger-search.h b/KTp/Logger/pending-logger-search.h index 6b55f22..f53b1b4 100644 --- a/KTp/Logger/pending-logger-search.h +++ b/KTp/Logger/pending-logger-search.h @@ -1,76 +1,76 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef KTP_PENDINGLOGGERSEARCH_H #define KTP_PENDINGLOGGERSEARCH_H #include #include #include namespace KTp { /** * @brief An operation that will retrieve list of chat logs matching given search * term. * * The operation will emit finished(KTp::PendingLoggerOperation*) signal when * search is finished. When an error occurs in any backend hasError() will be * set to true. Use error() to retrieve the error message. * * @since 0.7 * @author Daniel Vrátil */ class KTPCOMMONINTERNALS_EXPORT PendingLoggerSearch : public KTp::PendingLoggerOperation { Q_OBJECT public: /** * Destructor. */ ~PendingLoggerSearch() override; /** * Returns the search term that is used. */ QString term() const; /** * Returns list of hits matching givem search term. */ QList searchHits() const; protected: explicit PendingLoggerSearch(const QString &term, - QObject *parent = 0); + QObject *parent = nullptr); void appendSearchHits(const QList &searchHits); void appendSearchHit(const KTp::LogSearchHit &searchHit); private: class Private; Private * const d; }; } // namespace KTp #endif // KTP_PENDINGLOGGERSEARCH_H diff --git a/KTp/Logger/plugins/tplogger/pending-tp-logger-dates.h b/KTp/Logger/plugins/tplogger/pending-tp-logger-dates.h index 9539c80..68973cb 100644 --- a/KTp/Logger/plugins/tplogger/pending-tp-logger-dates.h +++ b/KTp/Logger/plugins/tplogger/pending-tp-logger-dates.h @@ -1,44 +1,44 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef PENDINGTPLOGGERDATES_H #define PENDINGTPLOGGERDATES_H #include "KTp/Logger/pending-logger-dates.h" namespace Tpl { class PendingOperation; } class PendingTpLoggerDates : public KTp::PendingLoggerDates { Q_OBJECT public: explicit PendingTpLoggerDates(const Tp::AccountPtr &account, const KTp::LogEntity &entity, - QObject *parent = 0); + QObject *parent = nullptr); ~PendingTpLoggerDates() override; private Q_SLOTS: void datesRetrieved(Tpl::PendingOperation *op); }; #endif // PENDINGTPLOGGERDATES_H diff --git a/KTp/Logger/plugins/tplogger/pending-tp-logger-entities.h b/KTp/Logger/plugins/tplogger/pending-tp-logger-entities.h index 7a00635..2f33188 100644 --- a/KTp/Logger/plugins/tplogger/pending-tp-logger-entities.h +++ b/KTp/Logger/plugins/tplogger/pending-tp-logger-entities.h @@ -1,43 +1,43 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef PENDINGTPLOGGERENTITIES_H #define PENDINGTPLOGGERENTITIES_H #include namespace Tpl { class PendingOperation; } class PendingTpLoggerEntities : public KTp::PendingLoggerEntities { Q_OBJECT public: explicit PendingTpLoggerEntities(const Tp::AccountPtr &account, - QObject *parent = 0); + QObject *parent = nullptr); ~PendingTpLoggerEntities() override; private Q_SLOTS: void entitiesRetrieved(Tpl::PendingOperation *op); }; #endif // PENDINGTPLOGGERENTITIES_H diff --git a/KTp/Logger/plugins/tplogger/pending-tp-logger-logs.h b/KTp/Logger/plugins/tplogger/pending-tp-logger-logs.h index 118dee9..a17bbcf 100644 --- a/KTp/Logger/plugins/tplogger/pending-tp-logger-logs.h +++ b/KTp/Logger/plugins/tplogger/pending-tp-logger-logs.h @@ -1,45 +1,45 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef PENDINGTPLOGGERLOGS_H #define PENDINGTPLOGGERLOGS_H #include "KTp/Logger/pending-logger-logs.h" namespace Tpl { class PendingOperation; } class PendingTpLoggerLogs : public KTp::PendingLoggerLogs { Q_OBJECT public: explicit PendingTpLoggerLogs(const Tp::AccountPtr &account, const KTp::LogEntity &entity, const QDate &date, - QObject *parent = 0); + QObject *parent = nullptr); ~PendingTpLoggerLogs() override; private Q_SLOTS: void logsRetrieved(Tpl::PendingOperation *op); }; #endif // PENDINGTPLOGGERLOGS_H diff --git a/KTp/Logger/plugins/tplogger/pending-tp-logger-search.h b/KTp/Logger/plugins/tplogger/pending-tp-logger-search.h index d2dc736..0b9f154 100644 --- a/KTp/Logger/plugins/tplogger/pending-tp-logger-search.h +++ b/KTp/Logger/plugins/tplogger/pending-tp-logger-search.h @@ -1,41 +1,41 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef PENDINGTPLOGGERSEARCH_H #define PENDINGTPLOGGERSEARCH_H #include namespace Tpl { class PendingOperation; } class PendingTpLoggerSearch : public KTp::PendingLoggerSearch { Q_OBJECT public: - explicit PendingTpLoggerSearch(const QString& term, QObject* parent = 0); + explicit PendingTpLoggerSearch(const QString& term, QObject* parent = nullptr); ~PendingTpLoggerSearch() override; private Q_SLOTS: void searchFinished(Tpl::PendingOperation *op); }; #endif // PENDINGTPLOGGERSEARCH_H diff --git a/KTp/Logger/plugins/tplogger/utils.cpp b/KTp/Logger/plugins/tplogger/utils.cpp index 764c6a8..dfd55e4 100644 --- a/KTp/Logger/plugins/tplogger/utils.cpp +++ b/KTp/Logger/plugins/tplogger/utils.cpp @@ -1,37 +1,37 @@ /* * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "utils.h" Tpl::EntityPtr Utils::toTplEntity(const KTp::LogEntity &entity) { return Tpl::Entity::create(entity.id().toLatin1().constData(), entity.entityType() == Tp::HandleTypeContact ? Tpl::EntityTypeContact : Tpl::EntityTypeRoom, entity.alias().toLatin1().constData(), - 0); + nullptr); } KTp::LogEntity Utils::fromTplEntity(const Tpl::EntityPtr& entity) { return KTp::LogEntity(entity->entityType() == Tpl::EntityTypeContact ? Tp::HandleTypeContact : Tp::HandleTypeRoom, entity->identifier(), entity->alias()); } diff --git a/KTp/Logger/scrollback-manager.h b/KTp/Logger/scrollback-manager.h index ef1fe5e..6b637ba 100644 --- a/KTp/Logger/scrollback-manager.h +++ b/KTp/Logger/scrollback-manager.h @@ -1,81 +1,81 @@ /* Copyright (C) 2011 Dominik Schmidt Copyright (C) 2013 Daniel Vrátil This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SCROLLBACKMANAGER_H #define SCROLLBACKMANAGER_H #include namespace KTp { class PendingLoggerOperation; } class KTPCOMMONINTERNALS_EXPORT ScrollbackManager : public QObject { Q_OBJECT public: - explicit ScrollbackManager(QObject *parent = 0); + explicit ScrollbackManager(QObject *parent = nullptr); ~ScrollbackManager() override; bool exists() const; void setTextChannel(const Tp::AccountPtr &account, const Tp::TextChannelPtr &textChannel); /** * This is an alternative for setTextChannel() to allow for offline scrollback * * @param account The account of the contact * @param contactId id of the contact for which the screollback is requested */ void setAccountAndContact(const Tp::AccountPtr &account, const QString &contactId, const QString &contactAlias = QString()); /** * Sets amount of messages to be fetched via @p fetchScrollback() */ void setScrollbackLength(int n); int scrollbackLength() const; /** * Fetches last N message,s as set via setFetchAmount() */ void fetchScrollback(); /** * Fetches last @p n messages * If @p fromMessageToken is specified, it fetches last @p n messages * from the message with the given token */ void fetchHistory(int n, const QString &fromMessageToken = QString()); Q_SIGNALS: void fetched(const QList &messages); private Q_SLOTS: void onDatesFinished(KTp::PendingLoggerOperation *po); void onEventsFinished(KTp::PendingLoggerOperation *po); private: class Private; Private * const d; }; #endif // SCROLLBACKMANAGER_H diff --git a/KTp/Models/abstract-grouping-proxy-model.cpp b/KTp/Models/abstract-grouping-proxy-model.cpp index c464c26..b82c246 100644 --- a/KTp/Models/abstract-grouping-proxy-model.cpp +++ b/KTp/Models/abstract-grouping-proxy-model.cpp @@ -1,378 +1,378 @@ /* * Turns a list model into a tree allowing nodes to be in multiple groups * * Copyright (C) 2012 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "abstract-grouping-proxy-model.h" #include #include #include "debug.h" class KTp::AbstractGroupingProxyModel::Private { public: QAbstractItemModel *source; //keep a cache of what groups an item belongs to QHash > groupCache; //item -> groups QMultiHash proxyMap; QHash groupMap; }; class ProxyNode : public QStandardItem { public: ProxyNode(const QPersistentModelIndex &sourceIndex); QVariant data(int role) const override; void changed(); //expose protected method in QStandardItem QString group() const; private: const QPersistentModelIndex m_sourceIndex; }; class GroupNode : public QStandardItem { public: GroupNode(const QString &groupId); QString group() const; QVariant data(int role) const override; bool forced() const; void changed(); //expose protected method in QStandardItem void setForced(bool forced); private: const QString m_groupId; bool m_forced; }; ProxyNode::ProxyNode(const QPersistentModelIndex &sourceIndex): QStandardItem(), m_sourceIndex(sourceIndex) { } QVariant ProxyNode::data(int role) const { return m_sourceIndex.data(role); } void ProxyNode::changed() { QStandardItem::emitDataChanged(); } QString ProxyNode::group() const { //FIXME is this a hack? GroupNode *groupNode = static_cast(parent()); if (groupNode) { return groupNode->group(); } return QString(); } GroupNode::GroupNode(const QString &groupId): QStandardItem(), m_groupId(groupId), m_forced(false) { } QString GroupNode::group() const { return m_groupId; } QVariant GroupNode::data(int role) const { KTp::AbstractGroupingProxyModel *proxyModel = qobject_cast(model()); Q_ASSERT(proxyModel); return proxyModel->dataForGroup(m_groupId, role); } void GroupNode::setForced(bool forced) { m_forced = forced; } bool GroupNode::forced() const { return m_forced; } void GroupNode::changed() { QStandardItem::emitDataChanged(); } KTp::AbstractGroupingProxyModel::AbstractGroupingProxyModel(QAbstractItemModel *source): QStandardItemModel(source), d(new KTp::AbstractGroupingProxyModel::Private()) { d->source = source; //we have to process all existing rows in the model, but must never call a virtual method from a constructor as it will crash. //we use a single shot timer to get round this QTimer::singleShot(0, this, SLOT(onLoad())); } KTp::AbstractGroupingProxyModel::~AbstractGroupingProxyModel() { delete d; } QHash KTp::AbstractGroupingProxyModel::roleNames() const { return d->source->roleNames(); } void KTp::AbstractGroupingProxyModel::forceGroup(const QString &group) { GroupNode* groupNode = itemForGroup(group); groupNode->setForced(true); } void KTp::AbstractGroupingProxyModel::unforceGroup(const QString &group) { GroupNode* groupNode = d->groupMap[group]; if (!groupNode) { return; } //mark that this group can be removed when it's empty groupNode->setForced(false); //if group is already empty remove it if (groupNode->rowCount() == 0) { takeRow(groupNode->row()); d->groupMap.remove(groupNode->group()); } } void KTp::AbstractGroupingProxyModel::groupChanged(const QString &group) { GroupNode *node = d->groupMap[group]; if (node) { node->changed(); } } /* Called when source items inserts a row * * For each new row, create a proxyNode. * If it's at the top level add it to the relevant group nodes. * Otherwise add it to the relevant proxy nodes in our model */ void KTp::AbstractGroupingProxyModel::onRowsInserted(const QModelIndex &sourceParent, int start, int end) { //if top level in root model if (!sourceParent.isValid()) { for (int i = start; i <= end; i++) { QModelIndex index = d->source->index(i, 0, sourceParent); Q_FOREACH(const QString &group, groupsForIndex(index)) { addProxyNode(index, itemForGroup(group)); } } } else { for (int i = start; i <= end; i++) { QModelIndex index = d->source->index(i, 0, sourceParent); QHash::const_iterator it = d->proxyMap.constFind(sourceParent); while (it != d->proxyMap.constEnd() && it.key() == sourceParent) { addProxyNode(index, it.value()); it++; } } } } #include void KTp::AbstractGroupingProxyModel::addProxyNode(const QModelIndex &sourceIndex, QStandardItem *parent) { Q_ASSERT(sourceIndex.isValid()); if (!sourceIndex.isValid()) { return; } ProxyNode *proxyNode = new ProxyNode(sourceIndex); d->proxyMap.insertMulti(sourceIndex, proxyNode); parent->appendRow(proxyNode); //add proxy nodes for all children of this sourceIndex for (int i=0; i < d->source->rowCount(sourceIndex); i++) { addProxyNode(sourceIndex.child(i,0), proxyNode); } } void KTp::AbstractGroupingProxyModel::removeProxyNodes(const QModelIndex &sourceIndex, const QList &removedItems) { Q_FOREACH(ProxyNode *proxy, removedItems) { QStandardItem *parentItem = proxy->parent(); //also remove child items of this proxy node from the proxy map for (int i = 0 ; i < d->source->rowCount(sourceIndex) ; i++) { //we always remove child(0) because we're deleting the first child each time removeProxyNodes(sourceIndex.child(i,0), QList() << dynamic_cast(proxy->child(0))); } parentItem->removeRow(proxy->row()); d->proxyMap.remove(sourceIndex, proxy); //if the parent item to this proxy node is now empty, and is a top level item - if (parentItem->rowCount() == 0 && parentItem->parent() == 0 ) { + if (parentItem->rowCount() == 0 && parentItem->parent() == nullptr ) { GroupNode* groupNode = dynamic_cast(parentItem); //do not delete forced groups if (groupNode->forced() == false) { takeRow(groupNode->row()); d->groupMap.remove(groupNode->group()); } } } } /* * Called when a row is remove from the source model model * Find all existing proxy models and delete thems */ void KTp::AbstractGroupingProxyModel::onRowsRemoved(const QModelIndex &sourceParent, int start, int end) { for (int i = start; i<=end; i++) { QPersistentModelIndex index = d->source->index(i, 0, sourceParent); QList itemsToRemove; QHash::const_iterator it = d->proxyMap.constFind(index); while (it != d->proxyMap.constEnd() && it.key() == index) { // qCDebug(KTP_MODELS) << "removing row" << index.data(); itemsToRemove.append(it.value()); ++it; } d->groupCache.remove(index); removeProxyNodes(index, itemsToRemove); } } /* * Called when source model changes data * If it's the top level item in the source model detect if the groups have changed, if so update as appropriately * Find all proxy nodes, and make dataChanged() get emitted */ void KTp::AbstractGroupingProxyModel::onDataChanged(const QModelIndex &sourceTopLeft, const QModelIndex &sourceBottomRight) { for (int i = sourceTopLeft.row(); i <= sourceBottomRight.row(); i++) { QPersistentModelIndex index = sourceTopLeft.sibling(i,0); if (!index.isValid()) { continue; } //if top level item if (!sourceTopLeft.parent().isValid()) { //groupsSet has changed...update as appropriate QSet itemGroups = groupsForIndex(d->source->index(i, 0, sourceTopLeft.parent())); if (d->groupCache[index] != itemGroups) { d->groupCache[index] = itemGroups; //loop through existing proxy nodes, and check each one is still valid. QHash::const_iterator it = d->proxyMap.constFind(index); QList removedItems; while (it != d->proxyMap.constEnd() && it.key() == index) { // if proxy's group is still in the item's groups. if (itemGroups.contains(it.value()->group())) { itemGroups.remove(it.value()->group()); } else { //remove the proxy item //cache to list and remove once outside the const_iterator removedItems.append(it.value()); qCDebug(KTP_MODELS) << "removing " << index.data().toString() << " from group " << it.value()->group(); } ++it; } removeProxyNodes(index, removedItems); //remaining items in itemGroups are now the new groups Q_FOREACH(const QString &group, itemGroups) { GroupNode *groupNode = itemForGroup(group); addProxyNode(index, groupNode); qCDebug(KTP_MODELS) << "adding " << index.data().toString() << " to group " << group; } } } //mark all proxy nodes as changed QHash::const_iterator it = d->proxyMap.constFind(index); while (it != d->proxyMap.constEnd() && it.key() == index) { it.value()->changed(); ++it; } } } void KTp::AbstractGroupingProxyModel::onLoad() { if (d->source->rowCount() > 0) { onRowsInserted(QModelIndex(), 0, d->source->rowCount()-1); } connect(d->source, SIGNAL(modelReset()), SLOT(onModelReset())); connect(d->source, SIGNAL(rowsInserted(QModelIndex, int,int)), SLOT(onRowsInserted(QModelIndex,int,int))); connect(d->source, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), SLOT(onRowsRemoved(QModelIndex,int,int))); connect(d->source, SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(onDataChanged(QModelIndex,QModelIndex))); } /* Called when source model gets reset * Delete all local caches/maps and wipe the current QStandardItemModel */ void KTp::AbstractGroupingProxyModel::onModelReset() { clear(); d->groupCache.clear(); d->proxyMap.clear(); d->groupMap.clear(); qCDebug(KTP_MODELS) << "reset"; if (d->source->rowCount() > 0) { onRowsInserted(QModelIndex(), 0, d->source->rowCount()-1); } } GroupNode* KTp::AbstractGroupingProxyModel::itemForGroup(const QString &group) { if (d->groupMap.contains(group)) { return d->groupMap[group]; } else { GroupNode* item = new GroupNode(group); appendRow(item); d->groupMap[group] = item; return item; } } diff --git a/KTp/Models/accounts-list-model.h b/KTp/Models/accounts-list-model.h index 262149a..4606b32 100644 --- a/KTp/Models/accounts-list-model.h +++ b/KTp/Models/accounts-list-model.h @@ -1,84 +1,84 @@ /* * This file is part of ktp-common-internals * * Copyright (C) 2009 Collabora Ltd. * Copyright (C) 2012 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KTP_ACCOUNTS_LIST_MODEL_H #define KTP_ACCOUNTS_LIST_MODEL_H #include #include #include #include namespace KTp { class KTPMODELS_EXPORT AccountsListModel : public QAbstractListModel { Q_OBJECT Q_PROPERTY(int count READ rowCount); Q_DISABLE_COPY(AccountsListModel); public: enum Roles { ConnectionStateRole = Qt::UserRole, ConnectionStateDisplayRole = Qt::UserRole+1, ConnectionStateIconRole, ConnectionErrorMessageDisplayRole, ConnectionProtocolNameRole, StatusHandlerSessionPresenceRole, StatusHandlerPresenceRole, RequestedPresenceRole, IconNameRole, EnabledRole, AccountRole }; - explicit AccountsListModel(QObject *parent = 0); + explicit AccountsListModel(QObject *parent = nullptr); ~AccountsListModel() override; QHash roleNames() const Q_DECL_OVERRIDE; void setAccountSet(const Tp::AccountSetPtr &accountSet); Q_SCRIPTABLE QVariant get(int row, const QByteArray& role) const; int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; bool setData(const QModelIndex &index, const QVariant &value, int role) override; private Q_SLOTS: void onAccountAdded(const Tp::AccountPtr &account); void onAccountRemoved(const Tp::AccountPtr &account); void onAccountUpdated(); private: class Private; Private * const d; const QString connectionStateString(const Tp::AccountPtr &account) const; const QIcon connectionStateIcon(const Tp::AccountPtr &account) const; const QString connectionStatusReason(const Tp::AccountPtr &account) const; }; } #endif // header guard diff --git a/KTp/Models/contacts-filter-model.h b/KTp/Models/contacts-filter-model.h index e9c4d3e..06692f5 100644 --- a/KTp/Models/contacts-filter-model.h +++ b/KTp/Models/contacts-filter-model.h @@ -1,310 +1,310 @@ /* * Provide some filters on the account model * * Copyright (C) 2011,2012 David Edmundson * Copyright (C) 2012 Daniele E. Domenichelli * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CONTACTSFILTERMODEL_H #define CONTACTSFILTERMODEL_H #include #include #include namespace KTp { /** * \brief Class used to sort and filter the contacts. */ class KTPMODELS_EXPORT ContactsFilterModel : public QSortFilterProxyModel { Q_OBJECT Q_DISABLE_COPY(ContactsFilterModel) Q_ENUMS(PresenceFilterFlag CapabilityFilterFlag SubscriptionStateFilterFlag) Q_FLAGS(PresenceTypeFilterFlags CapabilityFilterFlags SubscriptionStateFilterFlags) Q_PROPERTY(PresenceTypeFilterFlags presenceTypeFilterFlags READ presenceTypeFilterFlags RESET clearPresenceTypeFilterFlags WRITE setPresenceTypeFilterFlags NOTIFY presenceTypeFilterFlagsChanged) Q_PROPERTY(CapabilityFilterFlags capabilityFilterFlags READ capabilityFilterFlags RESET clearCapabilityFilterFlags WRITE setCapabilityFilterFlags NOTIFY capabilityFilterFlagsChanged) // FIXME This resumes Subscription state, Publish state and blocking state, perhaps we should find a better name Q_PROPERTY(SubscriptionStateFilterFlags subscriptionStateFilterFlags READ subscriptionStateFilterFlags RESET clearSubscriptionStateFilterFlags WRITE setSubscriptionStateFilterFlags NOTIFY subscriptionStateFilterFlagsChanged) // Filters on all fields Q_PROPERTY(QString globalFilterString READ globalFilterString RESET clearGlobalFilterString WRITE setGlobalFilterString NOTIFY globalFilterStringChanged) Q_PROPERTY(Qt::MatchFlags globalFilterMatchFlags READ globalFilterMatchFlags RESET resetGlobalFilterMatchFlags WRITE setGlobalFilterMatchFlags NOTIFY globalFilterMatchFlagsChanged) Q_PROPERTY(QString displayNameFilterString READ displayNameFilterString RESET clearDisplayNameFilterString WRITE setDisplayNameFilterString NOTIFY displayNameFilterStringChanged) Q_PROPERTY(QString nicknameFilterString READ nicknameFilterString RESET clearNicknameFilterString WRITE setNicknameFilterString NOTIFY nicknameFilterStringChanged) Q_PROPERTY(QString aliasFilterString READ aliasFilterString RESET clearAliasFilterString WRITE setAliasFilterString NOTIFY aliasFilterStringChanged) Q_PROPERTY(QString groupsFilterString READ groupsFilterString RESET clearGroupsFilterString WRITE setGroupsFilterString NOTIFY groupsFilterStringChanged) Q_PROPERTY(QString idFilterString READ idFilterString RESET clearIdFilterString WRITE setIdFilterString NOTIFY idFilterStringChanged) Q_PROPERTY(QStringList tubesFilterStrings READ tubesFilterStrings RESET clearTubesFilterStrings WRITE setTubesFilterStrings NOTIFY tubesFilterStringsChanged) Q_PROPERTY(Qt::MatchFlags displayNameFilterMatchFlags READ displayNameFilterMatchFlags RESET resetDisplayNameFilterMatchFlags WRITE setDisplayNameFilterMatchFlags NOTIFY displayNameFilterMatchFlagsChanged) Q_PROPERTY(Qt::MatchFlags nicknameFilterMatchFlags READ nicknameFilterMatchFlags RESET resetNicknameFilterMatchFlags WRITE setNicknameFilterMatchFlags NOTIFY nicknameFilterMatchFlagsChanged) Q_PROPERTY(Qt::MatchFlags aliasFilterMatchFlags READ aliasFilterMatchFlags RESET resetAliasFilterMatchFlags WRITE setAliasFilterMatchFlags NOTIFY aliasFilterMatchFlagsChanged) Q_PROPERTY(Qt::MatchFlags groupsFilterMatchFlags READ groupsFilterMatchFlags RESET resetGroupsFilterMatchFlags WRITE setGroupsFilterMatchFlags NOTIFY groupsFilterMatchFlagsChanged) Q_PROPERTY(Qt::MatchFlags idFilterMatchFlags READ idFilterMatchFlags RESET resetIdFilterMatchFlags WRITE setIdFilterMatchFlags NOTIFY idFilterMatchFlagsChanged) Q_PROPERTY(Tp::AccountPtr accountFilter READ accountFilter RESET clearAccountFilter WRITE setAccountFilter NOTIFY accountFilterChanged) Q_PROPERTY(QString sortRoleString READ sortRoleString WRITE setSortRoleString) public: enum PresenceTypeFilterFlag { DoNotFilterByPresence = 0x0000, HidePresenceTypeUnset = 0x0001, HidePresenceTypeOffline = 0x0002, HidePresenceTypeAvailable = 0x0004, HidePresenceTypeAway = 0x0008, HidePresenceTypeExtendedAway = 0x0010, HidePresenceTypeHidden = 0x0020, HidePresenceTypeBusy = 0x0040, HidePresenceTypeUnknown = 0x0080, HidePresenceTypeError = 0x0100, HideAllOffline = HidePresenceTypeUnset | HidePresenceTypeOffline | HidePresenceTypeUnknown | HidePresenceTypeError, HideAllOnline = HidePresenceTypeAvailable | HidePresenceTypeAway | HidePresenceTypeExtendedAway | HidePresenceTypeHidden | HidePresenceTypeBusy, HideAllUnavailable = HideAllOffline | HidePresenceTypeAway | HidePresenceTypeExtendedAway | HidePresenceTypeBusy, ShowOnlyConnected = HideAllOffline, ShowOnlyDisconnected = HideAllOnline, ShowAll = DoNotFilterByPresence }; Q_DECLARE_FLAGS(PresenceTypeFilterFlags, PresenceTypeFilterFlag) enum CapabilityFilterFlag { DoNotFilterByCapability = 0x0000, FilterByTextChatCapability = 0x0001, FilterByAudioCallCapability = 0x0002, FilterByVideoCallCapability = 0x0004, FilterByFileTransferCapability = 0x0008, FilterByTubes = 0x0010, CustomFilterCapability = 0x10000 // a placemark for custom capabilities in inherited classes }; Q_DECLARE_FLAGS(CapabilityFilterFlags, CapabilityFilterFlag) enum SubscriptionStateFilterFlag { DoNotFilterBySubscription = 0x0000, HideSubscriptionStateNo = 0x0001, HideSubscriptionStateAsk = 0x0002, HideSubscriptionStateYes = 0x0004, HidePublishStateNo = 0x0010, HidePublishStateAsk = 0x0020, HidePublishStateYes = 0x0040, HideBlocked = 0x0100, HideNonBlocked = 0x0200, ShowOnlyBlocked = HideNonBlocked }; Q_DECLARE_FLAGS(SubscriptionStateFilterFlags, SubscriptionStateFilterFlag) - ContactsFilterModel(QObject *parent = 0); + ContactsFilterModel(QObject *parent = nullptr); ~ContactsFilterModel() override; QVariant data(const QModelIndex &index, int role) const override; void setSourceModel(QAbstractItemModel *sourceModel) override; void invalidateFilter(); PresenceTypeFilterFlags presenceTypeFilterFlags() const; Q_SLOT void clearPresenceTypeFilterFlags(); Q_SLOT void setPresenceTypeFilterFlags(PresenceTypeFilterFlags presenceTypeFilterFlags); Q_SIGNAL void presenceTypeFilterFlagsChanged(PresenceTypeFilterFlags presenceTypeFilterFlags); CapabilityFilterFlags capabilityFilterFlags() const; Q_SLOT void clearCapabilityFilterFlags(); Q_SLOT void setCapabilityFilterFlags(CapabilityFilterFlags capabilityFilterFlags); Q_SIGNAL void capabilityFilterFlagsChanged(CapabilityFilterFlags capabilityFilterFlags); SubscriptionStateFilterFlags subscriptionStateFilterFlags() const; Q_SLOT void clearSubscriptionStateFilterFlags(); Q_SLOT void setSubscriptionStateFilterFlags(SubscriptionStateFilterFlags subscriptionStateFilterFlags); Q_SIGNAL void subscriptionStateFilterFlagsChanged(SubscriptionStateFilterFlags subscriptionStateFilterFlags); QString globalFilterString() const; Q_SLOT void clearGlobalFilterString(); Q_SLOT void setGlobalFilterString(const QString &globalFilterString); Q_SIGNAL void globalFilterStringChanged(const QString &globalFilterString); Qt::MatchFlags globalFilterMatchFlags() const; Q_SLOT void resetGlobalFilterMatchFlags(); Q_SLOT void setGlobalFilterMatchFlags(Qt::MatchFlags globalStringMatchFlags); Q_SIGNAL void globalFilterMatchFlagsChanged(Qt::MatchFlags globalStringMatchFlags); QString displayNameFilterString() const; Q_SLOT void clearDisplayNameFilterString(); Q_SLOT void setDisplayNameFilterString(const QString &displayNameFilterString); Q_SIGNAL void displayNameFilterStringChanged(const QString &displayNameFilterString); Qt::MatchFlags displayNameFilterMatchFlags() const; Q_SLOT void resetDisplayNameFilterMatchFlags(); Q_SLOT void setDisplayNameFilterMatchFlags(Qt::MatchFlags displayNameFilterMatchFlags); Q_SIGNAL void displayNameFilterMatchFlagsChanged(Qt::MatchFlags displayNameFilterMatchFlags); QString nicknameFilterString() const; Q_SLOT void clearNicknameFilterString(); Q_SLOT void setNicknameFilterString(const QString &nicknameFilterString); Q_SIGNAL void nicknameFilterStringChanged(const QString &nicknameFilterString); Qt::MatchFlags nicknameFilterMatchFlags() const; Q_SLOT void resetNicknameFilterMatchFlags(); Q_SLOT void setNicknameFilterMatchFlags(Qt::MatchFlags nicknameFilterMatchFlags); Q_SIGNAL void nicknameFilterMatchFlagsChanged(Qt::MatchFlags nicknameFilterMatchFlags); QString aliasFilterString() const; Q_SLOT void clearAliasFilterString(); Q_SLOT void setAliasFilterString(const QString &aliasFilterString); Q_SIGNAL void aliasFilterStringChanged(const QString &aliasFilterString); Qt::MatchFlags aliasFilterMatchFlags() const; Q_SLOT void resetAliasFilterMatchFlags(); Q_SLOT void setAliasFilterMatchFlags(Qt::MatchFlags aliasFilterMatchFlags); Q_SIGNAL void aliasFilterMatchFlagsChanged(Qt::MatchFlags aliasFilterMatchFlags); QString groupsFilterString() const; Q_SLOT void clearGroupsFilterString(); Q_SLOT void setGroupsFilterString(const QString &groupsFilterString); Q_SIGNAL void groupsFilterStringChanged(const QString &groupsFilterString); Qt::MatchFlags groupsFilterMatchFlags() const; Q_SLOT void resetGroupsFilterMatchFlags(); Q_SLOT void setGroupsFilterMatchFlags(Qt::MatchFlags groupsFilterMatchFlags); Q_SIGNAL void groupsFilterMatchFlagsChanged(Qt::MatchFlags groupsFilterMatchFlags); QString idFilterString() const; Q_SLOT void clearIdFilterString(); Q_SLOT void setIdFilterString(const QString &idFilterString); Q_SIGNAL void idFilterStringChanged(const QString &idFilterString); Qt::MatchFlags idFilterMatchFlags() const; Q_SLOT void resetIdFilterMatchFlags(); Q_SLOT void setIdFilterMatchFlags(Qt::MatchFlags idFilterMatchFlags); Q_SIGNAL void idFilterMatchFlagsChanged(Qt::MatchFlags idFilterMatchFlags); Tp::AccountPtr accountFilter() const; Q_SLOT void clearAccountFilter(); Q_SLOT void setAccountFilter(const Tp::AccountPtr &accountFilter); Q_SIGNAL void accountFilterChanged(const Tp::AccountPtr &accountFilter); QStringList tubesFilterStrings() const; Q_SLOT void clearTubesFilterStrings(); Q_SLOT void setTubesFilterStrings(const QStringList &tubesFilterStrings); Q_SIGNAL void tubesFilterStringsChanged(const QStringList &tubesFilterStrings); QString sortRoleString() const; Q_SLOT void setSortRoleString(const QString &role); protected: bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override; bool lessThan (const QModelIndex &left, const QModelIndex &right) const override; QModelIndexList match(const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags) const override; private: class Private; Private * const d; Q_PRIVATE_SLOT(d, void sourceModelParentIndexChanged(const QModelIndex &sourceIndex)) Q_PRIVATE_SLOT(d, void sourceModelIndexChanged(const QModelIndex &sourceIndex)) }; } //namespace #endif // CONTACTSFILTERMODEL_H diff --git a/KTp/Models/contacts-list-model.cpp b/KTp/Models/contacts-list-model.cpp index 06259fc..31c591a 100644 --- a/KTp/Models/contacts-list-model.cpp +++ b/KTp/Models/contacts-list-model.cpp @@ -1,249 +1,249 @@ /* * Copyright (C) 2012 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contacts-list-model.h" #include #include #include #include #include #include #include "debug.h" #include #include "contact.h" #include "presence.h" #include "types.h" class KTp::ContactsListModel::Private { public: Private(): initialized(false) { } QList contacts; KTp::GlobalContactManager *contactManager; bool initialized; }; KTp::ContactsListModel::ContactsListModel(QObject *parent) : QAbstractListModel(parent), d(new KTp::ContactsListModel::Private()) { - d->contactManager = 0; + d->contactManager = nullptr; } KTp::ContactsListModel::~ContactsListModel() { delete d; } void KTp::ContactsListModel::setAccountManager(const Tp::AccountManagerPtr &accountManager) { d->contactManager = new KTp::GlobalContactManager(accountManager, this); connect(d->contactManager, SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)), SLOT(onContactsChanged(Tp::Contacts,Tp::Contacts))); // If there are no enabled account or no account is online, emit the signal // directly, because onContactsChanged won't be called const QList accounts = accountManager->enabledAccounts()->accounts(); if (accounts.isEmpty()) { d->initialized = true; Q_EMIT modelInitialized(true); } else { Q_FOREACH (const Tp::AccountPtr &account, accounts) { if (account->isOnline()) { return; } } d->initialized = true; Q_EMIT modelInitialized(true); } } int KTp::ContactsListModel::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) { return d->contacts.size(); } else { return 0; } } QVariant KTp::ContactsListModel::data(const QModelIndex &index, int role) const { int row = index.row(); if (row >=0 && row < d->contacts.size()) { const KTp::ContactPtr contact = KTp::ContactPtr::qObjectCast(d->contacts[row]); Q_ASSERT_X(!contact.isNull(), "KTp::ContactListModel::data()", "Failed to cast Tp::ContactPtr to KTp::ContactPtr. Are you using KTp::ContactFactory?"); switch (role) { case KTp::RowTypeRole: return KTp::ContactRowType; case Qt::DisplayRole: return contact->alias(); case KTp::IdRole: return contact->id(); case KTp::ContactRole: return QVariant::fromValue(contact); case KTp::AccountRole: return QVariant::fromValue(d->contactManager->accountForContact(contact)); case KTp::ContactClientTypesRole: return contact->clientTypes(); case KTp::ContactAvatarPathRole: return contact->avatarData().fileName; case KTp::ContactAvatarPixmapRole: return contact->avatarPixmap(); case KTp::ContactGroupsRole: return contact->groups(); case KTp::ContactPresenceNameRole: return contact->presence().displayString(); case KTp::ContactPresenceMessageRole: return contact->presence().statusMessage(); case KTp::ContactPresenceTypeRole: return contact->presence().type(); case KTp::ContactPresenceIconRole: return contact->presence().iconName(); case KTp::ContactSubscriptionStateRole: return contact->subscriptionState(); case KTp::ContactPublishStateRole: return contact->publishState(); case KTp::ContactIsBlockedRole: return contact->isBlocked(); case KTp::ContactCanTextChatRole: return contact->textChatCapability(); case KTp::ContactCanFileTransferRole: return contact->fileTransferCapability(); case KTp::ContactCanAudioCallRole: return contact->audioCallCapability(); case KTp::ContactCanVideoCallRole: return contact->videoCallCapability(); case KTp::ContactTubesRole: return QStringList() << contact->streamTubeServicesCapability() << contact->dbusTubeServicesCapability(); default: break; } } return QVariant(); } void KTp::ContactsListModel::onContactsChanged(const Tp::Contacts &added, const Tp::Contacts &removed) { //add contacts. Q_FOREACH(const Tp::ContactPtr &contact_uncasted, added) { KTp::ContactPtr contact = KTp::ContactPtr::qObjectCast(contact_uncasted); connect(contact.data(), SIGNAL(aliasChanged(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(avatarTokenChanged(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)), SLOT(onChanged())); connect(contact.data(), SIGNAL(presenceChanged(Tp::Presence)), SLOT(onChanged())); connect(contact->manager()->connection()->selfContact().data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), SLOT(onChanged())); connect(contact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), SLOT(onChanged())); connect(contact.data(), SIGNAL(locationUpdated(Tp::LocationInfo)), SLOT(onChanged())); connect(contact.data(), SIGNAL(infoFieldsChanged(Tp::Contact::InfoFields)), SLOT(onChanged())); connect(contact.data(), SIGNAL(subscriptionStateChanged(Tp::Contact::PresenceState)), SLOT(onChanged())); connect(contact.data(), SIGNAL(publishStateChanged(Tp::Contact::PresenceState,QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(blockStatusChanged(bool)), SLOT(onChanged())); connect(contact.data(), SIGNAL(clientTypesChanged(QStringList)), SLOT(onChanged())); connect(contact.data(), SIGNAL(addedToGroup(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(removedFromGroup(QString)), SLOT(onChanged())); connect(contact.data(), SIGNAL(invalidated()), SLOT(onConnectionDropped())); } if (added.size() > 0) { beginInsertRows(QModelIndex(), d->contacts.size(), d->contacts.size() + added.size() -1); d->contacts.append(added.toList()); endInsertRows(); } //remove contacts Q_FOREACH(const Tp::ContactPtr &contact, removed) { int row = d->contacts.indexOf(contact); if (row >= 0) { //if contact found in list beginRemoveRows(QModelIndex(), row, row); d->contacts.removeOne(contact); endRemoveRows(); } } if (!d->initialized) { Q_EMIT modelInitialized(true); d->initialized = true; } } void KTp::ContactsListModel::onChanged() { KTp::ContactPtr contact(qobject_cast(sender())); int row = d->contacts.indexOf(contact); if (row > 0) { QModelIndex index = createIndex(row, 0); dataChanged(index, index); } } void KTp::ContactsListModel::onConnectionDropped() { KTp::ContactPtr contact(qobject_cast(sender())); onContactsChanged(Tp::Contacts(), Tp::Contacts() << contact); } diff --git a/KTp/Models/contacts-list-model.h b/KTp/Models/contacts-list-model.h index 2a3c662..2ffe9f1 100644 --- a/KTp/Models/contacts-list-model.h +++ b/KTp/Models/contacts-list-model.h @@ -1,59 +1,59 @@ /* * Copyright (C) 2012 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KTP_CONTACTS_LIST_MODEL_H #define KTP_CONTACTS_LIST_MODEL_H #include #include #include #include namespace KTp { class KTPMODELS_EXPORT ContactsListModel : public QAbstractListModel { Q_OBJECT public: - explicit ContactsListModel(QObject *parent = 0); + explicit ContactsListModel(QObject *parent = nullptr); ~ContactsListModel() override; void setAccountManager(const Tp::AccountManagerPtr &accountManager); int rowCount(const QModelIndex &parent) const override; QVariant data(const QModelIndex &index, int role) const override; Q_SIGNALS: void modelInitialized(bool success); private Q_SLOTS: void onContactsChanged(const Tp::Contacts &added, const Tp::Contacts &removed); void onChanged(); void onConnectionDropped(); private: Q_DISABLE_COPY(ContactsListModel) class Private; Private *d; }; } #endif // CONTACTSLISTMODEL_H diff --git a/KTp/Models/contacts-model.cpp b/KTp/Models/contacts-model.cpp index d5faed5..80279c5 100644 --- a/KTp/Models/contacts-model.cpp +++ b/KTp/Models/contacts-model.cpp @@ -1,236 +1,236 @@ /* * Model of all accounts with inbuilt grouping and filtering * * Copyright (C) 2013 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contacts-model.h" #include "contacts-list-model.h" #include "accounts-tree-proxy-model.h" #include "groups-tree-proxy-model.h" #include "text-channel-watcher-proxy-model.h" #include "core.h" #include #ifdef HAVE_KPEOPLE #include #include "kpeopletranslationproxy.h" #endif #include "debug.h" namespace KTp { class ContactsModel::Private { public: GroupMode groupMode; bool trackUnread; QPointer proxy; QAbstractItemModel *source; Tp::AccountManagerPtr accountManager; Tp::ClientRegistrarPtr clientRegistrar; Tp::SharedPtr channelWatcherProxy; }; } KTp::ContactsModel::ContactsModel(QObject *parent) : KTp::ContactsFilterModel(parent), d(new Private) { d->groupMode = NoGrouping; d->trackUnread = false; if (KTp::kpeopleEnabled()) { #ifdef HAVE_KPEOPLE qCDebug(KTP_MODELS) << "Built with kpeople support, using kpeople model"; KPeople::PersonsModel *personsModel = new KPeople::PersonsModel(this); connect(personsModel, SIGNAL(modelInitialized(bool)), this, SIGNAL(modelInitialized(bool))); d->source = new KPeopleTranslationProxy(this); qobject_cast(d->source)->setSourceModel(personsModel); #endif } else { qCDebug(KTP_MODELS) << "KPeople support not built-in, using normal model"; d->source = new KTp::ContactsListModel(this); connect(d->source, SIGNAL(modelInitialized(bool)), this, SIGNAL(modelInitialized(bool))); } } KTp::ContactsModel::~ContactsModel() { delete d; } void KTp::ContactsModel::setAccountManager(const Tp::AccountManagerPtr &accountManager) { d->accountManager = accountManager; updateGroupProxyModels(); //set the account manager after we've reloaded the groups so that we don't send a list to the view, only to replace it with a grouped tree if (qobject_cast(d->source)) { qobject_cast(d->source)->setAccountManager(accountManager); } } Tp::AccountManagerPtr KTp::ContactsModel::accountManager() const { return d->accountManager; } void KTp::ContactsModel::setGroupMode(KTp::ContactsModel::GroupMode mode) { if (mode == d->groupMode) { //if nothing has changed, do nothing. return; } d->groupMode = mode; updateGroupProxyModels(); Q_EMIT groupModeChanged(); } KTp::ContactsModel::GroupMode KTp::ContactsModel::groupMode() const { return d->groupMode; } void KTp::ContactsModel::setTrackUnreadMessages(bool trackUnread) { if (d->trackUnread == trackUnread) { return; } d->trackUnread = trackUnread; updateGroupProxyModels(); Q_EMIT trackUnreadMessagesChanged(); } bool KTp::ContactsModel::trackUnreadMessages() const { return d->trackUnread; } void KTp::ContactsModel::updateGroupProxyModels() { //reset the filter //trying to track current selections whilst updating proxy models can cause issues //debug versions of Qt will assert beginResetModel(); endResetModel(); //if there no account manager there's not a lot point doing anything if (!d->accountManager) { return; } //if needed set up the client registrar and observer proxy model if (d->trackUnread && d->clientRegistrar.isNull()) { //share the accountFactory and connectFactory etc. from the main application, but create a new channelFactory that fetches the message queue for text chats Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus()); channelFactory->addFeaturesForTextChats(Tp::Features() << Tp::Channel::FeatureCore << Tp::TextChannel::FeatureMessageQueue); d->clientRegistrar = Tp::ClientRegistrar::create(d->accountManager->accountFactory(), d->accountManager->connectionFactory(), channelFactory, d->accountManager->contactFactory()); d->channelWatcherProxy = Tp::SharedPtr(new TextChannelWatcherProxyModel()); d->channelWatcherProxy->setSourceModel(d->source); d->clientRegistrar->registerClient(Tp::AbstractClientPtr::dynamicCast(d->channelWatcherProxy), QLatin1String("ListWatcher")); } else if (!d->trackUnread) { //delete the client registrar d->clientRegistrar.reset(); d->channelWatcherProxy.reset(); } - QAbstractItemModel *modelToGroup = 0; + QAbstractItemModel *modelToGroup = nullptr; if (d->trackUnread) { modelToGroup = d->channelWatcherProxy.data(); } else { modelToGroup = d->source; } //delete any previous proxy if (d->proxy) { d->proxy->deleteLater(); } switch (d->groupMode) { case NoGrouping: //This is a workaround to a Qt assert which gets confused when we switch from a source model that was //part of the proxy chain, and is now used in the view directly // //do not disable until you have tested on Qt in debug mode - setSourceModel(0); + setSourceModel(nullptr); setSourceModel(modelToGroup); break; case AccountGrouping: d->proxy = new KTp::AccountsTreeProxyModel(modelToGroup, d->accountManager); setSourceModel(d->proxy); break; case GroupGrouping: d->proxy = new KTp::GroupsTreeProxyModel(modelToGroup); setSourceModel(d->proxy); break; } } QHash KTp::ContactsModel::roleNames() const { QHash roles = KTp::ContactsFilterModel::roleNames(); roles[KTp::RowTypeRole]= "type"; roles[KTp::IdRole]= "id"; roles[KTp::ContactRole]= "contact"; roles[KTp::AccountRole]= "account"; roles[KTp::ContactClientTypesRole]= "clientTypes"; roles[KTp::ContactAvatarPathRole]= "avatar"; roles[KTp::ContactAvatarPixmapRole]="avatarPixmap"; roles[KTp::ContactGroupsRole]= "groups"; roles[KTp::ContactPresenceNameRole]= "presenceName"; roles[KTp::ContactPresenceMessageRole]= "presenceMessage"; roles[KTp::ContactPresenceTypeRole]= "presenceType"; roles[KTp::ContactPresenceIconRole]= "presenceIcon"; roles[KTp::ContactSubscriptionStateRole]= "subscriptionState"; roles[KTp::ContactPublishStateRole]= "publishState"; roles[KTp::ContactIsBlockedRole]= "blocked"; roles[KTp::ContactHasTextChannelRole]= "hasTextChannel"; roles[KTp::ContactUnreadMessageCountRole]= "unreadMessageCount"; roles[KTp::ContactLastMessageRole]= "lastMessage"; roles[KTp::ContactLastMessageDirectionRole]= "lastMessageDirection"; roles[KTp::ContactCanTextChatRole]= "textChat"; roles[KTp::ContactCanFileTransferRole]= "fileTransfer"; roles[KTp::ContactCanAudioCallRole]= "audioCall"; roles[KTp::ContactCanVideoCallRole]= "videoCall"; roles[KTp::ContactTubesRole]= "tubes"; roles[KTp::PersonIdRole]= "personId"; return roles; } diff --git a/KTp/Models/contacts-model.h b/KTp/Models/contacts-model.h index e937709..d15f784 100644 --- a/KTp/Models/contacts-model.h +++ b/KTp/Models/contacts-model.h @@ -1,92 +1,92 @@ /* * Model of all accounts with inbuilt grouping and filtering * * Copyright (C) 2013 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KTP_CONTACTS_MODEL_H #define KTP_CONTACTS_MODEL_H #include #include #include namespace KTp { /** This class combines the list model and all the relevant filtering into a simple to use class In most cases you should use this as the entry point to the models in your application */ class KTPMODELS_EXPORT ContactsModel : public KTp::ContactsFilterModel { Q_OBJECT Q_PROPERTY(GroupMode groupMode READ groupMode WRITE setGroupMode NOTIFY groupModeChanged) Q_PROPERTY(bool trackUnreadMessages READ trackUnreadMessages WRITE setTrackUnreadMessages NOTIFY trackUnreadMessagesChanged) Q_PROPERTY(Tp::AccountManagerPtr accountManager READ accountManager WRITE setAccountManager) Q_ENUMS(GroupMode) public: enum GroupMode { /** Contacts are not grouped and are a simple flat list*/ NoGrouping, /** Contacts are grouped by their account using AccountsTreeProxyModel*/ AccountGrouping, /** Contacts are grouped by their group name using GroupsTreeProxyModel*/ GroupGrouping }; - ContactsModel(QObject *parent=0); + ContactsModel(QObject *parent=nullptr); ~ContactsModel() override; /** Sets the accounts manager to be used for the KTp::ContactListModel*/ void setAccountManager(const Tp::AccountManagerPtr &accountManager); /** Returns account manager currently used by the model */ Tp::AccountManagerPtr accountManager() const; /** Specify how the contacts should be grouped together*/ void setGroupMode(GroupMode mode); /** The currently specified grouping model*/ GroupMode groupMode() const; /** Specify whether to track unread messages or not. Note this adds additional overhead, so only use it if you're going to show the information * Default is False */ void setTrackUnreadMessages(bool trackUnread); bool trackUnreadMessages() const; QHash roleNames() const Q_DECL_OVERRIDE; Q_SIGNALS: void modelInitialized(bool success); void groupModeChanged(); void trackUnreadMessagesChanged(); private: class Private; Private *d; void updateGroupProxyModels(); }; } #endif // KTP_CONTACTS_MODEL_H diff --git a/KTp/Models/kpeopletranslationproxy.h b/KTp/Models/kpeopletranslationproxy.h index ce52cc2..92491dd 100644 --- a/KTp/Models/kpeopletranslationproxy.h +++ b/KTp/Models/kpeopletranslationproxy.h @@ -1,45 +1,45 @@ /* Copyright (C) 2013 Martin Klapetek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KTP_TRANSLATION_PROXY_H #define KTP_TRANSLATION_PROXY_H // #include #include #include class KTPMODELS_EXPORT KPeopleTranslationProxy : public QSortFilterProxyModel { Q_OBJECT public: - KPeopleTranslationProxy(QObject *parent = 0); + KPeopleTranslationProxy(QObject *parent = nullptr); ~KPeopleTranslationProxy() override; QVariant data(const QModelIndex &proxyIndex, int role = Qt::DisplayRole) const override; QVariant dataForKTpContact(const QString &accountPath, const QString &contactId, int role) const; bool filterAcceptsRow(int source_row, const QModelIndex & source_parent ) const override; private: QVariant translatePresence(const QVariant &presenceName) const; QPixmap contactPixmap(const QModelIndex &index) const; }; #endif // KTP_TRANSLATION_PROXY_H diff --git a/KTp/Models/presence-model.h b/KTp/Models/presence-model.h index a7578ce..cee090b 100644 --- a/KTp/Models/presence-model.h +++ b/KTp/Models/presence-model.h @@ -1,95 +1,95 @@ /* * Presence Model - A model of settable presences. * * Copyright (C) 2016 James D. Smith * Copyright (C) 2011 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef PRESENCEMODEL_H #define PRESENCEMODEL_H #include #include #include #include #include "ktpmodels_export.h" namespace KTp { class KTPMODELS_EXPORT PresenceModel : public QAbstractListModel { Q_OBJECT Q_PROPERTY(int count READ rowCount) public: - explicit PresenceModel(QObject *parent = 0); + explicit PresenceModel(QObject *parent = nullptr); ~PresenceModel() override; enum Roles { //Also supplies Qt::DisplayRole and Qt::DecorationRole PresenceRole = Qt::UserRole, IconNameRole }; /** Adds a custom presence to the model, writes it to the config file, and * propagates it to other models. * @return the newly added item */ QModelIndex addPresence(const KTp::Presence &presence); void removePresence(const KTp::Presence &presence); /** Load all presences from disk */ void loadPresences(); /** Write all presences to disk */ void syncCustomPresencesToDisk(); Q_SCRIPTABLE QVariant get(int row, const QByteArray& role) const; //protected: int rowCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QModelIndexList match(const QModelIndex &start, int role, const QVariant &value, int hits = 1, Qt::MatchFlags flags = Qt::MatchFlags(Qt::MatchStartsWith | Qt::MatchWrap)) const override; QHash roleNames() const override; public Q_SLOTS: /** Incoming changes from other models */ void propagationChange(const QVariantList modelChange); private: void modifyModel(const KTp::Presence &presence); void propagateChange(const KTp::Presence &presence); /** Loads standard presences (online, away etc) into the model */ void loadDefaultPresences(); /** Loads any user custom presences into the model */ void loadCustomPresences(); QList m_presences; //this is wrong, KConfigGroup is a sharedptr.. KConfigGroup m_presenceGroup; }; } #endif // PRESENCEMODEL_H diff --git a/KTp/Models/rooms-model.h b/KTp/Models/rooms-model.h index 6b4cab7..651db29 100644 --- a/KTp/Models/rooms-model.h +++ b/KTp/Models/rooms-model.h @@ -1,144 +1,144 @@ /* * Rooms Model - A model of chatrooms. * Copyright (C) 2012 Dominik Cermak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ROOMS_MODEL_H #define ROOMS_MODEL_H #include #include #include namespace KTp { class KTPMODELS_EXPORT RoomsModel : public QAbstractListModel { Q_OBJECT public: // TODO: find a suitable icon and add an invitation column enum Column { NameColumn=0, DescriptionColumn, MembersColumn, PasswordColumn, }; enum Roles { HandleNameRole = Qt::UserRole }; - explicit RoomsModel(QObject *parent = 0); + explicit RoomsModel(QObject *parent = nullptr); int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QVariant headerData(int section, Qt::Orientation orientation, int role) const override; /** * \brief Add new rooms to the list. * * \param newRoomList The list with the new rooms to add. */ void addRooms(const Tp::RoomInfoList newRoomList); /** * \brief Clear the room list. */ void clearRoomInfoList(); private: Tp::RoomInfoList m_roomInfoList; }; class KTPMODELS_EXPORT FavoriteRoomsModel : public QAbstractListModel { Q_OBJECT public: enum Column { BookmarkColumn = 0, HandleNameColumn, AccountIdentifierColumn }; enum Roles { HandleNameRole = Qt::UserRole, BookmarkRole, AccountRole, FavoriteRoomRole }; - explicit FavoriteRoomsModel(QObject *parent = 0); + explicit FavoriteRoomsModel(QObject *parent = nullptr); int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; bool setData(const QModelIndex &index, const QVariant &value, int role) override; Qt::ItemFlags flags(const QModelIndex &index) const override; /** * \brief Add new rooms to the list. * * \param newRoomList The list with the new rooms to add. */ void addRooms(const QList newRoomList); /** * \brief Add a new room to the list. * * \param room The room to add. */ void addRoom(const QVariantMap &room); /** * \brief Remove a room from the list. * * \param room The room to remove. */ void removeRoom(const QVariantMap &room); /** * \brief Remove all rooms from the list. */ void clearRooms(); /** * \brief Checks if it contains a room (identified by his handle-name). * * \param handle The handle to look for. * * \return True if it contains the room else false. */ bool containsRoom(const QString &handle, const QString &account) const; /** * \brief Returns the count of rooms for the specified account. * * \param account The account to return the count for. * * \return The count of rooms. */ int countForAccount(const QString &account) const; private: QList m_favoriteRoomsList; }; } // namespace KTp #endif // ROOMS_MODEL_H diff --git a/KTp/Models/text-channel-watcher-proxy-model.cpp b/KTp/Models/text-channel-watcher-proxy-model.cpp index 6e69c59..8803d7b 100644 --- a/KTp/Models/text-channel-watcher-proxy-model.cpp +++ b/KTp/Models/text-channel-watcher-proxy-model.cpp @@ -1,257 +1,257 @@ /* * Copyright (C) 2013 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "text-channel-watcher-proxy-model.h" #include #include #include #include #include #include #include #include inline Tp::ChannelClassSpecList channelClasses() { return Tp::ChannelClassSpecList() << Tp::ChannelClassSpec::textChat(); } class ChannelWatcher : public QObject, public Tp::RefCounted { Q_OBJECT public: - ChannelWatcher(const QPersistentModelIndex &index, const Tp::TextChannelPtr &channel, QObject *parent=0); + ChannelWatcher(const QPersistentModelIndex &index, const Tp::TextChannelPtr &channel, QObject *parent=nullptr); int unreadMessageCount() const; QString lastMessage() const; KTp::Message::MessageDirection lastMessageDirection() const; QPersistentModelIndex modelIndex() const; Q_SIGNALS: void messagesChanged(); void invalidated(); private Q_SLOTS: void onMessageReceived(const Tp::ReceivedMessage &message); void onMessageSent(const Tp::Message &message); private: QPersistentModelIndex m_index; Tp::TextChannelPtr m_channel; QString m_lastMessage; KTp::Message::MessageDirection m_lastMessageDirection; }; typedef Tp::SharedPtr ChannelWatcherPtr; ChannelWatcher::ChannelWatcher(const QPersistentModelIndex &index, const Tp::TextChannelPtr &channel, QObject *parent): QObject(parent), m_index(index), m_channel(channel), m_lastMessageDirection(KTp::Message::LocalToRemote) { connect(channel.data(), SIGNAL(pendingMessageRemoved(Tp::ReceivedMessage)), SIGNAL(messagesChanged())); connect(channel.data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)), SIGNAL(invalidated())); connect(channel.data(), SIGNAL(messageReceived(Tp::ReceivedMessage)), SLOT(onMessageReceived(Tp::ReceivedMessage))); connect(channel.data(), SIGNAL(messageSent(Tp::Message,Tp::MessageSendingFlags,QString)), SLOT(onMessageSent(Tp::Message))); //trigger an update to the contact straight away QTimer::singleShot(0, this, SIGNAL(messagesChanged())); } QPersistentModelIndex ChannelWatcher::modelIndex() const { return m_index; } int ChannelWatcher::unreadMessageCount() const { return m_channel->messageQueue().size(); } QString ChannelWatcher::lastMessage() const { return m_lastMessage; } KTp::Message::MessageDirection ChannelWatcher::lastMessageDirection() const { return m_lastMessageDirection; } void ChannelWatcher::onMessageReceived(const Tp::ReceivedMessage &message) { if (!message.isDeliveryReport()) { m_lastMessage = message.text(); m_lastMessageDirection = KTp::Message::RemoteToLocal; Q_EMIT messagesChanged(); } } void ChannelWatcher::onMessageSent(const Tp::Message &message) { m_lastMessage = message.text(); m_lastMessageDirection = KTp::Message::LocalToRemote; Q_EMIT messagesChanged(); } namespace KTp { class TextChannelWatcherProxyModel::Private { public: QHash currentChannels; }; } //namespace KTp::TextChannelWatcherProxyModel::TextChannelWatcherProxyModel(QObject *parent) : QIdentityProxyModel(parent), Tp::AbstractClientObserver(channelClasses(), true), d(new TextChannelWatcherProxyModel::Private) { } KTp::TextChannelWatcherProxyModel::~TextChannelWatcherProxyModel() { delete d; } void KTp::TextChannelWatcherProxyModel::observeChannels(const Tp::MethodInvocationContextPtr<> &context, const Tp::AccountPtr &account, const Tp::ConnectionPtr &connection, const QList &channels, const Tp::ChannelDispatchOperationPtr &dispatchOperation, const QList &requestsSatisfied, const Tp::AbstractClientObserver::ObserverInfo &observerInfo) { Q_UNUSED(context) Q_UNUSED(account) Q_UNUSED(connection) Q_UNUSED(dispatchOperation) Q_UNUSED(requestsSatisfied) Q_UNUSED(observerInfo) if (!sourceModel()) { return; } Q_FOREACH(const Tp::ChannelPtr & channel, channels) { Tp::TextChannelPtr textChannel = Tp::TextChannelPtr::dynamicCast(channel); if (textChannel) { KTp::ContactPtr targetContact = KTp::ContactPtr::qObjectCast(textChannel->targetContact()); //skip group chats and situations where we don't have a single contact to mark messages for if (targetContact.isNull()) { continue; } //if it's not in our source model, ignore the channel QModelIndexList matchedContacts = sourceModel()->match(QModelIndex(sourceModel()->index(0,0)), KTp::IdRole, QVariant::fromValue(targetContact->id())); if (matchedContacts.size() !=1) { continue; } QPersistentModelIndex contactIndex(matchedContacts[0]); ChannelWatcherPtr watcher = ChannelWatcherPtr(new ChannelWatcher(contactIndex, textChannel)); d->currentChannels[targetContact] = watcher; connect(watcher.data(), SIGNAL(messagesChanged()), SLOT(onChannelMessagesChanged())); } } } QVariant KTp::TextChannelWatcherProxyModel::data(const QModelIndex &proxyIndex, int role) const { // if we're processing a person and either of those two roles, // we propagate the data from sub contacts if (proxyIndex.model()->rowCount(proxyIndex) > 0 && (role == KTp::ContactHasTextChannelRole || role == KTp::ContactUnreadMessageCountRole)) { QVariant personData; for (int i = 0; i < proxyIndex.model()->rowCount(proxyIndex); i++) { QVariant data = proxyIndex.child(i, 0).data(role); if (!data.isNull()) { personData = data; break; } } return personData; } const QModelIndex sourceIndex = mapToSource(proxyIndex); if (role == KTp::ContactHasTextChannelRole) { KTp::ContactPtr contact = sourceIndex.data(KTp::ContactRole).value(); if (contact) { if (d->currentChannels.contains(contact)) { return true; } } return QVariant(); } if (role == KTp::ContactUnreadMessageCountRole) { KTp::ContactPtr contact = sourceIndex.data(KTp::ContactRole).value(); if (contact) { if (d->currentChannels.contains(contact)) { return d->currentChannels[contact]->unreadMessageCount(); } } return QVariant(); } if (role == KTp::ContactLastMessageRole) { KTp::ContactPtr contact = sourceIndex.data(KTp::ContactRole).value(); if (contact) { if (d->currentChannels.contains(contact)) { return d->currentChannels[contact]->lastMessage(); } } return QString(); } if (role == KTp::ContactLastMessageDirectionRole) { KTp::ContactPtr contact = sourceIndex.data(KTp::ContactRole).value(); if (contact) { if (d->currentChannels.contains(contact)) { return d->currentChannels[contact]->lastMessageDirection(); } } return KTp::Message::LocalToRemote; } return sourceIndex.data(role); } void KTp::TextChannelWatcherProxyModel::onChannelMessagesChanged() { ChannelWatcher* watcher = qobject_cast(sender()); Q_ASSERT(watcher); const QModelIndex &index = mapFromSource(watcher->modelIndex()); dataChanged(index, index); } void KTp::TextChannelWatcherProxyModel::onChannelInvalidated() { ChannelWatcher* watcher = qobject_cast(sender()); Q_ASSERT(watcher); const QModelIndex &index = mapFromSource(watcher->modelIndex()); const KTp::ContactPtr &contact = index.data(KTp::ContactRole).value(); d->currentChannels.remove(contact); dataChanged(index, index); } #include "text-channel-watcher-proxy-model.moc" #include "moc_text-channel-watcher-proxy-model.cpp" diff --git a/KTp/Models/text-channel-watcher-proxy-model.h b/KTp/Models/text-channel-watcher-proxy-model.h index f42638b..9bca8f7 100644 --- a/KTp/Models/text-channel-watcher-proxy-model.h +++ b/KTp/Models/text-channel-watcher-proxy-model.h @@ -1,61 +1,61 @@ /* * Copyright (C) 2013 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KTP_TEXT_CHANNEL_WATCHER_PROXY_MODEL_H #define KTP_TEXT_CHANNEL_WATCHER_PROXY_MODEL_H #include #include #include #include namespace KTp { /** This class proxies the ContactsListModel, adding a role for ongoing chats*/ class KTPMODELS_EXPORT TextChannelWatcherProxyModel : public QIdentityProxyModel, public Tp::AbstractClientObserver { Q_OBJECT public: - explicit TextChannelWatcherProxyModel(QObject *parent=0); + explicit TextChannelWatcherProxyModel(QObject *parent=nullptr); ~TextChannelWatcherProxyModel() override; void observeChannels(const Tp::MethodInvocationContextPtr<> &context, const Tp::AccountPtr &account, const Tp::ConnectionPtr &connection, const QList &channels, const Tp::ChannelDispatchOperationPtr &dispatchOperation, const QList &requestsSatisfied, const Tp::AbstractClientObserver::ObserverInfo &observerInfo) override; QVariant data(const QModelIndex &proxyIndex, int role) const override; private Q_SLOTS: void onChannelMessagesChanged(); void onChannelInvalidated(); private: class Private; Private *d; }; } #endif // KTP_TEXT_CHANNEL_WATCHER_PROXY_MODEL_H diff --git a/KTp/OTR/channel-adapter.cpp b/KTp/OTR/channel-adapter.cpp index 24bd1eb..c45a4cc 100644 --- a/KTp/OTR/channel-adapter.cpp +++ b/KTp/OTR/channel-adapter.cpp @@ -1,445 +1,445 @@ /* Copyright (C) 2014 Marcin Ziemiński This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "channel-adapter.h" #include "channel-proxy-interface.h" #include "utils.h" #include "constants.h" #include #include #include #include #include typedef QSharedPointer OTRProxyPtr; static int getId(const Tp::ReceivedMessage &recvMes) { - return recvMes.header()[QLatin1String("pending-message-id")].variant().toUInt(NULL); + return recvMes.header()[QLatin1String("pending-message-id")].variant().toUInt(nullptr); } class OTRMessage : public Tp::ReceivedMessage { public: OTRMessage(const Tp::ReceivedMessage &recMes) : Tp::ReceivedMessage(recMes) { } OTRMessage(const Tp::MessagePartList &message, const Tp::TextChannelPtr channel) : Tp::ReceivedMessage(message, channel) { setSender(channel->targetContact()); } bool hasId() const { return header().contains(QLatin1String("pending-message-id")); } int getId() const { return ::getId(*this); } void setId(int id) { header()[QLatin1String("pending-message-id")] = QDBusVariant(id); } void setSender(const Tp::ContactPtr &contact) { ReceivedMessage::setSender(contact); } }; namespace KTp { struct ChannelAdapter::Private { Private() : otrConnected(false), trustLevel(KTp::OTRTrustLevelNotPrivate) { } Tp::TextChannelPtr textChannel; OTRProxyPtr otrProxy; bool otrConnected; KTp::OTRTrustLevel trustLevel; QString remoteFp; QMap messages; QMap otrEvents; }; ChannelAdapter::ChannelAdapter(const Tp::TextChannelPtr &textChannel, QObject *parent) : QObject(parent), d(new Private()) { setChannel(textChannel); } ChannelAdapter::~ChannelAdapter() { delete d; } bool ChannelAdapter::isValid() const { return d->textChannel->isValid(); } void ChannelAdapter::setChannel(const Tp::TextChannelPtr &textChannel) { d->textChannel = textChannel; QDBusConnection dbusConnection = textChannel->dbusConnection(); if(textChannel->targetHandleType() != Tp::HandleTypeContact || !dbusConnection.interface()->isServiceRegistered(KTP_PROXY_BUS_NAME)) { setupTextChannel(); return; } QString otrProxyPath = KTp::Utils::getOtrProxyObjectPathFor(textChannel); d->otrProxy = OTRProxyPtr(new KTp::Client::ChannelProxyInterfaceOTRInterface(KTP_PROXY_BUS_NAME, otrProxyPath, this)); if(!d->otrProxy->isValid()) { qCDebug(KTP_OTR) << "No OTR proxy available for channel: " << textChannel->objectPath(); setupTextChannel(); return; } qCDebug(KTP_OTR) << "Connecting to the OTR proxy: " << d->otrProxy->path(); QDBusPendingReply<> connectResult = d->otrProxy->ConnectProxy(); connectResult.waitForFinished(); if(connectResult.isValid()) { setupOTRChannel(); } else { qCWarning(KTP_OTR) << "Could not connect to the proxy" << connectResult.error().message(); setupTextChannel(); } } Tp::TextChannelPtr ChannelAdapter::textChannel() { return d->textChannel; } void ChannelAdapter::setupTextChannel() { connect(d->textChannel.data(), SIGNAL(messageReceived(Tp::ReceivedMessage)), SIGNAL(messageReceived(Tp::ReceivedMessage))); connect(d->textChannel.data(), SIGNAL(pendingMessageRemoved(Tp::ReceivedMessage)), SIGNAL(pendingMessageRemoved(Tp::ReceivedMessage))); connect(d->textChannel.data(), SIGNAL(messageSent(Tp::Message,Tp::MessageSendingFlags,QString)), SIGNAL(messageSent(Tp::Message,Tp::MessageSendingFlags,QString))); } void ChannelAdapter::setupOTRChannel() { d->otrConnected = true; d->trustLevel = KTp::OTRTrustLevelNotPrivate; connect(d->otrProxy.data(), SIGNAL(SessionRefreshed()), SIGNAL(sessionRefreshed())); connect(d->otrProxy.data(), SIGNAL(MessageReceived(const Tp::MessagePartList&)), SLOT(onMessageReceived(const Tp::MessagePartList&))); connect(d->otrProxy.data(), SIGNAL(PendingMessagesRemoved(const Tp::UIntList&)), SLOT(onPendingMessagesRemoved(const Tp::UIntList&))); connect(d->otrProxy.data(), SIGNAL(MessageSent(const Tp::MessagePartList&, uint, const QString&)), SLOT(onMessageSent(const Tp::MessagePartList&, uint, const QString&))); connect(d->otrProxy.data(), SIGNAL(TrustLevelChanged(uint)), SLOT(onTrustLevelChanged(uint))); // smp protocol connect(d->otrProxy.data(), SIGNAL(PeerAuthenticationRequested(const QString&)), SLOT(onPeerAuthenticationRequested(const QString&))); connect(d->otrProxy.data(), SIGNAL(PeerAuthenticationConcluded(bool)), SIGNAL(peerAuthenticationConcluded(bool))); connect(d->otrProxy.data(), SIGNAL(PeerAuthenticationInProgress()), SIGNAL(peerAuthenticationInProgress())); connect(d->otrProxy.data(), SIGNAL(PeerAuthenticationAborted()), SIGNAL(peerAuthenticationAborted())); connect(d->otrProxy.data(), SIGNAL(PeerAuthenticationError()), SIGNAL(peerAuthenticationError())); connect(d->otrProxy.data(), SIGNAL(PeerAuthenticationCheated()), SIGNAL(peerAuthenticationCheated())); // initialize message queue; connect(d->otrProxy->requestPropertyPendingMessages(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onPendingMessagesPropertyGet(Tp::PendingOperation*))); // initialize trust level property connect(d->otrProxy->requestPropertyTrustLevel(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onTrustLevelPropertyGet(Tp::PendingOperation*))); // initialize remote fingerprint property connect(d->otrProxy->requestPropertyRemoteFingerprint(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onRemoteFingerprintPropertyGet(Tp::PendingOperation*))); } KTp::OTRTrustLevel ChannelAdapter::otrTrustLevel() const { return d->trustLevel; } void ChannelAdapter::onTrustLevelPropertyGet(Tp::PendingOperation *op) { if(op->isError()) { qCWarning(KTP_OTR) << "Could not get property: TrustLevel"; return; } // we must have received trust level changed signal before if(d->trustLevel != KTp::OTRTrustLevelNotPrivate) { return; } Tp::PendingVariant *pv = dynamic_cast(op); - d->trustLevel = static_cast(pv->result().toUInt(NULL)); + d->trustLevel = static_cast(pv->result().toUInt(nullptr)); Q_EMIT otrTrustLevelChanged(d->trustLevel, KTp::OTRTrustLevelNotPrivate); } bool ChannelAdapter::isOTRsuppored() const { return d->otrConnected; } void ChannelAdapter::initializeOTR() { qCDebug(KTP_OTR) << "Initializing OTR session"; d->otrProxy->Initialize(); } void ChannelAdapter::stopOTR() { d->otrProxy->Stop(); } QString ChannelAdapter::remoteFingerprint() const { return d->remoteFp; } QDBusPendingReply<> ChannelAdapter::trustFingerprint(const QString &fingerprint, bool trust) { return d->otrProxy->TrustFingerprint(fingerprint, trust); } void ChannelAdapter::acknowledge(const QList &messages) { if(messages.isEmpty()) { return; } if(isOTRsuppored()) { QList toAck; QList eventsToRemove; Q_FOREACH(const Tp::ReceivedMessage &mes, messages) { if(KTp::Utils::isOtrEvent(mes)) { d->otrEvents.remove(getId(mes)); eventsToRemove << mes; } else { toAck << mes; } } d->otrProxy->AcknowledgePendingMessages(KTp::Utils::getPendingMessagesIDs(toAck)); Q_FOREACH(const Tp::ReceivedMessage &mes, eventsToRemove) { Q_EMIT pendingMessageRemoved(mes); } } else { d->textChannel->acknowledge(messages); } } void ChannelAdapter::send(const QString& text, Tp::ChannelTextMessageType type, Tp::MessageSendingFlags flags) { if(isOTRsuppored()) { Tp::MessagePartList parts; parts << Tp::MessagePart() << Tp::MessagePart(); parts[0].insert(QLatin1String("message-type"), QDBusVariant(type)); parts[1].insert(QLatin1String("content-type"), QDBusVariant(QLatin1String("text/plain"))); parts[1].insert(QLatin1String("content"), QDBusVariant(text)); d->otrProxy->SendMessage(parts, (uint) flags); } else { d->textChannel->send(text, type, flags); } } bool ChannelAdapter::supportsMessageType(Tp::ChannelTextMessageType messageType) const { return d->textChannel->supportsMessageType(messageType); } QList ChannelAdapter::supportedMessageTypes() const { return d->textChannel->supportedMessageTypes(); } QStringList ChannelAdapter::supportedContentTypes() const { return d->textChannel->supportedContentTypes(); } Tp::MessagePartSupportFlags ChannelAdapter::messagePartSupport() const { return d->textChannel->messagePartSupport(); } Tp::DeliveryReportingSupportFlags ChannelAdapter::deliveryReportingSupport() const { return d->textChannel->deliveryReportingSupport(); } QList ChannelAdapter::messageQueue() const { if(isOTRsuppored()) { QList messages; Q_FOREACH(const Tp::ReceivedMessage &m, d->messages) { messages << m; } Q_FOREACH(const Tp::ReceivedMessage &m, d->otrEvents) { messages << m; } return messages; } else { return d->textChannel->messageQueue(); } } void ChannelAdapter::onMessageReceived(const Tp::MessagePartList &message) { OTRMessage recvMes(message, d->textChannel); if(recvMes.hasId()) { const int id = recvMes.getId(); if(!d->messages.contains(id)) { d->messages.insert(id, recvMes); Q_EMIT messageReceived(recvMes); } else { qCWarning(KTP_OTR) << "Message already in the queue. Id: " << id; } } else if (KTp::Utils::isOtrEvent(recvMes)) { const int id = d->otrEvents.size(); recvMes.setId(d->otrEvents.size()); d->otrEvents.insert(id, recvMes); Q_EMIT messageReceived(recvMes); } else { qCWarning(KTP_OTR) << "Message has not id and is not an OTR event either"; } } void ChannelAdapter::onPendingMessagesPropertyGet(Tp::PendingOperation *op) { Tp::PendingVariant *variant = dynamic_cast(op); if(!variant->isError()) { QDBusArgument dbusArgument = variant->result().value(); Tp::MessagePartListList pendingMessages; dbusArgument >> pendingMessages; Q_FOREACH(const Tp::MessagePartList &message, pendingMessages) { onMessageReceived(message); } } else { qCWarning(KTP_OTR) << "Could not initialize message queue: " << variant->errorName() << " - " << variant->errorMessage(); } } void ChannelAdapter::onRemoteFingerprintPropertyGet(Tp::PendingOperation *op) { Tp::PendingVariant *variant = dynamic_cast(op); if(!variant->isError()) { d->remoteFp = variant->result().toString(); } else { qCWarning(KTP_OTR) << "Could not get remote fingerprint: " << variant->errorName() << " - " << variant->errorMessage(); } } void ChannelAdapter::onPendingMessagesRemoved(const Tp::UIntList &messageIDs) { Q_FOREACH(uint id, messageIDs) { const QMap::Iterator mIt = d->messages.find(id); if(mIt != d->messages.end()) { OTRMessage message = *mIt; d->messages.erase(mIt); Q_EMIT pendingMessageRemoved(message); } else { qCWarning(KTP_OTR) << "No message to remove with id: " << id; } } } void ChannelAdapter::onMessageSent(const Tp::MessagePartList &content, uint flags, const QString &messageToken) { OTRMessage message(content, d->textChannel); Q_EMIT messageSent(message, Tp::MessageSendingFlags(flags), messageToken); } void ChannelAdapter::onTrustLevelChanged(uint trustLevel) { KTp::OTRTrustLevel oldLevel = d->trustLevel; d->trustLevel = static_cast(trustLevel); // get remote's fingerprint if(oldLevel == KTp::OTRTrustLevelNotPrivate) { connect(d->otrProxy->requestPropertyRemoteFingerprint(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onRemoteFingerprintPropertyGet(Tp::PendingOperation*))); } // it may be a new session and the fingerprint has to be updated if(d->trustLevel == KTp::OTRTrustLevelPrivate || d->trustLevel == KTp::OTRTrustLevelUnverified) { connect(d->otrProxy->requestPropertyRemoteFingerprint(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onRemoteFingerprintPropertyGet(Tp::PendingOperation*))); } Q_EMIT otrTrustLevelChanged(d->trustLevel, oldLevel); } void ChannelAdapter::onPeerAuthenticationRequested(const QString &question) { if(question.isEmpty()) { Q_EMIT peerAuthenticationRequestedSS(); } else { Q_EMIT peerAuthenticationRequestedQA(question); } } void ChannelAdapter::startPeerAuthenticationQA(const QString &question, const QString &answer) { d->otrProxy->StartPeerAuthentication(question, answer); } void ChannelAdapter::startPeerAuthenticationSS(const QString &secret) { startPeerAuthenticationQA(QLatin1String(""), secret); } void ChannelAdapter::respondPeerAuthentication(const QString &secret) { d->otrProxy->RespondPeerAuthentication(secret); } void ChannelAdapter::abortPeerAuthentication() { d->otrProxy->AbortPeerAuthentication(); } } /* namespace KTp */ diff --git a/KTp/OTR/channel-adapter.h b/KTp/OTR/channel-adapter.h index 4c01ed0..cc5a7b3 100644 --- a/KTp/OTR/channel-adapter.h +++ b/KTp/OTR/channel-adapter.h @@ -1,116 +1,116 @@ /* Copyright (C) 2014 Marcin Ziemiński This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #ifndef OTR_CHANNEL_ADAPTER_HEADER #define OTR_CHANNEL_ADAPTER_HEADER #include "types.h" #include "constants.h" #include "ktpotr_export.h" #include #include #include #include #include namespace KTp { class KTPOTR_EXPORT ChannelAdapter : public QObject, public Tp::RefCounted { Q_OBJECT public: - ChannelAdapter(const Tp::TextChannelPtr &textChannel, QObject *parent = 0); + ChannelAdapter(const Tp::TextChannelPtr &textChannel, QObject *parent = nullptr); ~ChannelAdapter() override; Tp::TextChannelPtr textChannel(); KTp::OTRTrustLevel otrTrustLevel() const; bool isOTRsuppored() const; QString remoteFingerprint() const; QDBusPendingReply<> trustFingerprint(const QString &fingerprint, bool trust); bool isValid() const; void initializeOTR(); void stopOTR(); /** question answer peer authentication */ void startPeerAuthenticationQA(const QString &question, const QString &answer); /** shared secret peer authentication*/ void startPeerAuthenticationSS(const QString &secret); void respondPeerAuthentication(const QString &secret); void abortPeerAuthentication(); void acknowledge(const QList &messages); void send(const QString& text, Tp::ChannelTextMessageType type = Tp::ChannelTextMessageTypeNormal, - Tp::MessageSendingFlags flags = 0); + Tp::MessageSendingFlags flags = nullptr); bool supportsMessageType(Tp::ChannelTextMessageType messageType) const; QList supportedMessageTypes() const; QStringList supportedContentTypes() const; Tp::MessagePartSupportFlags messagePartSupport() const; Tp::DeliveryReportingSupportFlags deliveryReportingSupport() const; QList messageQueue() const; private: void setChannel(const Tp::TextChannelPtr &textChannel); void setupOTRChannel(); void setupTextChannel(); private Q_SLOTS: void onTrustLevelPropertyGet(Tp::PendingOperation *op); void onPendingMessagesPropertyGet(Tp::PendingOperation *op); void onRemoteFingerprintPropertyGet(Tp::PendingOperation *op); void onMessageReceived(const Tp::MessagePartList &message); void onPendingMessagesRemoved(const Tp::UIntList &messageIDs); void onMessageSent(const Tp::MessagePartList &content, uint flags, const QString &messageToken); void onTrustLevelChanged(uint trustLevel); void onPeerAuthenticationRequested(const QString &question); Q_SIGNALS: void messageSent(const Tp::Message &message, Tp::MessageSendingFlags flags, const QString &sentMessageToken); void messageReceived(const Tp::ReceivedMessage &message); void pendingMessageRemoved( const Tp::ReceivedMessage &message); void otrTrustLevelChanged(KTp::OTRTrustLevel newStatus, KTp::OTRTrustLevel oldStatus); void sessionRefreshed(); void peerAuthenticationRequestedQA(const QString &question); void peerAuthenticationRequestedSS(); void peerAuthenticationConcluded(bool authenticated); void peerAuthenticationInProgress(); void peerAuthenticationAborted(); void peerAuthenticationError(); void peerAuthenticationCheated(); private: struct Private; friend struct Private; Private *d; }; typedef Tp::SharedPtr ChannelAdapterPtr; } /* namespace KTp */ #endif diff --git a/KTp/OTR/channel-proxy-interface.cpp b/KTp/OTR/channel-proxy-interface.cpp index 61da714..0571537 100644 --- a/KTp/OTR/channel-proxy-interface.cpp +++ b/KTp/OTR/channel-proxy-interface.cpp @@ -1,52 +1,52 @@ #define IN_TP_QT_HEADER #include "channel-proxy-interface.h" namespace KTp { namespace Client { ChannelProxyInterfaceOTRInterface::ChannelProxyInterfaceOTRInterface(const QString& busName, const QString& objectPath, QObject *parent) : Tp::AbstractInterface(busName, objectPath, staticInterfaceName(), QDBusConnection::sessionBus(), parent) { } ChannelProxyInterfaceOTRInterface::ChannelProxyInterfaceOTRInterface(const QDBusConnection& connection, const QString& busName, const QString& objectPath, QObject *parent) : Tp::AbstractInterface(busName, objectPath, staticInterfaceName(), connection, parent) { } ChannelProxyInterfaceOTRInterface::ChannelProxyInterfaceOTRInterface(Tp::DBusProxy *proxy) : Tp::AbstractInterface(proxy, staticInterfaceName()) { } ChannelProxyInterfaceOTRInterface::ChannelProxyInterfaceOTRInterface(const Tp::AbstractInterface& mainInterface) : Tp::AbstractInterface(mainInterface.service(), mainInterface.path(), staticInterfaceName(), mainInterface.connection(), mainInterface.parent()) { } ChannelProxyInterfaceOTRInterface::ChannelProxyInterfaceOTRInterface(const Tp::AbstractInterface& mainInterface, QObject *parent) : Tp::AbstractInterface(mainInterface.service(), mainInterface.path(), staticInterfaceName(), mainInterface.connection(), parent) { } void ChannelProxyInterfaceOTRInterface::invalidate(Tp::DBusProxy *proxy, const QString &error, const QString &message) { - disconnect(this, SIGNAL(MessageSent(const Tp::MessagePartList&, uint, const QString&)), NULL, NULL); - disconnect(this, SIGNAL(MessageReceived(const Tp::MessagePartList&)), NULL, NULL); - disconnect(this, SIGNAL(PendingMessagesRemoved(const Tp::UIntList&)), NULL, NULL); - disconnect(this, SIGNAL(PeerAuthenticationRequested(const QString&)), NULL, NULL); - disconnect(this, SIGNAL(PeerAuthenticationConcluded(bool)), NULL, NULL); - disconnect(this, SIGNAL(PeerAuthenticationInProgress()), NULL, NULL); - disconnect(this, SIGNAL(PeerAuthenticationAborted()), NULL, NULL); - disconnect(this, SIGNAL(PeerAuthenticationError()), NULL, NULL); - disconnect(this, SIGNAL(PeerAuthenticationCheated()), NULL, NULL); - disconnect(this, SIGNAL(SessionRefreshed()), NULL, NULL); - disconnect(this, SIGNAL(TrustLevelChanged(uint)), NULL, NULL); + disconnect(this, SIGNAL(MessageSent(const Tp::MessagePartList&, uint, const QString&)), nullptr, nullptr); + disconnect(this, SIGNAL(MessageReceived(const Tp::MessagePartList&)), nullptr, nullptr); + disconnect(this, SIGNAL(PendingMessagesRemoved(const Tp::UIntList&)), nullptr, nullptr); + disconnect(this, SIGNAL(PeerAuthenticationRequested(const QString&)), nullptr, nullptr); + disconnect(this, SIGNAL(PeerAuthenticationConcluded(bool)), nullptr, nullptr); + disconnect(this, SIGNAL(PeerAuthenticationInProgress()), nullptr, nullptr); + disconnect(this, SIGNAL(PeerAuthenticationAborted()), nullptr, nullptr); + disconnect(this, SIGNAL(PeerAuthenticationError()), nullptr, nullptr); + disconnect(this, SIGNAL(PeerAuthenticationCheated()), nullptr, nullptr); + disconnect(this, SIGNAL(SessionRefreshed()), nullptr, nullptr); + disconnect(this, SIGNAL(TrustLevelChanged(uint)), nullptr, nullptr); Tp::AbstractInterface::invalidate(proxy, error, message); } } } diff --git a/KTp/OTR/channel-proxy-interface.h b/KTp/OTR/channel-proxy-interface.h index 15d863e..abf5efb 100644 --- a/KTp/OTR/channel-proxy-interface.h +++ b/KTp/OTR/channel-proxy-interface.h @@ -1,691 +1,691 @@ /* * This file contains D-Bus client proxy classes generated by qt-client-gen.py. * * This file can be distributed under the same terms as the specification from * which it was generated. */ #ifndef OTR_CHANNEL_PROXY_HEADER #define OTR_CHANNEL_PROXY_HEADER #include "ktpotr_export.h" #include #include #include #include #include #include #include #include #include namespace Tp { class PendingVariant; class PendingOperation; } namespace KTp { namespace Client { /** * \class ChannelProxyInterfaceOTRInterface * \headerfile TelepathyQt/channel-proxy.h * \ingroup clientchannelproxy * * Proxy class providing a 1:1 mapping of the D-Bus interface "org.kde.TelepathyProxy.ChannelProxy.Interface.OTR". */ class KTPOTR_EXPORT ChannelProxyInterfaceOTRInterface : public Tp::AbstractInterface { Q_OBJECT public: /** * Returns the name of the interface "org.kde.TelepathyProxy.ChannelProxy.Interface.OTR", which this class * represents. * * \return The D-Bus interface name. */ static inline QLatin1String staticInterfaceName() { return QLatin1String("org.kde.TelepathyProxy.ChannelProxy.Interface.OTR"); } /** * Creates a ChannelProxyInterfaceOTRInterface associated with the given object on the session bus. * * \param busName Name of the service the object is on. * \param objectPath Path to the object on the service. * \param parent Passed to the parent class constructor. */ ChannelProxyInterfaceOTRInterface( const QString& busName, const QString& objectPath, - QObject* parent = 0 + QObject* parent = nullptr ); /** * Creates a ChannelProxyInterfaceOTRInterface associated with the given object on the given bus. * * \param connection The bus via which the object can be reached. * \param busName Name of the service the object is on. * \param objectPath Path to the object on the service. * \param parent Passed to the parent class constructor. */ ChannelProxyInterfaceOTRInterface( const QDBusConnection& connection, const QString& busName, const QString& objectPath, - QObject* parent = 0 + QObject* parent = nullptr ); /** * Creates a ChannelProxyInterfaceOTRInterface associated with the same object as the given proxy. * * \param proxy The proxy to use. It will also be the QObject::parent() * for this object. */ ChannelProxyInterfaceOTRInterface(Tp::DBusProxy *proxy); /** * Creates a ChannelProxyInterfaceOTRInterface associated with the same object as the given proxy. * Additionally, the created proxy will have the same parent as the given * proxy. * * \param mainInterface The proxy to use. */ explicit ChannelProxyInterfaceOTRInterface(const Tp::AbstractInterface& mainInterface); /** * Creates a ChannelProxyInterfaceOTRInterface associated with the same object as the given proxy. * However, a different parent object can be specified. * * \param mainInterface The proxy to use. * \param parent Passed to the parent class constructor. */ ChannelProxyInterfaceOTRInterface(const Tp::AbstractInterface& mainInterface, QObject* parent); /** * Asynchronous getter for the remote object property \c WrappedChannel of type \c QDBusObjectPath. * * * \htmlonly *

Object path of the channel this proxy is created for.

* \endhtmlonly * * \return A pending variant which will emit finished when the property has been * retrieved. */ inline Tp::PendingVariant *requestPropertyWrappedChannel() const { return internalRequestProperty(QLatin1String("WrappedChannel")); } /** * Asynchronous getter for the remote object property \c Connected of type \c bool. * * * \htmlonly *

TRUE if the proxy is connected

* \endhtmlonly * * \return A pending variant which will emit finished when the property has been * retrieved. */ inline Tp::PendingVariant *requestPropertyConnected() const { return internalRequestProperty(QLatin1String("Connected")); } /** * Asynchronous getter for the remote object property \c PendingMessages of type \c Tp::MessagePartListList. * * * \htmlonly *

* The same as: * \endhtmlonly ChannelInterfaceMessagesInterface \htmlonly *

* \endhtmlonly * * \return A pending variant which will emit finished when the property has been * retrieved. */ inline Tp::PendingVariant *requestPropertyPendingMessages() const { return internalRequestProperty(QLatin1String("PendingMessages")); } /** * Asynchronous getter for the remote object property \c TrustLevel of type \c uint. * * * \htmlonly *

The current trust level of this channel: * 0=TRUST_NOT_PRIVATE, 1=TRUST_UNVERIFIED, 2=TRUST_PRIVATE, * 3=TRUST_FINISHED

*

Clients MUST listen to PropertiesChanged to update UI when trust * level changes.

* \endhtmlonly * * \return A pending variant which will emit finished when the property has been * retrieved. */ inline Tp::PendingVariant *requestPropertyTrustLevel() const { return internalRequestProperty(QLatin1String("TrustLevel")); } /** * Asynchronous getter for the remote object property \c LocalFingerprint of type \c QString. * * * \htmlonly *

User's current fingerprint. The first element is a human readable * fingerprint that can be displayed to the user so he can communicate it * to the other end by other means so he can trust it. The 2nd element is * the fingerprint raw data.

* \endhtmlonly * * \return A pending variant which will emit finished when the property has been * retrieved. */ inline Tp::PendingVariant *requestPropertyLocalFingerprint() const { return internalRequestProperty(QLatin1String("LocalFingerprint")); } /** * Asynchronous getter for the remote object property \c RemoteFingerprint of type \c QString. * * * \htmlonly *

The current fingerprint of the remote contact. Should be displayed * to the user to update its trust level. It is shown in human readable format i.e. * :e '12345678 12345678 12345678 12345678 12345678'.

* \endhtmlonly * * \return A pending variant which will emit finished when the property has been * retrieved. */ inline Tp::PendingVariant *requestPropertyRemoteFingerprint() const { return internalRequestProperty(QLatin1String("RemoteFingerprint")); } /** * Request all of the DBus properties on the interface. * * \return A pending variant map which will emit finished when the properties have * been retrieved. */ Tp::PendingVariantMap *requestAllProperties() const { return internalRequestAllProperties(); } public Q_SLOTS: /** * Begins a call to the D-Bus method \c ConnectProxy on the remote object. * * Connect to the otr proxy. From now on all data which is modified by it * should be acquired from the proxy, not from the underlying channel. * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply<> ConnectProxy(int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply<>(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("ConnectProxy")); return this->connection().asyncCall(callMessage, timeout); } /** * Begins a call to the D-Bus method \c DisconnectProxy on the remote object. * * Turns off proxy if one is connected. * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply<> DisconnectProxy(int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply<>(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("DisconnectProxy")); return this->connection().asyncCall(callMessage, timeout); } /** * Begins a call to the D-Bus method \c SendMessage on the remote object. * * \htmlonly *

* The same as: * \endhtmlonly org.freedesktop.Telepathy.Channel.Interface.Messages.Sent \htmlonly *

* \endhtmlonly * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply SendMessage(const Tp::MessagePartList& message, uint flags, int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("SendMessage")); callMessage << QVariant::fromValue(message) << QVariant::fromValue(flags); return this->connection().asyncCall(callMessage, timeout); } /** * Begins a call to the D-Bus method \c AcknowledgePendingMessages on the remote object. * * \htmlonly *

* The same as: * \endhtmlonly ChannelTypeTextInterface \htmlonly *

* \endhtmlonly * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply<> AcknowledgePendingMessages(const Tp::UIntList& IDs, int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply<>(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("AcknowledgePendingMessages")); callMessage << QVariant::fromValue(IDs); return this->connection().asyncCall(callMessage, timeout); } /** * Begins a call to the D-Bus method \c Initialize on the remote object. * * Start an OTR session for this channel if the remote end supports it has * well. * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply<> Initialize(int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply<>(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("Initialize")); return this->connection().asyncCall(callMessage, timeout); } /** * Begins a call to the D-Bus method \c Stop on the remote object. * * Stops the OTR session. * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply<> Stop(int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply<>(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("Stop")); return this->connection().asyncCall(callMessage, timeout); } /** * Begins a call to the D-Bus method \c TrustFingerprint on the remote object. * * Set whether or not the user trusts the given fingerprint. It has to be * the fingerprint the remote contact is currently using. * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * * \param fingerprint * * The fingerprint in format: '12345678 12345678 12345678 * 12345678 12345678' * * \param trust * * %TRUE if trusted, %FALSE otherwise. * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply<> TrustFingerprint(const QString& fingerprint, bool trust, int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply<>(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("TrustFingerprint")); callMessage << QVariant::fromValue(fingerprint) << QVariant::fromValue(trust); return this->connection().asyncCall(callMessage, timeout); } /** * Begins a call to the D-Bus method \c StartPeerAuthentication on the remote object. * * \htmlonly *

This method starts peer authentication using the Socialist * Millionaire protocol.

* \endhtmlonly * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * * \param question * * The question to be used for peer authentication. It is used by the * remote peer as a hint for the shared secret. If an empty string is * passed only the shared secret will be used on the peer * authentication process. * * \param secret * * The shared secret to be used for peer authentication. If the * Question parameter is not empty, this should be the answer to it. * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply<> StartPeerAuthentication(const QString& question, const QString& secret, int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply<>(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("StartPeerAuthentication")); callMessage << QVariant::fromValue(question) << QVariant::fromValue(secret); return this->connection().asyncCall(callMessage, timeout); } /** * Begins a call to the D-Bus method \c RespondPeerAuthentication on the remote object. * * \htmlonly *

This method continues the peer authentication started by the remote * peer.

* \endhtmlonly * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * * \param secret * * The shared secret to be used for peer authentication. * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply<> RespondPeerAuthentication(const QString& secret, int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply<>(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("RespondPeerAuthentication")); callMessage << QVariant::fromValue(secret); return this->connection().asyncCall(callMessage, timeout); } /** * Begins a call to the D-Bus method \c AbortPeerAuthentication on the remote object. * * \htmlonly *

This method aborts the peer authentication process.

* \endhtmlonly * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply<> AbortPeerAuthentication(int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply<>(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("AbortPeerAuthentication")); return this->connection().asyncCall(callMessage, timeout); } Q_SIGNALS: /** * Represents the signal \c MessageSent on the remote object. * * \htmlonly *

* The same as: * \endhtmlonly ChannelInterfaceMessagesInterface \htmlonly *

* \endhtmlonly */ void MessageSent(const Tp::MessagePartList& content, uint flags, const QString& messageToken); /** * Represents the signal \c MessageReceived on the remote object. * * \htmlonly *

* The same as: * \endhtmlonly ChannelInterfaceMessagesInterface \htmlonly * Plus: *

The OTR interface adds some additional keys to message headers. * Messages sent during an encrypted OTR session have an additional * 'otr-remote-fingerprint' header, whose string value is the * human-readable hex form of an OTR fingerprint:

* * * { * 'message-type': Channel_Text_Message_Type_Normal, * 'message-sender': 42, # Contact_Handle of mercutio@example.com * 'otr-remote-fingerprint': '12345678 12345678 12345678 12345678 12345678', * }, * { * 'content-type': 'text/plain', * 'content': 'O, then, I see Queen Mab hath been with you.', * } * * *

Logging infrastructure MAY use these headers to associate * conversations with OTR users in a secure way, or to avoid * logging OTR conversations at all.

* *

Messages generated internally by the OTR implementation have an * additional "otr-message-event" key in the header (0'th part) whose * value is the OtrlMessageEvent, and SHOULD be * of type Channel_Text_Message_Type_Notice. These messages do not have id * and should not be acknowledged:

* * * { * 'message-type': Channel_Text_Message_Type_Notice, * 'message-sender': 42, # Contact_Handle of mercutio@example.com * 'otr-message-event': OTRL_MSGEVENT_RCVDMSG_UNRECOGNIZED, * 'otr-remote-fingerprint': '12345678 12345678 12345678 12345678 12345678', * }, * { * 'content-type': 'text/plain', * 'content': 'Unrecognized OTR message received from mercutio@example.com', * } * * *

User interfaces that implement OTR MUST present these special * notices in a way that cannot be faked by the remote user * sending a crafted XMPP (or other protocol) notice.

* *

For OTRL_MSGEVENT_SETUP_ERROR or OTRL_MSGEVENT_RCVDMSG_GENERAL_ERR * events, the header SHOULD additionally contain an "otr-error" * key whose string value is a debug message.

* *

For OTRL_MSGEVENT_RCVDMSG_UNENCRYPTED events, the header * MUST additionally contain an "otr-unencrypted-message" key * whose string value is the unencrypted message.

*

* \endhtmlonly */ void MessageReceived(const Tp::MessagePartList& message); /** * Represents the signal \c PendingMessagesRemoved on the remote object. * * \htmlonly *

* The same as: * \endhtmlonly ChannelInterfaceMessagesInterface \htmlonly *

* \endhtmlonly */ void PendingMessagesRemoved(const Tp::UIntList& messageIDs); /** * Represents the signal \c PeerAuthenticationRequested on the remote object. * * Emitted when peer authentication has been requested by the remote peer. * * \param question * * The question the remote peer is using for peer authentication. If * an empty string is passed only the shared secret will be used on * the peer authentication process. */ void PeerAuthenticationRequested(const QString& question); /** * Represents the signal \c PeerAuthenticationConcluded on the remote object. * * Emitted when the peer authentication process finishes normally. * * \param authenticated * * True if peer identity could be authenticated, false otherwise. */ void PeerAuthenticationConcluded(bool authenticated); /** * Represents the signal \c PeerAuthenticationInProgress on the remote object. * * Emitted when the peer authentication process has entered next stage. */ void PeerAuthenticationInProgress(); /** * Represents the signal \c PeerAuthenticationAborted on the remote object. * * Emitted when the peer authentication process has been aborted by the * remote peer. */ void PeerAuthenticationAborted(); /** * Represents the signal \c PeerAuthenticationError on the remote object. * * Emitted when the peer authentication process has been aborted because a * protocol error has occured. */ void PeerAuthenticationError(); /** * Represents the signal \c PeerAuthenticationCheated on the remote object. * * Emitted when the peer authentication process has been aborted because * cheating was discovered. */ void PeerAuthenticationCheated(); /** * Represents the signal \c SessionRefreshed on the remote object. * * An AKE has been performed in an already established session. */ void SessionRefreshed(); /** * Represents the signal \c TrustLevelChanged on the remote object. * * \htmlonly * OTR state of the connection has changed. * \endhtmlonly */ void TrustLevelChanged(uint trustLevel); protected: void invalidate(Tp::DBusProxy *, const QString &, const QString &) override; }; } } Q_DECLARE_METATYPE(KTp::Client::ChannelProxyInterfaceOTRInterface*) #endif diff --git a/KTp/OTR/proxy-service-interface.cpp b/KTp/OTR/proxy-service-interface.cpp index 53df6cb..6481729 100644 --- a/KTp/OTR/proxy-service-interface.cpp +++ b/KTp/OTR/proxy-service-interface.cpp @@ -1,45 +1,45 @@ #define IN_TP_QT_HEADER #include "proxy-service-interface.h" namespace KTp { namespace Client { ProxyServiceInterface::ProxyServiceInterface(const QString& busName, const QString& objectPath, QObject *parent) : Tp::AbstractInterface(busName, objectPath, staticInterfaceName(), QDBusConnection::sessionBus(), parent) { } ProxyServiceInterface::ProxyServiceInterface(const QDBusConnection& connection, const QString& busName, const QString& objectPath, QObject *parent) : Tp::AbstractInterface(busName, objectPath, staticInterfaceName(), connection, parent) { } ProxyServiceInterface::ProxyServiceInterface(Tp::DBusProxy *proxy) : Tp::AbstractInterface(proxy, staticInterfaceName()) { } ProxyServiceInterface::ProxyServiceInterface(const Tp::AbstractInterface& mainInterface) : Tp::AbstractInterface(mainInterface.service(), mainInterface.path(), staticInterfaceName(), mainInterface.connection(), mainInterface.parent()) { } ProxyServiceInterface::ProxyServiceInterface(const Tp::AbstractInterface& mainInterface, QObject *parent) : Tp::AbstractInterface(mainInterface.service(), mainInterface.path(), staticInterfaceName(), mainInterface.connection(), parent) { } void ProxyServiceInterface::invalidate(Tp::DBusProxy *proxy, const QString &error, const QString &message) { - disconnect(this, SIGNAL(ProxyConnected(const QDBusObjectPath&)), NULL, NULL); - disconnect(this, SIGNAL(ProxyDisconnected(const QDBusObjectPath&)), NULL, NULL); - disconnect(this, SIGNAL(KeyGenerationStarted(const QDBusObjectPath&)), NULL, NULL); - disconnect(this, SIGNAL(KeyGenerationFinished(const QDBusObjectPath&, bool)), NULL, NULL); + disconnect(this, SIGNAL(ProxyConnected(const QDBusObjectPath&)), nullptr, nullptr); + disconnect(this, SIGNAL(ProxyDisconnected(const QDBusObjectPath&)), nullptr, nullptr); + disconnect(this, SIGNAL(KeyGenerationStarted(const QDBusObjectPath&)), nullptr, nullptr); + disconnect(this, SIGNAL(KeyGenerationFinished(const QDBusObjectPath&, bool)), nullptr, nullptr); Tp::AbstractInterface::invalidate(proxy, error, message); } } } diff --git a/KTp/OTR/proxy-service-interface.h b/KTp/OTR/proxy-service-interface.h index f00efd4..c9265cc 100644 --- a/KTp/OTR/proxy-service-interface.h +++ b/KTp/OTR/proxy-service-interface.h @@ -1,354 +1,354 @@ /* * This file contains D-Bus client proxy classes generated by qt-client-gen.py. * * This file can be distributed under the same terms as the specification from * which it was generated. */ #ifndef OTR_PROXY_SERVICE_INTERFACE_HEADER #define OTR_PROXY_SERVICE_INTERFACE_HEADER #include "types.h" #include "ktpotr_export.h" #include #include #include #include #include #include #include #include #include namespace Tp { class PendingVariant; class PendingOperation; } namespace KTp { namespace Client { /** * \class ProxyServiceInterface * \headerfile TelepathyQt/proxy-service.h * \ingroup clientproxyservice * * Proxy class providing a 1:1 mapping of the D-Bus interface "org.kde.TelepathyProxy.ProxyService". */ class KTPOTR_EXPORT ProxyServiceInterface : public Tp::AbstractInterface { Q_OBJECT public: /** * Returns the name of the interface "org.kde.TelepathyProxy.ProxyService", which this class * represents. * * \return The D-Bus interface name. */ static inline QLatin1String staticInterfaceName() { return QLatin1String("org.kde.TelepathyProxy.ProxyService"); } /** * Creates a ProxyServiceInterface associated with the given object on the session bus. * * \param busName Name of the service the object is on. * \param objectPath Path to the object on the service. * \param parent Passed to the parent class constructor. */ ProxyServiceInterface( const QString& busName, const QString& objectPath, - QObject* parent = 0 + QObject* parent = nullptr ); /** * Creates a ProxyServiceInterface associated with the given object on the given bus. * * \param connection The bus via which the object can be reached. * \param busName Name of the service the object is on. * \param objectPath Path to the object on the service. * \param parent Passed to the parent class constructor. */ ProxyServiceInterface( const QDBusConnection& connection, const QString& busName, const QString& objectPath, - QObject* parent = 0 + QObject* parent = nullptr ); /** * Creates a ProxyServiceInterface associated with the same object as the given proxy. * * \param proxy The proxy to use. It will also be the QObject::parent() * for this object. */ ProxyServiceInterface(Tp::DBusProxy *proxy); /** * Creates a ProxyServiceInterface associated with the same object as the given proxy. * Additionally, the created proxy will have the same parent as the given * proxy. * * \param mainInterface The proxy to use. */ explicit ProxyServiceInterface(const Tp::AbstractInterface& mainInterface); /** * Creates a ProxyServiceInterface associated with the same object as the given proxy. * However, a different parent object can be specified. * * \param mainInterface The proxy to use. * \param parent Passed to the parent class constructor. */ ProxyServiceInterface(const Tp::AbstractInterface& mainInterface, QObject* parent); /** * Asynchronous getter for the remote object property \c PolicySettings of type \c uint. * * * \htmlonly *

Set the OTR policy how you like it

* \endhtmlonly * * \return A pending variant which will emit finished when the property has been * retrieved. */ inline Tp::PendingVariant *requestPropertyPolicySettings() const { return internalRequestProperty(QLatin1String("PolicySettings")); } /** * Asynchronous setter for the remote object property \c PolicySettings of type \c uint. * * * \htmlonly *

Set the OTR policy how you like it

* \endhtmlonly * * \return A pending operation which will emit finished when the property has been * set. */ inline Tp::PendingOperation *setPropertyPolicySettings(uint newValue) { return internalSetProperty(QLatin1String("PolicySettings"), QVariant::fromValue(newValue)); } /** * Request all of the DBus properties on the interface. * * \return A pending variant map which will emit finished when the properties have * been retrieved. */ Tp::PendingVariantMap *requestAllProperties() const { return internalRequestAllProperties(); } public Q_SLOTS: /** * Begins a call to the D-Bus method \c GeneratePrivateKey on the remote object. * * \htmlonly *

Generate new private key for given account.

* \endhtmlonly * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply<> GeneratePrivateKey(const QDBusObjectPath& account, int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply<>(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("GeneratePrivateKey")); callMessage << QVariant::fromValue(account); return this->connection().asyncCall(callMessage, timeout); } /** * Begins a call to the D-Bus method \c GetFingerprintForAccount on the remote object. * * Get private key fingerprint associated with given account * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * * \param account * * The account the new key is generated for * \param timeout The timeout in milliseconds. * * \return * * Fingerprint of given account's private key or an empty string * if none exists */ inline QDBusPendingReply GetFingerprintForAccount(const QDBusObjectPath& account, int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("GetFingerprintForAccount")); callMessage << QVariant::fromValue(account); return this->connection().asyncCall(callMessage, timeout); } /** * Begins a call to the D-Bus method \c GetKnownFingerprints on the remote object. * * Get private key fingerprint associated with given account * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply GetKnownFingerprints(const QDBusObjectPath& account, int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("GetKnownFingerprints")); callMessage << QVariant::fromValue(account); return this->connection().asyncCall(callMessage, timeout); } /** * Begins a call to the D-Bus method \c TrustFingerprint on the remote object. * * Trust or distrust given fingerprint for account by settings * Is_Verfified to %TRUE or %FALSE * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply<> TrustFingerprint(const QDBusObjectPath& account, const QString& contactName, const QString& fingerprint, bool trust, int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply<>(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("TrustFingerprint")); callMessage << QVariant::fromValue(account) << QVariant::fromValue(contactName) << QVariant::fromValue(fingerprint) << QVariant::fromValue(trust); return this->connection().asyncCall(callMessage, timeout); } /** * Begins a call to the D-Bus method \c ForgetFingerprint on the remote object. * * Forget fingerprint romoving it from the list of known fingerprints * * Note that \a timeout is ignored as of now. It will be used once * http://bugreports.qt.nokia.com/browse/QTBUG-11775 is fixed. * * \param timeout The timeout in milliseconds. */ inline QDBusPendingReply<> ForgetFingerprint(const QDBusObjectPath& account, const QString& contactName, const QString& fingerprint, int timeout = -1) { if (!invalidationReason().isEmpty()) { return QDBusPendingReply<>(QDBusMessage::createError( invalidationReason(), invalidationMessage() )); } QDBusMessage callMessage = QDBusMessage::createMethodCall(this->service(), this->path(), this->staticInterfaceName(), QLatin1String("ForgetFingerprint")); callMessage << QVariant::fromValue(account) << QVariant::fromValue(contactName) << QVariant::fromValue(fingerprint); return this->connection().asyncCall(callMessage, timeout); } Q_SIGNALS: /** * Represents the signal \c ProxyConnected on the remote object. * * Signals that a proxy has been connected * * \param proxy * * The object path of the connected proxy */ void ProxyConnected(const QDBusObjectPath& proxy); /** * Represents the signal \c ProxyDisconnected on the remote object. * * Signals that a proxy has been disconnected * * \param proxy * * The object path of the disconnectd proxy type */ void ProxyDisconnected(const QDBusObjectPath& proxy); /** * Represents the signal \c KeyGenerationStarted on the remote object. * * Signals that a new private key is being generated for account * * \param account * * The account the new key is generated for */ void KeyGenerationStarted(const QDBusObjectPath& account); /** * Represents the signal \c KeyGenerationFinished on the remote object. * * Signals that a new private key has just been generated for account * * \param account * * The account the new key has been generated for * * \param error * * %TRUE if error occured during generation */ void KeyGenerationFinished(const QDBusObjectPath& account, bool error); protected: void invalidate(Tp::DBusProxy *, const QString &, const QString &) override; }; } } Q_DECLARE_METATYPE(KTp::Client::ProxyServiceInterface*) #endif diff --git a/KTp/OTR/utils.cpp b/KTp/OTR/utils.cpp index ad57be8..366388e 100644 --- a/KTp/OTR/utils.cpp +++ b/KTp/OTR/utils.cpp @@ -1,92 +1,92 @@ /* Copyright (C) 2014 Marcin Ziemiński This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include "utils.h" #include "constants.h" #include #include namespace KTp { namespace Utils { Tp::UIntList getPendingMessagesIDs(const QList &messageQueue) { Tp::UIntList ids; Q_FOREACH(const Tp::ReceivedMessage &mes, messageQueue) { ids << getId(mes.parts()); } return ids; } uint getId(const Tp::MessagePartList &message) { - return message.first()[QLatin1String("pending-message-id")].variant().toUInt(NULL); + return message.first()[QLatin1String("pending-message-id")].variant().toUInt(nullptr); } QString getOtrProxyObjectPathFor(const Tp::TextChannelPtr &textChannel) { int index; QString connectionId = textChannel->connection()->objectPath(); index = connectionId.lastIndexOf(QChar::fromLatin1('/')); connectionId = connectionId.mid(index+1); QString channelId = textChannel->objectPath(); index = channelId.lastIndexOf(QChar::fromLatin1('/')); channelId = channelId.mid(index+1); return QString::fromLatin1("%1%2/%3").arg(KTP_PROXY_CHANNEL_OBJECT_PATH_PREFIX, connectionId, channelId); } bool isOtrMessage(const QString &text) { return text.startsWith(QLatin1String("?OTR")); } bool isOtrEvent(const Tp::ReceivedMessage &message) { return message.part(0).contains(OTR_MESSAGE_EVENT_HEADER); } QString processOtrMessage(const Tp::ReceivedMessage &message) { Tp::MessagePart messagePart = message.part(0); OTRMessageEvent otrEvent = static_cast( - messagePart[OTR_MESSAGE_EVENT_HEADER].variant().toUInt(0)); + messagePart[OTR_MESSAGE_EVENT_HEADER].variant().toUInt(nullptr)); switch(otrEvent) { case KTp::OTRL_MSGEVENT_SETUP_ERROR: case KTp::OTRL_MSGEVENT_RCVDMSG_GENERAL_ERR: { QString otrError = messagePart[OTR_ERROR_HEADER].variant().toString(); return i18n("OTR error: %1", otrError); } case KTp::OTRL_MSGEVENT_RCVDMSG_UNENCRYPTED: { QString unencryptedMessage = messagePart[OTR_UNENCRYPTED_MESSAGE_HEADER].variant().toString(); return i18n("Received unencrypted message: [%1]", unencryptedMessage); } default: return message.text(); } } } } diff --git a/KTp/Widgets/accounts-combo-box.h b/KTp/Widgets/accounts-combo-box.h index 5eec59a..252ecef 100644 --- a/KTp/Widgets/accounts-combo-box.h +++ b/KTp/Widgets/accounts-combo-box.h @@ -1,67 +1,67 @@ /* * Copyright (C) 2012 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ACCOUNTSCOMBOBOX_H #define ACCOUNTSCOMBOBOX_H #include #include #include namespace KTp { class KTPCOMMONINTERNALS_EXPORT AccountsComboBox : public QComboBox { Q_OBJECT Q_DISABLE_COPY(AccountsComboBox) public: - explicit AccountsComboBox(QWidget *parent = 0); + explicit AccountsComboBox(QWidget *parent = nullptr); ~AccountsComboBox() override; public: /** A set of accounts to show. * See AccountsListModel::setAccountSet for details */ void setAccountSet(const Tp::AccountSetPtr &accountSet); /** The currently selected account * @return the select account this pointer will be null if no account is selected */ Tp::AccountPtr currentAccount(); /** Sets the index to the account with the specified ID, provided it exists in the account set * This may be used to save/restore the last used account when showing the combo box * @param selectedAccountId the account id as found from Tp::Account::uniqueIdentifier */ void setCurrentAccount(const QString &selectedAccountId); /** Sets the index to the specified account, provided it exists in the account set @param selectedAccount the account to select */ void setCurrentAccount(const Tp::AccountPtr &selectedAccount); private: class Private; Private * const d; }; } #endif // ACCOUNTSCOMBOBOX_H diff --git a/KTp/Widgets/add-contact-dialog.h b/KTp/Widgets/add-contact-dialog.h index aaab0b9..4775f7c 100644 --- a/KTp/Widgets/add-contact-dialog.h +++ b/KTp/Widgets/add-contact-dialog.h @@ -1,64 +1,64 @@ /* * Add contact dialog * * Copyright (C) 2011 David Edmundson * Copyright (C) 2012 George Kiagiadakis * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ADDCONTACTDIALOG_H #define ADDCONTACTDIALOG_H #include #include #include namespace Tp { class PendingOperation; } namespace KTp { class KTPCOMMONINTERNALS_EXPORT AddContactDialog : public QDialog { Q_OBJECT public: - explicit AddContactDialog(const Tp::AccountManagerPtr &accountManager, QWidget *parent = 0); + explicit AddContactDialog(const Tp::AccountManagerPtr &accountManager, QWidget *parent = nullptr); ~AddContactDialog() override; void accept() override; protected: void closeEvent(QCloseEvent *e) override; private Q_SLOTS: KTPCOMMONINTERNALS_NO_EXPORT void _k_onContactsForIdentifiersFinished(Tp::PendingOperation *op); KTPCOMMONINTERNALS_NO_EXPORT void _k_onRequestPresenceSubscriptionFinished(Tp::PendingOperation *op); KTPCOMMONINTERNALS_NO_EXPORT void _k_onAccountUpgraded(Tp::PendingOperation *op); void updateSubscriptionMessageVisibility(); private: KTPCOMMONINTERNALS_NO_EXPORT void setInProgress(bool inProgress); struct Private; Private * const d; }; } #endif // ADDCONTACTDIALOG_H diff --git a/KTp/Widgets/contact-grid-dialog.cpp b/KTp/Widgets/contact-grid-dialog.cpp index 212be5e..91d6a1e 100644 --- a/KTp/Widgets/contact-grid-dialog.cpp +++ b/KTp/Widgets/contact-grid-dialog.cpp @@ -1,159 +1,159 @@ /* * Contact Chooser Dialog * * Copyright (C) 2011 David Edmundson * Copyright (C) 2012 Daniele E. Domenichelli * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact-grid-dialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include class KTp::ContactGridDialog::Private { public: Private(KTp::ContactGridDialog *parent) : q(parent), - contactsModel(0) + contactsModel(nullptr) { } KTp::ContactGridDialog * const q; Tp::AccountManagerPtr accountManager; KTp::ContactsListModel *contactsModel; KTp::ContactGridWidget *contactGridWidget; QDialogButtonBox *buttonBox; public: void _k_onAccountManagerReady(); void _k_onSelectionChanged(); }; void KTp::ContactGridDialog::Private::_k_onAccountManagerReady() { contactsModel->setAccountManager(accountManager); } void KTp::ContactGridDialog::Private::_k_onSelectionChanged() { buttonBox->button(QDialogButtonBox::Ok)->setEnabled(contactGridWidget->hasSelection()); } KTp::ContactGridDialog::ContactGridDialog(QWidget *parent) : QDialog(parent), d(new Private(this)) { resize(500,450); Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(), Tp::Features() << Tp::Account::FeatureCore << Tp::Account::FeatureAvatar << Tp::Account::FeatureProtocolInfo << Tp::Account::FeatureProfile << Tp::Account::FeatureCapabilities); Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(), Tp::Features() << Tp::Connection::FeatureCore << Tp::Connection::FeatureRosterGroups << Tp::Connection::FeatureRoster << Tp::Connection::FeatureSelfContact); Tp::ContactFactoryPtr contactFactory = KTp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias << Tp::Contact::FeatureAvatarData << Tp::Contact::FeatureSimplePresence << Tp::Contact::FeatureCapabilities); Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus()); d->accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(), accountFactory, connectionFactory, channelFactory, contactFactory); d->contactsModel = new KTp::ContactsListModel(this); connect(d->accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(_k_onAccountManagerReady())); d->contactGridWidget = new KTp::ContactGridWidget(d->contactsModel, this); d->contactGridWidget->contactFilterLineEdit()->setPlaceholderText(i18n("Search in Contacts...")); d->contactGridWidget->filter()->setPresenceTypeFilterFlags(KTp::ContactsFilterModel::ShowOnlyConnected); d->buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this); connect(d->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(d->buttonBox, SIGNAL(rejected()), this, SLOT(reject())); QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->addWidget(d->contactGridWidget); mainLayout->addWidget(d->buttonBox); setLayout(mainLayout); connect(d->contactGridWidget, SIGNAL(contactDoubleClicked(Tp::AccountPtr,KTp::ContactPtr)), SLOT(accept())); connect(d->contactGridWidget, SIGNAL(selectionChanged(Tp::AccountPtr,KTp::ContactPtr)), SLOT(_k_onSelectionChanged())); d->_k_onSelectionChanged(); connect(this, SIGNAL(rejected()), SLOT(close())); } KTp::ContactGridDialog::~ContactGridDialog() { delete d; } Tp::AccountPtr KTp::ContactGridDialog::account() { return d->contactGridWidget->selectedAccount(); } Tp::ContactPtr KTp::ContactGridDialog::contact() { return d->contactGridWidget->selectedContact(); } KTp::ContactsFilterModel* KTp::ContactGridDialog::filter() const { return d->contactGridWidget->filter(); } #include "moc_contact-grid-dialog.cpp" diff --git a/KTp/Widgets/contact-grid-widget.h b/KTp/Widgets/contact-grid-widget.h index 084bbed..2f823f0 100644 --- a/KTp/Widgets/contact-grid-widget.h +++ b/KTp/Widgets/contact-grid-widget.h @@ -1,40 +1,40 @@ /* * Copyright (C) 2014 Amandeep Singh * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CONTACT_GRID_WIDGET_H #define CONTACT_GRID_WIDGET_H #include namespace KTp { class KTPCOMMONINTERNALS_EXPORT ContactGridWidget : public ContactViewWidget { Q_OBJECT Q_DISABLE_COPY(ContactGridWidget) public: - explicit ContactGridWidget(ContactsListModel *model, QWidget *parent = 0); + explicit ContactGridWidget(ContactsListModel *model, QWidget *parent = nullptr); }; // class ContactGridWidget } // namespace KTp #endif // CONTACT_GRID_WIDGET_H diff --git a/KTp/Widgets/contact-info-dialog.cpp b/KTp/Widgets/contact-info-dialog.cpp index 123cad3..c903612 100644 --- a/KTp/Widgets/contact-info-dialog.cpp +++ b/KTp/Widgets/contact-info-dialog.cpp @@ -1,468 +1,468 @@ /* * Copyright (C) 2013 Dan Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact-info-dialog.h" #include "contact.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace KTp { enum InfoRowIndex { FullName = 0, Nickname, Email, Phone, Homepage, Birthday, Organization, _InfoRowCount }; static struct InfoRow { const InfoRowIndex index; const QString fieldName; const char* title; } InfoRows[] = { // Don't use i18n in global static vars { FullName, QLatin1String("fn"), I18N_NOOP("Full name:") }, { Nickname, QLatin1String("nickname"), I18N_NOOP("Nickname:") }, { Email, QLatin1String("email"), I18N_NOOP("Email:") }, { Phone, QLatin1String("tel"), I18N_NOOP("Phone:") }, { Homepage, QLatin1String("url"), I18N_NOOP("Homepage:") }, { Birthday, QLatin1String("bday"), I18N_NOOP("Birthday:") }, { Organization, QLatin1String("org"), I18N_NOOP("Organization:") } }; class ContactInfoDialog::Private { public: Private(ContactInfoDialog *parent): editable(false), infoDataChanged(false), avatarChanged(false), - columnsLayout(0), - infoLayout(0), - stateLayout(0), - changeAvatarButton(0), - clearAvatarButton(0), - avatarLabel(0), + columnsLayout(nullptr), + infoLayout(nullptr), + stateLayout(nullptr), + changeAvatarButton(nullptr), + clearAvatarButton(nullptr), + avatarLabel(nullptr), q(parent) {} void onContactUpgraded(Tp::PendingOperation *op); void onContactInfoReceived(Tp::PendingOperation *op); void onChangeAvatarButtonClicked(); void onClearAvatarButtonClicked(); void onInfoDataChanged(); void onFeatureRosterReady(Tp::PendingOperation *op); void addInfoRow(InfoRowIndex index, const QString &value); void addStateRow(const QString &description, Tp::Contact::PresenceState state); void loadStateRows(); Tp::AccountPtr account; KTp::ContactPtr contact; bool editable; bool infoDataChanged; bool avatarChanged; QString newAvatarFile; QMap infoValueWidgets; QHBoxLayout *columnsLayout; QFormLayout *infoLayout; QFormLayout *stateLayout; QPushButton *changeAvatarButton; QPushButton *clearAvatarButton; QLabel *avatarLabel; QDialogButtonBox *buttonBox; private: ContactInfoDialog *q; }; void ContactInfoDialog::Private::onContactUpgraded(Tp::PendingOperation* op) { Tp::PendingContacts *contacts = qobject_cast(op); if (op->isError()) { return; } Q_ASSERT(contacts->contacts().count() == 1); contact = KTp::ContactPtr::qObjectCast(contacts->contacts().first()); /* Show avatar immediatelly */ if (contacts->features().contains(Tp::Contact::FeatureAvatarData)) { QVBoxLayout *avatarLayout = new QVBoxLayout(); avatarLayout->setSpacing(5); avatarLayout->setAlignment(Qt::AlignHCenter); columnsLayout->addLayout(avatarLayout); avatarLabel = new QLabel(q); avatarLabel->setMaximumSize(150, 150); avatarLayout->addWidget(avatarLabel, 0, Qt::AlignTop); if (editable) { changeAvatarButton = new QPushButton(i18n("Change Avatar"), q); connect(changeAvatarButton, SIGNAL(clicked(bool)), q, SLOT(onChangeAvatarButtonClicked())); avatarLayout->addWidget(changeAvatarButton); clearAvatarButton = new QPushButton(i18n("Clear Avatar"), q); connect(clearAvatarButton, SIGNAL(clicked(bool)), q, SLOT(onClearAvatarButtonClicked())); avatarLayout->addWidget(clearAvatarButton); avatarLayout->addStretch(1); } QPixmap avatar(contact->avatarPixmap()); avatarLabel->setPixmap(avatar.scaled(avatarLabel->maximumSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); } /* Request detailed contact info */ if (contacts->features().contains(Tp::Contact::FeatureInfo)) { infoLayout = new QFormLayout(); infoLayout->setSpacing(10); columnsLayout->addLayout(infoLayout); Tp::PendingContactInfo *op = contact->requestInfo(); connect(op, SIGNAL(finished(Tp::PendingOperation*)), q, SLOT(onContactInfoReceived(Tp::PendingOperation*))); } } void ContactInfoDialog::Private::onFeatureRosterReady(Tp::PendingOperation *op) { loadStateRows(); } void ContactInfoDialog::Private::onContactInfoReceived(Tp::PendingOperation* op) { Tp::PendingContactInfo *ci = qobject_cast(op); const Tp::ContactInfoFieldList fieldList = ci->infoFields().allFields(); for (InfoRowIndex index = (InfoRowIndex) 0; index < _InfoRowCount; index = (InfoRowIndex)(index + 1)) { QString value; Q_FOREACH(const Tp::ContactInfoField &field, fieldList) { if (field.fieldValue.count() == 0) { continue; } if (field.fieldName == InfoRows[index].fieldName) { value = field.fieldValue.first(); break; } } /* Show edits for all values when in editable mode */ if (!editable && value.isEmpty()) { continue; } addInfoRow(index, value); } } void ContactInfoDialog::Private::onChangeAvatarButtonClicked() { QPointer fileDialog = new QFileDialog(q); // fileDialog->setPreviewWidget(new KImageFilePreview(fileDialog)); //TODO KF5 - is there a replacement? fileDialog->setMimeTypeFilters(QStringList() << QStringLiteral("image/*")); fileDialog->setFileMode(QFileDialog::ExistingFile); int c = fileDialog->exec(); if (fileDialog && c && !fileDialog->selectedFiles().isEmpty()) { newAvatarFile = fileDialog->selectedFiles().first(); QPixmap avatar(newAvatarFile); if (avatar.isNull()) { KMessageBox::error(q, i18n("Failed to load the new avatar image")); newAvatarFile.clear(); delete fileDialog; return; } avatarLabel->setPixmap(avatar.scaled(avatarLabel->maximumSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); avatarChanged = true; clearAvatarButton->setEnabled(true); } delete fileDialog; } void ContactInfoDialog::Private::onClearAvatarButtonClicked() { QPixmap avatar; avatar = KIconLoader::global()->loadIcon(QLatin1String("im-user"), KIconLoader::Desktop, 128); newAvatarFile.clear(); avatarChanged = true; } void ContactInfoDialog::Private::onInfoDataChanged() { infoDataChanged = true; } void ContactInfoDialog::Private::addInfoRow(InfoRowIndex index, const QString &value) { InfoRow *row = &InfoRows[index]; // I18N_NOOP only marks the string for translation, the actual lookup of // translated row->title happens here QLabel *descriptionLabel = new QLabel(i18n(row->title), q); QFont font = descriptionLabel->font(); font.setBold(true); descriptionLabel->setFont(font); if (editable) { if (index == Birthday) { KDateComboBox *combo = new KDateComboBox(q); combo->setOptions(KDateComboBox::EditDate | KDateComboBox::SelectDate | KDateComboBox::DatePicker); combo->setMinimumWidth(200); combo->setDate(QDate::fromString(value)); connect(combo, SIGNAL(dateChanged(QDate)), q, SLOT(onInfoDataChanged())); infoValueWidgets.insert(index, combo); } else { QLineEdit *edit = new QLineEdit(q); edit->setMinimumWidth(200); edit->setText(value); connect(edit, SIGNAL(textChanged(QString)), q, SLOT(onInfoDataChanged())); infoValueWidgets.insert(index, edit); } } else { QLabel *label = new QLabel(q); label->setOpenExternalLinks(true); label->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse); if (index == Email) { label->setText(QString::fromLatin1("%1").arg(value)); } else if (index == Homepage) { QString format; if (!value.startsWith(QLatin1String("http"), Qt::CaseInsensitive)) { format = QLatin1String("%1"); } else { format = QLatin1String("%1"); } label->setText(format.arg(value)); } else { label->setText(value); } infoValueWidgets.insert(index, label); } infoLayout->addRow(descriptionLabel, infoValueWidgets.value(index)); } void ContactInfoDialog::Private::addStateRow(const QString& description, Tp::Contact::PresenceState state) { QLabel *descriptionLabel = new QLabel(description, q); QIcon icon; switch (state) { case Tp::Contact::PresenceStateYes: icon = QIcon::fromTheme(QStringLiteral("task-complete")); break; case Tp::Contact::PresenceStateNo: icon = QIcon::fromTheme(QStringLiteral("task-reject")); break; case Tp::Contact::PresenceStateAsk: default: icon = QIcon::fromTheme(QStringLiteral("task-attempt")); break; } QLabel *stateLabel = new QLabel(q); stateLabel->setPixmap(icon.pixmap(16)); stateLayout->addRow(descriptionLabel, stateLabel); } void ContactInfoDialog::Private::loadStateRows() { if(stateLayout) { addStateRow(i18n("Contact can see when you are online:"), contact->publishState()); addStateRow(i18n("You can see when the contact is online:"), contact->subscriptionState()); addStateRow(i18n("Contact is blocked:"), contact->isBlocked() ? Tp::Contact::PresenceStateYes : Tp::Contact::PresenceStateNo); } } ContactInfoDialog::ContactInfoDialog(const Tp::AccountPtr &account, const Tp::ContactPtr &contact, QWidget *parent) : QDialog(parent) , d(new Private(this)) { #if 0 // Editing contacts is not yet supported in TpQt /* Whether contact is the user himself */ d->editable = (contact == account->connection()->selfContact()); #endif d->editable = false; d->account = account; d->contact = KTp::ContactPtr::qObjectCast(contact); d->buttonBox = new QDialogButtonBox(this); if (d->editable) { d->buttonBox->setStandardButtons(QDialogButtonBox::Save | QDialogButtonBox::Close); } else { d->buttonBox->setStandardButtons(QDialogButtonBox::Close); } connect(d->buttonBox, &QDialogButtonBox::clicked, this, &ContactInfoDialog::slotButtonClicked); setMaximumSize(sizeHint()); QVBoxLayout *layout = new QVBoxLayout(this); layout->setSpacing(30); /* Title - presence icon, alias, id */ KTitleWidget *titleWidget = new KTitleWidget(this); KTp::Presence presence(contact->presence()); titleWidget->setPixmap(presence.icon().pixmap(32, 32), KTitleWidget::ImageLeft); titleWidget->setText(contact->alias()); titleWidget->setComment(contact->id()); layout->addWidget(titleWidget); /* 1st column: avatar; 2nd column: details */ d->columnsLayout = new QHBoxLayout(); d->columnsLayout->setSpacing(30); layout->addLayout(d->columnsLayout); /* Make sure the contact has all neccessary features ready */ Tp::PendingContacts *op = contact->manager()->upgradeContacts( QList() << contact, Tp::Features() << Tp::Contact::FeatureAvatarData << Tp::Contact::FeatureInfo); connect(op, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onContactUpgraded(Tp::PendingOperation*))); /* State Info - there is no point showing this information when it's about ourselves */ if (!d->editable) { d->stateLayout = new QFormLayout(); d->stateLayout->setSpacing(10); layout->addLayout(d->stateLayout); // Fetch roster feature, if it is supported, but not loaded Tp::ConnectionPtr conn = contact->manager()->connection(); if(!conn->actualFeatures().contains(Tp::Connection::FeatureRoster) && !conn->missingFeatures().contains(Tp::Connection::FeatureRoster)) { Tp::PendingReady *pr = conn->becomeReady(Tp::Features() << Tp::Connection::FeatureRoster); connect(pr, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onFeatureRosterReady(Tp::PendingOperation*))); } else { d->loadStateRows(); } } layout->addWidget(d->buttonBox); } ContactInfoDialog::~ContactInfoDialog() { delete d; } void ContactInfoDialog::slotButtonClicked(QAbstractButton *button) { if (button == d->buttonBox->button(QDialogButtonBox::Save)) { if (d->avatarChanged) { Tp::Avatar avatar; if (!d->newAvatarFile.isEmpty()) { QFile file(d->newAvatarFile); file.open(QIODevice::ReadOnly); QFileInfo fi(file); avatar.avatarData = file.readAll(); file.seek(0); // reset before passing to KMimeType QMimeDatabase db; avatar.MIMEType = db.mimeTypeForFileNameAndData(d->newAvatarFile, &file).name(); } d->account->setAvatar(avatar); } if (d->infoDataChanged) { Tp::ContactInfoFieldList fieldList; for (InfoRowIndex index = (InfoRowIndex) 0; index < _InfoRowCount; index = (InfoRowIndex) (index + 1)) { InfoRow *row = &InfoRows[index]; Tp::ContactInfoField field; field.fieldName = row->fieldName; if (index == Birthday) { KDateComboBox *combo = qobject_cast(d->infoValueWidgets.value(index)); field.fieldValue << combo->date().toString(); } else { QLineEdit *lineEdit = qobject_cast(d->infoValueWidgets.value(index)); field.fieldValue << lineEdit->text(); } fieldList << field; } #if 0 // This method does not exist in TpQt (yet) d->account->connection()->setContactInfo(fieldList); #endif } accept(); return; } } } /* namespace KTp */ #include "moc_contact-info-dialog.cpp" diff --git a/KTp/Widgets/contact-info-dialog.h b/KTp/Widgets/contact-info-dialog.h index 2734bdb..455768f 100644 --- a/KTp/Widgets/contact-info-dialog.h +++ b/KTp/Widgets/contact-info-dialog.h @@ -1,63 +1,63 @@ /* * Copyright (C) 2013 Dan Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KTP_CONTACTINFODIALOG_H #define KTP_CONTACTINFODIALOG_H #include #include #include class QAbstractButton; namespace Tp { class PendingOperation; } namespace KTp { class KTPCOMMONINTERNALS_EXPORT ContactInfoDialog : public QDialog { Q_OBJECT public: - explicit ContactInfoDialog(const Tp::AccountPtr &account, const Tp::ContactPtr &contact, QWidget *parent = 0); + explicit ContactInfoDialog(const Tp::AccountPtr &account, const Tp::ContactPtr &contact, QWidget *parent = nullptr); ~ContactInfoDialog() override; protected: virtual void slotButtonClicked(QAbstractButton *button); private: class Private; Private * const d; Q_PRIVATE_SLOT(d, void onContactUpgraded(Tp::PendingOperation*)) Q_PRIVATE_SLOT(d, void onContactInfoReceived(Tp::PendingOperation*)) Q_PRIVATE_SLOT(d, void onChangeAvatarButtonClicked()) Q_PRIVATE_SLOT(d, void onClearAvatarButtonClicked()) Q_PRIVATE_SLOT(d, void onInfoDataChanged()) Q_PRIVATE_SLOT(d, void onFeatureRosterReady(Tp::PendingOperation *op)) }; } // namespace KTp #endif // KTP_CONTACTINFODIALOG_H diff --git a/KTp/Widgets/contact-view-widget.cpp b/KTp/Widgets/contact-view-widget.cpp index cdc64ba..0d91668 100644 --- a/KTp/Widgets/contact-view-widget.cpp +++ b/KTp/Widgets/contact-view-widget.cpp @@ -1,284 +1,284 @@ /* * Copyright (C) 2011 David Edmundson * Copyright (C) 2012 Daniele E. Domenichelli * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact-view-widget.h" #include #include #include #include #include #include "types.h" #include #include namespace KTp { class ContactViewDelegate : public QAbstractItemDelegate { Q_OBJECT Q_DISABLE_COPY(ContactViewDelegate) public: ContactViewDelegate(QObject *parent); ~ContactViewDelegate() override; void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; }; // class ContactViewDelegate } // namespace KTp KTp::ContactViewDelegate::ContactViewDelegate(QObject *parent) : QAbstractItemDelegate(parent) { } KTp::ContactViewDelegate::~ContactViewDelegate() { } void KTp::ContactViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyle *style = QApplication::style(); int textHeight = option.fontMetrics.height() * 2; style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter); QRect avatarRect = option.rect.adjusted(0, 0, 0, -textHeight); QRect textRect = option.rect.adjusted(0, option.rect.height() - textHeight, 0, -3); QPixmap avatar; avatar.load(index.data(KTp::ContactAvatarPathRole).toString()); if (avatar.isNull()) { avatar = QIcon::fromTheme(QStringLiteral("im-user-online")).pixmap(option.decorationSize); } else if (avatar.width() > option.decorationSize.width() || avatar.height() > option.decorationSize.height()) { //resize larger avatars if required avatar = avatar.scaled(option.decorationSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); //draw leaving paddings on smaller (or non square) avatars } style->drawItemPixmap(painter, avatarRect, Qt::AlignCenter, avatar); QTextOption textOption; textOption.setAlignment(Qt::AlignCenter); textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); painter->drawText(textRect, index.data().toString(), textOption); } QSize KTp::ContactViewDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(index); int textHeight = option.fontMetrics.height() * 2; return QSize(option.decorationSize.width() + 4, option.decorationSize.height() + textHeight + 3); } // ----------------------------------------------------------------------------- class KTp::ContactViewWidget::Private { public: Private(KTp::ContactViewWidget *parent) : q(parent), layout(new QVBoxLayout(parent)), contactView(new QListView(parent)), contactFilterLineEdit(new QLineEdit(parent)), - contactsModel(0), - filterModel(0) + contactsModel(nullptr), + filterModel(nullptr) { } ~Private() { } void _k_onSelectionChanged(const QItemSelection &newSelection, const QItemSelection &oldSelection); void _k_onDoubleClicked(const QModelIndex &index); KTp::ContactViewWidget *q; QVBoxLayout *layout; QListView *contactView; QLineEdit *contactFilterLineEdit; KTp::ContactsListModel *contactsModel; KTp::ContactsFilterModel *filterModel; }; void KTp::ContactViewWidget::Private::_k_onSelectionChanged(const QItemSelection &newSelection, const QItemSelection &oldSelection) { Q_UNUSED(oldSelection) if (newSelection.isEmpty()) { Q_EMIT q->selectionChanged(Tp::AccountPtr(), KTp::ContactPtr()); return; } Q_EMIT q->selectionChanged(q->selectedAccount(), q->selectedContact()); } void KTp::ContactViewWidget::Private::_k_onDoubleClicked(const QModelIndex& index) { if (!index.isValid()) { return; } Q_EMIT q->contactDoubleClicked(index.data(KTp::AccountRole).value(), index.data(KTp::ContactRole).value()); } // ----------------------------------------------------------------------------- KTp::ContactViewWidget::ContactViewWidget(KTp::ContactsListModel* model, QWidget *parent) : QWidget(parent), d(new Private(this)) { d->filterModel = new KTp::ContactsFilterModel(this); d->contactsModel = model; d->filterModel->setSourceModel(d->contactsModel); d->contactView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); d->contactView->setResizeMode(QListView::Adjust); d->contactView->setSpacing(5); d->contactView->setViewMode(QListView::ListMode); d->contactView->setIconSize(QSize(80, 80)); d->contactFilterLineEdit->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); d->contactFilterLineEdit->setClearButtonEnabled(true); d->layout->setMargin(0); d->layout->addWidget(d->contactView); d->layout->addWidget(d->contactFilterLineEdit); setLayout(d->layout); d->contactView->setModel(d->filterModel); d->contactView->setItemDelegate(new ContactViewDelegate(d->contactView)); connect(d->contactView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(_k_onSelectionChanged(QItemSelection,QItemSelection))); connect(d->contactView, SIGNAL(doubleClicked(QModelIndex)), SLOT(_k_onDoubleClicked(QModelIndex))); connect(d->contactFilterLineEdit, SIGNAL(textChanged(QString)), d->filterModel, SLOT(setDisplayNameFilterString(QString))); } KTp::ContactViewWidget::~ContactViewWidget() { delete d; } QString KTp::ContactViewWidget::displayNameFilter() const { return d->contactFilterLineEdit->text(); } void KTp::ContactViewWidget::clearDisplayNameFilter() { setDisplayNameFilter(QString()); } void KTp::ContactViewWidget::setDisplayNameFilter(const QString& displayNameFilter) { if (displayNameFilter != d->contactFilterLineEdit->text()) { d->contactFilterLineEdit->setText(displayNameFilter); Q_EMIT displayNameFilterChanged(displayNameFilter); } } QSize KTp::ContactViewWidget::iconSize() const { return d->contactView->iconSize(); } void KTp::ContactViewWidget::setIconSize(const QSize& iconSize) { if (iconSize != d->contactView->iconSize()) { d->contactView->setIconSize(iconSize); Q_EMIT iconSizeChanged(iconSize); } } bool KTp::ContactViewWidget::hasSelection() const { return d->contactView->selectionModel()->hasSelection(); } Tp::AccountPtr KTp::ContactViewWidget::selectedAccount() const { return d->contactView->currentIndex().data(KTp::AccountRole).value(); } KTp::ContactPtr KTp::ContactViewWidget::selectedContact() const { return d->contactView->currentIndex().data(KTp::ContactRole).value(); } QList KTp::ContactViewWidget::selectedContacts() const { QList selected; Q_FOREACH (const QModelIndex &index, d->contactView->selectionModel()->selectedIndexes()) { selected << index.data(KTp::ContactRole).value(); } return selected; } void KTp::ContactViewWidget::setViewMode(QListView::ViewMode mode) { d->contactView->setViewMode(mode); } QListView::ViewMode KTp::ContactViewWidget::viewMode() const { return d->contactView->viewMode(); } QAbstractItemView::SelectionMode KTp::ContactViewWidget::selectionMode() { return d->contactView->selectionMode(); } void KTp::ContactViewWidget::setSelectionMode(QAbstractItemView::SelectionMode mode) { d->contactView->setSelectionMode(mode); } KTp::ContactsFilterModel* KTp::ContactViewWidget::filter() const { return d->filterModel; } QLineEdit* KTp::ContactViewWidget::contactFilterLineEdit() const { return d->contactFilterLineEdit; } #include "contact-view-widget.moc" #include "moc_contact-view-widget.cpp" diff --git a/KTp/Widgets/contact-view-widget.h b/KTp/Widgets/contact-view-widget.h index 9e46ee6..313c029 100644 --- a/KTp/Widgets/contact-view-widget.h +++ b/KTp/Widgets/contact-view-widget.h @@ -1,102 +1,102 @@ /* * Copyright (C) 2011 David Edmundson * Copyright (C) 2012 Daniele E. Domenichelli * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CONTACT_VIEW_WIDGET_H #define CONTACT_VIEW_WIDGET_H #include #include #include #include #include class QLineEdit; class QItemSelection; class QListView; namespace KTp { class ContactsFilterModel; class ContactsListModel; class KTPCOMMONINTERNALS_EXPORT ContactViewWidget : public QWidget { Q_OBJECT Q_DISABLE_COPY(ContactViewWidget) Q_PROPERTY(QString displayNameFilter READ displayNameFilter RESET clearDisplayNameFilter WRITE setDisplayNameFilter NOTIFY displayNameFilterChanged) Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize NOTIFY iconSizeChanged) Q_PROPERTY(QListView::ViewMode viewMode READ viewMode WRITE setViewMode) public: - explicit ContactViewWidget(ContactsListModel *model, QWidget *parent = 0); + explicit ContactViewWidget(ContactsListModel *model, QWidget *parent = nullptr); ~ContactViewWidget() override; virtual QString displayNameFilter() const; Q_SLOT virtual void clearDisplayNameFilter(); Q_SLOT virtual void setDisplayNameFilter(const QString &displayNameFilter); Q_SIGNAL void displayNameFilterChanged(const QString &displayNameFilter); virtual QSize iconSize() const; Q_SLOT virtual void setIconSize(const QSize &iconSize); Q_SIGNAL void iconSizeChanged(const QSize &iconSize); virtual KTp::ContactsFilterModel* filter() const; virtual QLineEdit* contactFilterLineEdit() const; virtual bool hasSelection() const; virtual Tp::AccountPtr selectedAccount() const; virtual KTp::ContactPtr selectedContact() const; virtual QList selectedContacts() const; void setViewMode(QListView::ViewMode); QListView::ViewMode viewMode() const; void setSelectionMode(QAbstractItemView::SelectionMode mode); QAbstractItemView::SelectionMode selectionMode(); Q_SIGNALS: void selectionChanged(const Tp::AccountPtr &selectedAccount, const KTp::ContactPtr &selectedContact); void contactDoubleClicked(const Tp::AccountPtr &account, const KTp::ContactPtr &contact); private: class Private; Private * const d; Q_PRIVATE_SLOT(d, void _k_onSelectionChanged(const QItemSelection ¤tSelection, const QItemSelection &previousSelection)); Q_PRIVATE_SLOT(d, void _k_onDoubleClicked(const QModelIndex &index)); }; // class ContactViewWidget } // namespace KTp #endif // CONTACT_VIEW_WIDGET_H diff --git a/KTp/Widgets/join-chat-room-dialog.h b/KTp/Widgets/join-chat-room-dialog.h index 26934e3..d0c2638 100644 --- a/KTp/Widgets/join-chat-room-dialog.h +++ b/KTp/Widgets/join-chat-room-dialog.h @@ -1,86 +1,86 @@ /* * This file is part of telepathy-contactslist-prototype * * Copyright (C) 2011 Francesco Nwokeka * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef JOINCHATROOMDIALOG_H #define JOINCHATROOMDIALOG_H #include #include #include #include namespace Ui { class JoinChatRoomDialog; } class RoomsModel; class FavoriteRoomsModel; class QSortFilterProxyModel; class QAbstractButton; namespace KTp { class KTPCOMMONINTERNALS_EXPORT JoinChatRoomDialog : public QDialog { Q_OBJECT public: - explicit JoinChatRoomDialog(Tp::AccountManagerPtr accountManager, QWidget *parent = 0); + explicit JoinChatRoomDialog(Tp::AccountManagerPtr accountManager, QWidget *parent = nullptr); ~JoinChatRoomDialog() override; Tp::AccountPtr selectedAccount() const; /** returns selected account */ QString selectedChatRoom() const; /** returns selected chat room */ void accept() override; protected: void closeEvent(QCloseEvent *e) override; private Q_SLOTS: void onTextChanged(QString newText); void onAccountSelectionChanged(int newIndex); void addRecentRoom(); void clearRecentRooms(); void getRoomList(); void stopListing(); void onRoomListChannelReadyForHandling(Tp::PendingOperation *operation); void onRoomListChannelReady(Tp::PendingOperation *operation); void onRoomListChannelClosed(Tp::PendingOperation *operation); void onListing(bool isListing); void onGotRooms(Tp::RoomInfoList roomInfoList); void onFavoriteRoomSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous); void onFavoriteRoomDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight); void onRoomClicked(const QModelIndex &index); void onAccountManagerReady(Tp::PendingOperation*); void onStartChatFinished(Tp::PendingOperation *op); private: void sendNotificationToUser(const QString& errorMsg); void loadFavoriteRooms(); void setJoinInProgress(bool); struct Private; Private * const d; }; } //namespace KTp #endif // JOINCHATROOMDIALOG_H diff --git a/KTp/Widgets/notification-config-dialog.h b/KTp/Widgets/notification-config-dialog.h index aec7e05..821dcfa 100644 --- a/KTp/Widgets/notification-config-dialog.h +++ b/KTp/Widgets/notification-config-dialog.h @@ -1,56 +1,56 @@ /* * This file is part of KDE Telepathy Common Internals * * Copyright (C) 2012 Rohan Garg * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef NOTIFICATIONCONFIGDIALOG_H #define NOTIFICATIONCONFIGDIALOG_H #include #include #include class QDialogButtonBox; class KNotifyConfigWidget; class QAbstractButton; namespace KTp { class KTPCOMMONINTERNALS_EXPORT NotificationConfigDialog : public QDialog { Q_OBJECT public: - explicit NotificationConfigDialog(const Tp::ContactPtr &contact, QWidget *parent = 0); + explicit NotificationConfigDialog(const Tp::ContactPtr &contact, QWidget *parent = nullptr); ~NotificationConfigDialog() override; private Q_SLOTS: void updateNotifyWidget(const int selection); void defaults(); void onOkClicked(); void onButtonBoxClicked(QAbstractButton *button); private: KNotifyConfigWidget *m_notifyWidget; Tp::ContactPtr m_contact; int m_currentSelection; QDialogButtonBox *m_buttonBox; }; } #endif // NOTIFICATIONCONFIGDIALOG_H diff --git a/KTp/Widgets/settings-kcm-dialog.h b/KTp/Widgets/settings-kcm-dialog.h index da5445a..5146459 100644 --- a/KTp/Widgets/settings-kcm-dialog.h +++ b/KTp/Widgets/settings-kcm-dialog.h @@ -1,45 +1,45 @@ /* * Settings KCM Dialog * * Copyright (C) 2011 Martin Klapetek * Copyright (C) 2014 Siddhartha Sahu * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SETTINGS_KCM_DIALOG_H #define SETTINGS_KCM_DIALOG_H #include #include namespace KTp { class KTPCOMMONINTERNALS_EXPORT SettingsKcmDialog : public KSettings::Dialog { Q_OBJECT public: - SettingsKcmDialog(QWidget *parent = 0); + SettingsKcmDialog(QWidget *parent = nullptr); // Add the General Settings tab void addGeneralSettingsModule(); // Add the Notifications tab void addNotificationsModule(); }; } // namespace KTp #endif // SETTINGS_KCM_DIALOG_H diff --git a/KTp/Widgets/start-chat-dialog.h b/KTp/Widgets/start-chat-dialog.h index 0591526..d21c88b 100644 --- a/KTp/Widgets/start-chat-dialog.h +++ b/KTp/Widgets/start-chat-dialog.h @@ -1,61 +1,61 @@ /* * Start chat dialog * * Copyright (C) 2013 Anant Kamath * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef STARTCHATDIALOG_H #define STARTCHATDIALOG_H #include #include #include namespace Tp { class PendingOperation; } namespace KTp { class KTPCOMMONINTERNALS_EXPORT StartChatDialog : public QDialog { Q_OBJECT public: - explicit StartChatDialog(const Tp::AccountManagerPtr &accountManager, QWidget *parent = 0); + explicit StartChatDialog(const Tp::AccountManagerPtr &accountManager, QWidget *parent = nullptr); ~StartChatDialog() override; void accept() override; protected: void closeEvent(QCloseEvent *e) override; private Q_SLOTS: KTPCOMMONINTERNALS_NO_EXPORT void _k_onStartChatFinished(Tp::PendingOperation *op); KTPCOMMONINTERNALS_NO_EXPORT void _k_onPendingContactFinished(Tp::PendingOperation *op); private: KTPCOMMONINTERNALS_NO_EXPORT void setInProgress(bool inProgress); struct Private; Private * const d; }; } #endif // STARTCHATDIALOG_H diff --git a/KTp/abstract-message-filter.h b/KTp/abstract-message-filter.h index af10a34..bef664f 100644 --- a/KTp/abstract-message-filter.h +++ b/KTp/abstract-message-filter.h @@ -1,58 +1,58 @@ /* Copyright (C) 2012 Lasath Fernando This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KTP_ABSTRACT_MESSAGE_FILTER_H #define KTP_ABSTRACT_MESSAGE_FILTER_H #include #include #include #include #include #include namespace KTp { class KTPCOMMONINTERNALS_EXPORT AbstractMessageFilter : public QObject { Q_OBJECT public: - AbstractMessageFilter(QObject* parent = 0); + AbstractMessageFilter(QObject* parent = nullptr); ~AbstractMessageFilter() override; /** Filter messages to show on the UI recieved by another contact*/ virtual void filterMessage(KTp::Message &message, const KTp::MessageContext &context); /** Scripts that must be included in the section of the html required by this message filter.*/ virtual QStringList requiredScripts(); /** Stylesheets that must be included in the section of the html required by this message filter.*/ virtual QStringList requiredStylesheets(); /** Filter composed messages about to be sent to telepathy backend */ virtual void filterOutgoingMessage(KTp::OutgoingMessage &message, const KTp::MessageContext &context); }; } #endif // ABSTRACTPLUGIN_H diff --git a/KTp/actions.cpp b/KTp/actions.cpp index 17d631f..80c5da8 100644 --- a/KTp/actions.cpp +++ b/KTp/actions.cpp @@ -1,319 +1,319 @@ /* * Copyright (C) 2012 Dan Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "actions.h" #include #include #include #include #include #include #include #include #include "ktp-debug.h" #include #include #include #define PREFERRED_TEXT_CHAT_HANDLER QLatin1String("org.freedesktop.Telepathy.Client.KTp.TextUi") #define PREFERRED_FILE_TRANSFER_HANDLER QLatin1String("org.freedesktop.Telepathy.Client.KTp.FileTransfer") #define PREFERRED_AUDIO_VIDEO_HANDLER QLatin1String("org.freedesktop.Telepathy.Client.KTp.CallUi") #define PREFERRED_RFB_HANDLER QLatin1String("org.freedesktop.Telepathy.Client.krfb_rfb_handler") using namespace KTp; Tp::PendingChannelRequest* Actions::startChat(const Tp::AccountPtr &account, const QString &contactIdentifier, bool delegateToPreferredHandler) { if (account.isNull() || contactIdentifier.isEmpty()) { qCWarning(KTP_COMMONINTERNALS) << "Parameters invalid"; } qCDebug(KTP_COMMONINTERNALS) << "Requesting text channel for contact id: " << contactIdentifier; Tp::ChannelRequestHints hints; if (delegateToPreferredHandler) { hints.setHint(QLatin1String("org.freedesktop.Telepathy.ChannelRequest"), QLatin1String("DelegateToPreferredHandler"), QVariant(true)); } return account->ensureTextChat(contactIdentifier, QDateTime::currentDateTime(), PREFERRED_TEXT_CHAT_HANDLER, hints); } Tp::PendingChannelRequest* Actions::startChat(const Tp::AccountPtr &account, const Tp::ContactPtr &contact, bool delegateToPreferredHandler) { if (account.isNull() || contact.isNull()) { qCWarning(KTP_COMMONINTERNALS) << "Parameters invalid"; } qCDebug(KTP_COMMONINTERNALS) << "Requesting text channel for" << contact->id(); Tp::ChannelRequestHints hints; if (delegateToPreferredHandler) { hints.setHint(QLatin1String("org.freedesktop.Telepathy.ChannelRequest"), QLatin1String("DelegateToPreferredHandler"), QVariant(true)); } return account->ensureTextChat(contact, QDateTime::currentDateTime(), PREFERRED_TEXT_CHAT_HANDLER, hints); } Tp::PendingChannelRequest* Actions::startGroupChat(const Tp::AccountPtr &account, const QString &roomName) { if (account.isNull() || roomName.isEmpty()) { qCWarning(KTP_COMMONINTERNALS) << "Parameters invalid"; } qCDebug(KTP_COMMONINTERNALS) << "Requesting text chat room " << roomName; Tp::ChannelRequestHints hints; hints.setHint(QLatin1String("org.kde.telepathy"), QLatin1String("forceRaiseWindow"), QVariant(true)); return account->ensureTextChatroom(roomName, QDateTime::currentDateTime(), PREFERRED_TEXT_CHAT_HANDLER, hints); } Tp::PendingChannelRequest* Actions::startAudioCall(const Tp::AccountPtr &account, const Tp::ContactPtr &contact) { if (account.isNull() || contact.isNull()) { qCWarning(KTP_COMMONINTERNALS) << "Parameters invalid"; } qCDebug(KTP_COMMONINTERNALS) << "Requesting audio channel for" << contact->id(); return account->ensureAudioCall(contact, QLatin1String("audio"), QDateTime::currentDateTime(), PREFERRED_AUDIO_VIDEO_HANDLER); } Tp::PendingChannelRequest* Actions::startAudioVideoCall(const Tp::AccountPtr &account, const Tp::ContactPtr &contact) { if (account.isNull() || contact.isNull()) { qCWarning(KTP_COMMONINTERNALS) << "Parameters invalid"; } qCDebug(KTP_COMMONINTERNALS) << "Requesting audio-video channel for" << contact->id(); return account->ensureAudioVideoCall(contact, QLatin1String("audio"), QLatin1String("video"), QDateTime::currentDateTime(), PREFERRED_AUDIO_VIDEO_HANDLER); } Tp::PendingChannelRequest* Actions::startDesktopSharing(const Tp::AccountPtr &account, const Tp::ContactPtr &contact) { if (account.isNull() || contact.isNull()) { qCWarning(KTP_COMMONINTERNALS) << "Parameters invalid"; } qCDebug(KTP_COMMONINTERNALS) << "Requesting stream tube for" << contact->id(); return account->createStreamTube(contact, QLatin1String("rfb"), QDateTime::currentDateTime(), PREFERRED_RFB_HANDLER); } Tp::PendingChannelRequest* Actions::startFileTransfer(const Tp::AccountPtr &account, const Tp::ContactPtr &contact, const QString &filePath) { if (account.isNull() || contact.isNull()) { qCWarning(KTP_COMMONINTERNALS) << "Parameters invalid"; } qCDebug(KTP_COMMONINTERNALS) << "Requesting file transfer of" << filePath << "to" << contact->id(); QFileInfo fileInfo(filePath); Tp::FileTransferChannelCreationProperties fileTransferProperties; if (account->serviceName() == QLatin1String("google-talk") && (fileInfo.suffix() == QLatin1String("exe") || fileInfo.suffix() == QLatin1String("ini"))) { qCDebug(KTP_COMMONINTERNALS) << "Google Talk forbids transfering files with suffix \"ini\" or \"exe\". Renaming."; QString fileName = fileInfo.fileName().append(QLatin1String("_")); QMimeDatabase db; fileTransferProperties = Tp::FileTransferChannelCreationProperties(fileName, db.mimeTypeForFile(filePath).name(), fileInfo.size()); fileTransferProperties.setUri(QUrl::fromLocalFile(filePath).toString()); fileTransferProperties.setLastModificationTime(fileInfo.lastModified()); KNotification *notification = new KNotification (QLatin1String("googletalkExtensionsError")); notification->setText(i18n("Transferring files with .exe or .ini extension is not allowed by Google Talk. It was sent with filename %1", fileName)); notification->setTitle(i18n("Transferred file renamed")); notification->setComponentName(QStringLiteral("ktelepathy")); notification->sendEvent(); } else { QMimeDatabase db; fileTransferProperties = Tp::FileTransferChannelCreationProperties( filePath, db.mimeTypeForFile(filePath, QMimeDatabase::MatchContent).name()); } return account->createFileTransfer(contact, fileTransferProperties, QDateTime::currentDateTime(), PREFERRED_FILE_TRANSFER_HANDLER); } Tp::PendingOperation* Actions::startFileTransfer(const Tp::AccountPtr &account, const Tp::ContactPtr &contact, const QUrl &url) { if (account.isNull() || contact.isNull() || url.isEmpty()) { qCWarning(KTP_COMMONINTERNALS) << "Parameters invalid"; } qCDebug(KTP_COMMONINTERNALS) << "Requesting file transfer of" << url.toLocalFile() << "to" << contact->id(); - Tp::PendingOperation *ret = 0; + Tp::PendingOperation *ret = nullptr; if (url.isLocalFile()) { ret = startFileTransfer(account, contact, url.toLocalFile()); } else { ret = new Tp::PendingFailure(QLatin1String("Failed file transfer"), QString(QLatin1String("You are only supposed to send local files, not %1")).arg(url.toString()), account); } return ret; } void Actions::openLogViewer(const Tp::AccountPtr &account, const Tp::ContactPtr &contact) { if (account.isNull() || contact.isNull()) { qCWarning(KTP_COMMONINTERNALS) << "Parameters invalid"; return; } openLogViewer(account, contact->id()); } void Actions::openLogViewer(const QUrl &uri) { qCDebug(KTP_COMMONINTERNALS) << "Opening logviewer for" << uri; QStringList arguments; arguments << QLatin1String("--") << uri.toString(); KToolInvocation::kdeinitExec(QLatin1String("ktp-log-viewer"), arguments); } void Actions::openLogViewer(const Tp::AccountPtr& account, const QString& targetId) { if (account.isNull() || targetId.isEmpty()) { qCWarning(KTP_COMMONINTERNALS) << " Parameters invalid"; return; } qCDebug(KTP_COMMONINTERNALS) << "Opening logviewer for" << targetId; QStringList arguments; arguments << QLatin1String("--") << account->uniqueIdentifier() << targetId; /* Use "--" so that KCmdLineArgs does not parse UIDs starting with "-" as arguments */ KToolInvocation::kdeinitExec(QLatin1String("ktp-log-viewer"), arguments); } const QVariantMap createHintsForCollabRequest(const Actions::DocumentList& documents, bool needOpenEditor) { QVariantMap hints; hints.insert(QLatin1String("initialDocumentsSize"), documents.size()); for ( int i = 0; i < documents.size(); i++ ) { const QString key(QLatin1String("initialDocument") + QString::number(i)); hints.insert(key, documents.at(i).fileName()); if ( needOpenEditor ) { hints.insert(key + QLatin1String("_source"), documents.at(i).url()); } } if ( needOpenEditor ) { hints.insert(QLatin1String("needToOpenDocument"), QVariant(true)); } return hints; } Tp::PendingChannelRequest* createCollabRequest(const Tp::AccountPtr account, const Actions::DocumentList documents, QVariantMap requestBase, bool needOpenEditor) { QVariantMap hints = createHintsForCollabRequest(documents, needOpenEditor); requestBase.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType"), TP_QT_IFACE_CHANNEL_TYPE_STREAM_TUBE); requestBase.insert(TP_QT_IFACE_CHANNEL_TYPE_STREAM_TUBE + QLatin1String(".Service"), QLatin1String("infinote")); Tp::PendingChannelRequest* channelRequest; channelRequest = account->ensureChannel(requestBase, QDateTime::currentDateTime(), QLatin1String("org.freedesktop.Telepathy.Client.KTp.infinoteServer"), hints); return channelRequest; } Tp::PendingChannelRequest* Actions::startCollaborativeEditing(const Tp::AccountPtr& account, const Tp::ContactPtr& contact, const DocumentList& documents, bool needOpenEditor) { QVariantMap request; request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType"), (uint) Tp::HandleTypeContact); request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle"), contact->handle().at(0)); return createCollabRequest(account, documents, request, needOpenEditor); } Tp::PendingChannelRequest* Actions::startCollaborativeEditing(const Tp::AccountPtr& account, const QString& chatroom, const DocumentList& documents, bool needOpenEditor) { QVariantMap request; request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType"), (uint) Tp::HandleTypeRoom); request.insert(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetID"), chatroom); return createCollabRequest(account, documents, request, needOpenEditor); } diff --git a/KTp/circular-countdown.h b/KTp/circular-countdown.h index fcbd5c7..cd375c7 100644 --- a/KTp/circular-countdown.h +++ b/KTp/circular-countdown.h @@ -1,62 +1,62 @@ /* Circular countdown widget Copyright (C) 2011 Martin Klapetek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CIRCULARCOUNTDOWN_H #define CIRCULARCOUNTDOWN_H #include #include namespace KTp { class KTPCOMMONINTERNALS_EXPORT CircularCountdown : public QWidget { Q_OBJECT public: - explicit CircularCountdown(int msec = 5000, QWidget *parent = 0); + explicit CircularCountdown(int msec = 5000, QWidget *parent = nullptr); ~CircularCountdown() override; void setDuration(int msec); int duration() const; public Q_SLOTS: void start(); void stop(); void pause(); void resume(); Q_SIGNALS: void timeout(); protected: void paintEvent(QPaintEvent *event) override; QSize sizeHint() const override; private: class Private; Private * const d; }; } #endif // CIRCULARCOUNTDOWN_H diff --git a/KTp/core.cpp b/KTp/core.cpp index ac36ced..f4dfc15 100644 --- a/KTp/core.cpp +++ b/KTp/core.cpp @@ -1,122 +1,122 @@ /* * static methods on the KTp namespace * * Copyright (C) 2013 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "core.h" #ifdef HAVE_KPEOPLE #include #include #endif #include #include #include #include "contact-factory.h" #include "account-factory_p.h" class CorePrivate { public: CorePrivate(); bool m_kPeopleEnabled; Tp::AccountFactoryPtr m_accountFactory; Tp::ConnectionFactoryPtr m_connectionFactory; Tp::ContactFactoryPtr m_contactFactory; Tp::ChannelFactoryPtr m_channelFactory ; Tp::AccountManagerPtr m_accountManager; KTp::GlobalContactManager *m_contactManager; }; CorePrivate::CorePrivate() : m_kPeopleEnabled(false), - m_contactManager(0) + m_contactManager(nullptr) { //if built with kpeople support, enable it #ifdef HAVE_KPEOPLE m_kPeopleEnabled = true; #endif m_accountFactory = KTp::AccountFactory::create(QDBusConnection::sessionBus(), Tp::Features() << Tp::Account::FeatureCore << Tp::Account::FeatureCapabilities << Tp::Account::FeatureProfile); m_connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(), Tp::Features() << Tp::Connection::FeatureCore << Tp::Connection::FeatureConnected << Tp::Connection::FeatureSelfContact); m_contactFactory = KTp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias << Tp::Contact::FeatureSimplePresence << Tp::Contact::FeatureCapabilities << Tp::Contact::FeatureClientTypes << Tp::Contact::FeatureAvatarData); m_channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus()); } Q_GLOBAL_STATIC(CorePrivate, s_instance) bool KTp::kpeopleEnabled() { return s_instance->m_kPeopleEnabled; } Tp::AccountFactoryConstPtr KTp::accountFactory() { return s_instance->m_accountFactory; } Tp::ConnectionFactoryConstPtr KTp::connectionFactory() { return s_instance->m_connectionFactory; } Tp::ChannelFactoryConstPtr KTp::channelFactory() { return s_instance->m_channelFactory; } Tp::ContactFactoryConstPtr KTp::contactFactory() { return s_instance->m_contactFactory; } Tp::AccountManagerPtr KTp::accountManager() { if (!s_instance->m_accountManager) { s_instance->m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(), KTp::accountFactory(), KTp::connectionFactory(), KTp::channelFactory(), KTp::contactFactory()); } return s_instance->m_accountManager; } KTp::GlobalContactManager* KTp::contactManager() { if (!s_instance->m_contactManager) { - s_instance->m_contactManager = new KTp::GlobalContactManager(KTp::accountManager(), 0); + s_instance->m_contactManager = new KTp::GlobalContactManager(KTp::accountManager(), nullptr); } return s_instance->m_contactManager; } diff --git a/KTp/global-contact-manager.h b/KTp/global-contact-manager.h index ecad19a..21f81d1 100644 --- a/KTp/global-contact-manager.h +++ b/KTp/global-contact-manager.h @@ -1,68 +1,68 @@ /* * This file is part of telepathy-common-internals * * Copyright (C) 2012 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef GLOBALCONTACTMANAGER_H #define GLOBALCONTACTMANAGER_H #include #include #include #include #include namespace KTp { class GlobalContactManagerPrivate; class KTPCOMMONINTERNALS_EXPORT GlobalContactManager : public QObject { Q_OBJECT public: - explicit GlobalContactManager(const Tp::AccountManagerPtr &accountManager, QObject *parent = 0); + explicit GlobalContactManager(const Tp::AccountManagerPtr &accountManager, QObject *parent = nullptr); ~GlobalContactManager() override; Tp::Contacts allKnownContacts() const; Tp::AccountPtr accountForConnection(const Tp::ConnectionPtr &connection) const; Tp::AccountPtr accountForContact(const Tp::ContactPtr &contact) const; Tp::AccountPtr accountForAccountId(const QString &accountId) const; Tp::AccountPtr accountForAccountPath(const QString &accountPath) const; KTp::ContactPtr contactForContactId(const QString &accountPath, const QString &contactId); Q_SIGNALS: void allKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved); void presencePublicationRequested(const Tp::Contacts); private Q_SLOTS: void onAccountManagerReady(Tp::PendingOperation *op); void onNewAccount(const Tp::AccountPtr &account); void onConnectionChanged(const Tp::ConnectionPtr &connection); void onConnectionReady(Tp::PendingOperation *op); void onContactManagerStateChanged(Tp::ContactListState state); private: void onContactManagerStateChanged(const Tp::ContactManagerPtr &contactManager, Tp::ContactListState state); GlobalContactManagerPrivate *d; }; } #endif // GLOBALCONTACTLIST_H diff --git a/KTp/global-presence.h b/KTp/global-presence.h index 169ce4b..061bcbf 100644 --- a/KTp/global-presence.h +++ b/KTp/global-presence.h @@ -1,243 +1,243 @@ /* * Global Presence - wraps calls to set and get presence for all accounts. * * Copyright (C) 2011 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef GLOBALPRESENCE_H #define GLOBALPRESENCE_H #include #include #include #include #include #include #include #include #include namespace KTp { /** This class handles the presence between all enabled accounts. * It shows the highest current / requested presence, indicates if any accounts * are changing state, and the highest they are changing to. */ class KTPCOMMONINTERNALS_EXPORT GlobalPresence : public QObject { Q_OBJECT Q_PROPERTY(Tp::AccountManagerPtr accountManager READ accountManager WRITE addAccountManager NOTIFY accountManagerReady) Q_PROPERTY(QString presenceMessage READ currentPresenceMessage NOTIFY currentPresenceChanged) Q_PROPERTY(ConnectionPresenceType presenceType READ currentPresenceType NOTIFY currentPresenceChanged) Q_PROPERTY(QIcon currentPresenceIcon READ currentPresenceIcon NOTIFY currentPresenceChanged) Q_PROPERTY(QString currentPresenceIconName READ currentPresenceIconName NOTIFY currentPresenceChanged) Q_PROPERTY(KTp::Presence currentPresence READ currentPresence NOTIFY currentPresenceChanged) Q_PROPERTY(QString currentPresenceName READ currentPresenceName NOTIFY currentPresenceChanged); Q_PROPERTY(KTp::Presence requestedPresence READ requestedPresence NOTIFY requestedPresenceChanged WRITE setPresence) Q_PROPERTY(QString requestedPresenceName READ requestedPresenceName NOTIFY requestedPresenceChanged) Q_PROPERTY(KTp::Presence globalPresence READ globalPresence WRITE setPresence) Q_PROPERTY(ConnectionStatus connectionStatus READ connectionStatus NOTIFY connectionStatusChanged) Q_PROPERTY(bool isChangingPresence READ isChangingPresence NOTIFY changingPresence) Q_PROPERTY(bool hasConnectionError READ hasConnectionError NOTIFY connectionStatusChanged) Q_PROPERTY(bool hasEnabledAccounts READ hasEnabledAccounts NOTIFY enabledAccountsChanged) Q_PROPERTY(Tp::AccountSetPtr enabledAccounts READ enabledAccounts) Q_PROPERTY(Tp::AccountSetPtr onlineAccounts READ onlineAccounts) public: - explicit GlobalPresence(QObject *parent = 0); + explicit GlobalPresence(QObject *parent = nullptr); enum ConnectionPresenceType { Offline = Tp::ConnectionPresenceTypeOffline, Available = Tp::ConnectionPresenceTypeAvailable, Away = Tp::ConnectionPresenceTypeAway, ExtendedAway = Tp::ConnectionPresenceTypeExtendedAway, Hidden = Tp::ConnectionPresenceTypeHidden, Busy = Tp::ConnectionPresenceTypeBusy, Unknown = Tp::ConnectionPresenceTypeUnknown, Unset = Tp::ConnectionPresenceTypeUnset, Error = Tp::ConnectionPresenceTypeError }; Q_ENUM(ConnectionPresenceType) enum ConnectionStatus { Disconnected = Tp::ConnectionStatusDisconnected, Connecting = Tp::ConnectionStatusConnecting, Connected = Tp::ConnectionStatusConnected }; Q_ENUM(ConnectionStatus) enum PresenceClass { Persistent, Session }; Q_ENUM(PresenceClass) /** * \brief Set a ready account manager. * * \param accountManager A Tp::AccountManagerPtr. */ void setAccountManager(const Tp::AccountManagerPtr &accountManager); /** * \brief Add a new (unready) account manager. * * \param accountManager A Tp::AccountManagerPtr. */ void addAccountManager(const Tp::AccountManagerPtr &accountManager); /** * \brief The account manager. * * \return A Tp::AccountManagerPtr. */ Tp::AccountManagerPtr accountManager() const; /** * \brief Global connection status. Returns connecting if any account is * connecting, else connected if at least one account is connected, * disconnected otherwise. * * \return A ConnectionStatus enum. */ ConnectionStatus connectionStatus() const; /** * \brief The most online presence of all accounts. Returns the same presence * as the requested presence if the most online account supports the * requested presence. */ KTp::Presence currentPresence() const; QString currentPresenceMessage() const; QIcon currentPresenceIcon() const; QString currentPresenceIconName() const; ConnectionPresenceType currentPresenceType() const; QString currentPresenceName() const; /** * \brief The most online requested presence for all accounts. */ KTp::Presence requestedPresence() const; QString requestedPresenceName() const; /** * \brief If any account is changing presence. * * \return true if any account is changing state. */ bool isChangingPresence() const; /** * \brief The KDED module requested global presence. * * \return A KTp::Presence. */ KTp::Presence globalPresence() const; /** * \brief If any account has a connection error. * * \return true if any account has a connection error. */ bool hasConnectionError() const; /** * \brief If the account manager has enabled accounts. * * \return true if the account manager has enabled accounts. */ bool hasEnabledAccounts() const; /** * \brief The account manager enabled accounts. * * \return The account manager enabled accounts set. */ Tp::AccountSetPtr enabledAccounts() const; /** * \brief The account manager online accounts. * * \return The account manager online accounts set. */ Tp::AccountSetPtr onlineAccounts() const; Q_SIGNALS: void requestedPresenceChanged(const KTp::Presence &requestedPresence); void currentPresenceChanged(const KTp::Presence ¤tPresence); void connectionStatusChanged(KTp::GlobalPresence::ConnectionStatus connectionStatus); void changingPresence(bool isChangingPresence); void enabledAccountsChanged(bool hasEnabledAccounts); void accountManagerReady(); public Q_SLOTS: /** * \brief Set the requested presence of all enabled accounts. If setting * the global requested presence fails, will set each account to the * specified presence. A presence type of unset will unset the presence. * * \param presence The requested presence. * * \overload presenceClass Session or Persistent presence class. **/ void setPresence(const KTp::Presence &presence, PresenceClass presenceClass = Persistent); /** * \brief Set the requested presence of all enabled accounts. If setting * the global requested presence fails, will set each account to the * specified presence. A presence type of unset will unset the presence. * * \param type The ConnectionPresenceType. * * \overload message A status message. * \overload presenceClass Session or Persistent presence class. **/ void setPresence(ConnectionPresenceType type, QString message = QString(), PresenceClass presenceClass = Session); private Q_SLOTS: void onCurrentPresenceChanged(const Tp::Presence ¤tPresence); void onRequestedPresenceChanged(const Tp::Presence &requestedPresence); void onChangingPresence(bool isChangingPresence); void onConnectionStatusChanged(Tp::ConnectionStatus connectionStatus); void onAccountEnabledChanged(const Tp::AccountPtr &account); private: QDBusInterface *m_statusHandlerInterface; Tp::AccountManagerPtr m_accountManager; Tp::AccountSetPtr m_enabledAccounts; Tp::AccountSetPtr m_onlineAccounts; KTp::Presence m_requestedPresence; KTp::Presence m_currentPresence; ConnectionStatus m_connectionStatus; bool m_changingPresence; bool m_hasConnectionError; bool m_hasEnabledAccounts; }; } #endif // GLOBALPRESENCE_H diff --git a/KTp/logs-importer.h b/KTp/logs-importer.h index 66e289c..d3d4a1d 100644 --- a/KTp/logs-importer.h +++ b/KTp/logs-importer.h @@ -1,89 +1,89 @@ /* * Copyright (C) 2012 Dan Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef LOGSIMPORTER_H #define LOGSIMPORTER_H #include #include #include namespace KTp { /** * @short A class to import old logs from Kopete * * This class provides convenient interface for importing logs from Kopete. * * Currently the importer supports AIM, WML, ICQ, Jabber, GaduGadu and Yahoo logs. */ class KTPCOMMONINTERNALS_EXPORT LogsImporter : public QObject { Q_OBJECT public: - LogsImporter(QObject *parent = 0); + LogsImporter(QObject *parent = nullptr); ~LogsImporter() override; /** * Checks whether there are any Kopete logs for \p account. * * @param account Telepathy Account against whose Kopete counterpart to check * @return Returns when there is at least one log for given account */ bool hasKopeteLogs(const Tp::AccountPtr &account); /** * Imports Kopete logs for \p account to Telepathy * * Finds all Kopete logs for Kopete-version of \p account, converts them * to Telepathy Logger format and imports then to Telepathy Logger storage. * * This method returns immediatelly. When all logs are scanned and converted, * logsImported() signal is emitted. * * The import will NOT overwrite existing log files. * * @param account A Telepathy Account */ void startLogImport(const Tp::AccountPtr &account); Q_SIGNALS: /** * Emitted when logs are successfully imported. */ void logsImported(); /** * Emitted when an error occurs during importing. * * The process can still import some logs, but some might be missing. */ void error(const QString &error); private: class Private; Private *d; }; } /* namespace KTp */ #endif // LOGSIMPORTER_H diff --git a/KTp/message-filters-private.h b/KTp/message-filters-private.h index 5e18f37..a15876e 100644 --- a/KTp/message-filters-private.h +++ b/KTp/message-filters-private.h @@ -1,40 +1,40 @@ /* Copyright (C) 2012 Lasath Fernando This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MESSAGE_FILTERS_PRIVATE_H #define MESSAGE_FILTERS_PRIVATE_H #include "abstract-message-filter.h" #include class MessageUrlFilter : public KTp::AbstractMessageFilter { public: - explicit MessageUrlFilter(QObject *parent = 0); + explicit MessageUrlFilter(QObject *parent = nullptr); void filterMessage(KTp::Message &message, const KTp::MessageContext &context) override; }; class MessageEscapeFilter : public KTp::AbstractMessageFilter { public: - explicit MessageEscapeFilter(QObject *parent = 0); + explicit MessageEscapeFilter(QObject *parent = nullptr); void filterMessage(KTp::Message& message, const KTp::MessageContext &context) override; }; #endif diff --git a/KTp/pending-wallet.cpp b/KTp/pending-wallet.cpp index 5006b7f..9f14718 100644 --- a/KTp/pending-wallet.cpp +++ b/KTp/pending-wallet.cpp @@ -1,53 +1,53 @@ /* * Copyright (C) 2012 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pending-wallet.h" #include "wallet-interface.h" namespace KTp { class PendingWalletPrivate { public: KTp::WalletInterface *walletInterface; }; } KTp::PendingWallet::PendingWallet(KTp::WalletInterface* walletInterface) - :Tp::PendingOperation(Tp::SharedPtr(0)), + :Tp::PendingOperation(Tp::SharedPtr(nullptr)), d( new KTp::PendingWalletPrivate()) { d->walletInterface = walletInterface; //if wallet is not enabled, or wallet is already opened, setFinished() immediately if (!walletInterface->wallet() || walletInterface->isOpen()) { setFinished(); } else { connect(walletInterface->wallet(), SIGNAL(walletOpened(bool)), SLOT(setFinished())); } } KTp::PendingWallet::~PendingWallet() { delete d; } KTp::WalletInterface *KTp::PendingWallet::walletInterface() const { return d->walletInterface; } diff --git a/KTp/service-availability-checker.h b/KTp/service-availability-checker.h index 5e50b0e..ed6ac81 100644 --- a/KTp/service-availability-checker.h +++ b/KTp/service-availability-checker.h @@ -1,57 +1,57 @@ /* Copyright (C) 2011 Collabora Ltd. @author George Kiagiadakis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #ifndef SERVICE_AVAILABILITY_CHECKER_H #define SERVICE_AVAILABILITY_CHECKER_H #include #include class QDBusPendingCallWatcher; namespace KTp { /** * This class watches if a given d-bus service is either * available on the bus or can be activated on demand. */ class KTPCOMMONINTERNALS_EXPORT ServiceAvailabilityChecker : public QObject { Q_OBJECT public: - explicit ServiceAvailabilityChecker(const QString & serviceName, QObject *parent = 0); + explicit ServiceAvailabilityChecker(const QString & serviceName, QObject *parent = nullptr); ~ServiceAvailabilityChecker() override; bool isAvailable() const; private Q_SLOTS: void introspect(); void onCallFinished(QDBusPendingCallWatcher *watcher); void onServiceOwnerChanged(const QString & service, const QString & oldOwner, const QString & newOwner); private: struct Private; Private * const d; }; } #endif // SERVICE_AVAILABILITY_CHECKER_H diff --git a/KTp/text-parser.cpp b/KTp/text-parser.cpp index 46cf566..b62a7a0 100644 --- a/KTp/text-parser.cpp +++ b/KTp/text-parser.cpp @@ -1,94 +1,94 @@ /* * Text Parser common class * Copyright (C) 2004 Peter Simonsson * Copyright (C) 2006-2008 Eike Hein * Copyright (C) 2011 Przemek Czekaj * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "text-parser.h" #include namespace KTp { -TextParser* TextParser::s_instance = NULL; +TextParser* TextParser::s_instance = nullptr; /** * RegExp for url detection */ static QRegExp s_urlPattern(QString::fromLatin1("\\b((?:(?:([a-z][\\w\\.-]+:/{1,3})|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|\\}\\]|[^\\s`!()\\[\\]{};:'\".,<>?%1%2%3%4%5%6])|[a-z0-9.\\-+_]+@[a-z0-9.\\-]+[.][a-z]{1,5}[^\\s/`!()\\[\\]{};:'\".,<>?%1%2%3%4%5%6]))") .arg(QChar(0x00AB)).arg(QChar(0x00BB)).arg(QChar(0x201C)).arg(QChar(0x201D)).arg(QChar(0x2018)).arg(QChar(0x2019))); TextParser::TextParser(QObject* parent) : QObject(parent) { } TextParser* TextParser::instance() { if (!s_instance) { - s_instance = new TextParser(0); + s_instance = new TextParser(nullptr); } return s_instance; } TextUrlData TextParser::extractUrlData(const QString& text, bool doUrlFixup) { TextUrlData data; QString htmlText(text); s_urlPattern.setCaseSensitivity(Qt::CaseInsensitive); int pos = 0; int urlLen = 0; QString protocol; QString href; while ((pos = s_urlPattern.indexIn(htmlText, pos)) >= 0) { urlLen = s_urlPattern.matchedLength(); href = htmlText.mid(pos, urlLen); data.urlRanges << QPair(pos, href.length()); pos += href.length(); if (doUrlFixup) { protocol.clear(); if (s_urlPattern.cap(2).isEmpty()) { QString urlPatternCap1(s_urlPattern.cap(1)); if (urlPatternCap1.contains(QLatin1Char('@'))) { protocol = QLatin1String("mailto:"); } else if (urlPatternCap1.startsWith(QLatin1String("ftp."), Qt::CaseInsensitive)) { protocol = QLatin1String("ftp://"); } else { protocol = QLatin1String("http://"); } } href = protocol + href; data.fixedUrls.append(href); } } return data; } TextParser::~TextParser() { } } diff --git a/KTp/text-parser.h b/KTp/text-parser.h index 5ae8704..833e543 100644 --- a/KTp/text-parser.h +++ b/KTp/text-parser.h @@ -1,95 +1,95 @@ /* * Text Parser common class * Copyright (C) 2004 Peter Simonsson * Copyright (C) 2006-2008 Eike Hein * Copyright (C) 2011 Przemek Czekaj * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TEXT_PARSER_H #define TEXT_PARSER_H #include #include #include #include namespace KTp { /** * Useful data container * * @var QList urlRanges * @var QStringList fixedUrls */ struct KTPCOMMONINTERNALS_EXPORT TextUrlData { QList > urlRanges; QStringList fixedUrls; }; /** * TextParser * */ class KTPCOMMONINTERNALS_EXPORT TextParser : public QObject { public: /** * Singleton pattern * * @param void * @return TextParser */ static TextParser *instance(); /** * Method extract url from text * * @param QString string A whole text * @param bool doUrlFixup fix the url default true * @return TextUrlData * @author Konversation developers */ TextUrlData extractUrlData(const QString& string, bool doUrlFixup = true); /** * Destructor * * @param void */ ~TextParser() override; private: /** * Constructor * * @param QObject */ - TextParser(QObject *parent = 0); + TextParser(QObject *parent = nullptr); /** * @var TextParser */ static TextParser *s_instance; }; } #endif // TEXT_PARSER_H diff --git a/KTp/wallet-interface.cpp b/KTp/wallet-interface.cpp index c5ec0d9..16b8991 100644 --- a/KTp/wallet-interface.cpp +++ b/KTp/wallet-interface.cpp @@ -1,294 +1,294 @@ /* * This file is part of telepathy-accounts-kcm * * Copyright (C) 2011 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "wallet-interface.h" #include "pending-wallet.h" #include "ktp-debug.h" class KTp::WalletInterfacePrivate : public QObject { Q_OBJECT public: WalletInterfacePrivate(); void ensureWalletIsReady(); QScopedPointer wallet; static const QLatin1String folderName; static const QLatin1String mapsPrefix; bool isOpening; private Q_SLOTS: void onWalletOpened(bool success); }; using KTp::WalletInterface; using KTp::WalletInterfacePrivate; const QLatin1String WalletInterfacePrivate::folderName = QLatin1String("telepathy-kde"); const QLatin1String WalletInterfacePrivate::mapsPrefix = QLatin1String("maps/"); void WalletInterfacePrivate::ensureWalletIsReady() { // If wallet was force-closed since last WalletInterface::openWallet(), // try to reopen it. if (!wallet || !wallet->isOpen()) { // If the wallet is not already being opened, we try to open it if (!isOpening) { isOpening = true; wallet.reset(KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(), 0, KWallet::Wallet::Asynchronous)); connect(wallet.data(), SIGNAL(walletOpened(bool)), SLOT(onWalletOpened(bool))); } } } WalletInterfacePrivate::WalletInterfacePrivate() : - wallet(NULL), + wallet(nullptr), isOpening(false) { ensureWalletIsReady(); } KTp::PendingWallet* WalletInterface::openWallet() { static KTp::WalletInterface s_instance; s_instance.d->ensureWalletIsReady(); return new PendingWallet(&s_instance); } void WalletInterfacePrivate::onWalletOpened(bool success) { if (!success) { qCWarning(KTP_COMMONINTERNALS) << "Couldn't open wallet"; } disconnect(wallet.data(), SIGNAL(walletOpened(bool)), this, SLOT(onWalletOpened(bool))); isOpening = false; } WalletInterface::WalletInterface(): d(new WalletInterfacePrivate) { } WalletInterface::~WalletInterface() { delete d; } bool WalletInterface::hasPassword(const Tp::AccountPtr &account) { if (d->wallet.isNull() || !d->wallet->hasFolder(d->folderName)) { return false; } d->wallet->setFolder(d->folderName); return d->wallet->hasEntry(account->uniqueIdentifier()); } QString WalletInterface::password(const Tp::AccountPtr &account) { if (d->wallet.isNull() || !d->wallet->hasFolder(d->folderName)) { return QString(); } d->wallet->setFolder(d->folderName); QString password; if (d->wallet->hasEntry(account->uniqueIdentifier())) { int rc = d->wallet->readPassword(account->uniqueIdentifier(), password); if (rc != 0) { password.clear(); qCWarning(KTP_COMMONINTERNALS) << "failed to read password from KWallet"; } } return password; } void WalletInterface::setPassword(const Tp::AccountPtr &account, const QString &password) { if (d->wallet.isNull()) { return; } if (!d->wallet->hasFolder(d->folderName)) { d->wallet->createFolder(d->folderName); } d->wallet->setFolder(d->folderName); d->wallet->writePassword(account->uniqueIdentifier(), password); setLastLoginFailed(account, false); //sync normally happens on close, but in this case we need it to happen /now/ as it needs to be synced before the auth-client starts d->wallet->sync(); } void WalletInterface::setLastLoginFailed(const Tp::AccountPtr &account, bool failed) { if (failed) { setEntry(account, QLatin1String("lastLoginFailed"), QLatin1String("true")); } else { if (hasEntry(account, QLatin1String("lastLoginFailed"))) { removeEntry(account, QLatin1String("lastLoginFailed")); } } } bool WalletInterface::lastLoginFailed(const Tp::AccountPtr &account) { if (d->wallet.isNull()) { return false; } return hasEntry(account, QLatin1String("lastLoginFailed")); } void WalletInterface::removePassword(const Tp::AccountPtr &account) { if (d->wallet.isNull() || !d->wallet->hasFolder(d->folderName)) { return; } d->wallet->setFolder(d->folderName); d->wallet->removeEntry(account->uniqueIdentifier()); d->wallet->sync(); } bool WalletInterface::hasEntry(const Tp::AccountPtr &account, const QString &key) { if (d->wallet.isNull() || !d->wallet->hasFolder(d->folderName)) { return false; } d->wallet->setFolder(d->folderName); QMap< QString, QString > map; if (d->wallet->hasEntry(d->mapsPrefix + account->uniqueIdentifier())) { int rc = d->wallet->readMap(d->mapsPrefix + account->uniqueIdentifier(), map); if (rc != 0) { qCWarning(KTP_COMMONINTERNALS) << "failed to read map from KWallet (probably it is not a map)"; return false; } } return map.contains(key); } QString WalletInterface::entry(const Tp::AccountPtr &account, const QString &key) { if (d->wallet.isNull() || !d->wallet->hasFolder(d->folderName)) { return QString(); } d->wallet->setFolder(d->folderName); QString value; QMap< QString, QString > map; if (d->wallet->hasEntry(d->mapsPrefix + account->uniqueIdentifier())) { int rc = d->wallet->readMap(d->mapsPrefix + account->uniqueIdentifier(), map); if (rc != 0) { qCWarning(KTP_COMMONINTERNALS) << "failed to read map from KWallet (probably it is not a map)"; return QString(); } } return map.value(key); } void WalletInterface::setEntry(const Tp::AccountPtr &account, const QString &key, const QString &value) { if (d->wallet.isNull()) { return; } if (! d->wallet->hasFolder(d->folderName)) { d->wallet->createFolder(d->folderName); } d->wallet->setFolder(d->folderName); QMap< QString, QString > map; if (d->wallet->hasEntry(d->mapsPrefix + account->uniqueIdentifier())) { int rc = d->wallet->readMap(d->mapsPrefix + account->uniqueIdentifier(), map); if (rc != 0) { qCWarning(KTP_COMMONINTERNALS) << "failed to read map from KWallet (probably it is not a map)"; return; } } map[key] = value; d->wallet->writeMap(d->mapsPrefix + account->uniqueIdentifier(), map); //sync normally happens on close, but in this case we need it to happen /now/ as it needs to be synced before the auth-client starts d->wallet->sync(); } void WalletInterface::removeEntry(const Tp::AccountPtr &account, const QString &key) { if (d->wallet.isNull() || !d->wallet->hasFolder(d->folderName)) { return; } d->wallet->setFolder(d->folderName); QMap< QString, QString > map; if (d->wallet->hasEntry(d->mapsPrefix + account->uniqueIdentifier())) { int rc = d->wallet->readMap(d->mapsPrefix + account->uniqueIdentifier(), map); if (rc != 0) { qCWarning(KTP_COMMONINTERNALS) << "failed to read map from KWallet (probably it is not a map)"; return; } } map.remove(key); if (!map.empty()) { d->wallet->writeMap(d->mapsPrefix + account->uniqueIdentifier(), map); } else { d->wallet->removeEntry(d->mapsPrefix + account->uniqueIdentifier()); } //sync normally happens on close, but in this case we need it to happen /now/ as it needs to be synced before the auth-client starts d->wallet->sync(); } void WalletInterface::removeAllEntries(const Tp::AccountPtr& account) { if (d->wallet.isNull() || !d->wallet->hasFolder(d->folderName)) { return; } d->wallet->setFolder(d->folderName); d->wallet->removeEntry(d->mapsPrefix + account->uniqueIdentifier()); } void WalletInterface::removeAccount(const Tp::AccountPtr& account) { removePassword(account); removeAllEntries(account); } bool WalletInterface::isOpen() { return (!d->wallet.isNull() && d->wallet->isOpen()); } KWallet::Wallet *WalletInterface::wallet() const { return d->wallet.data(); } #include "wallet-interface.moc" diff --git a/kaccounts/kaccounts-ktp-plugin.h b/kaccounts/kaccounts-ktp-plugin.h index 60d5bda..b401b21 100644 --- a/kaccounts/kaccounts-ktp-plugin.h +++ b/kaccounts/kaccounts-ktp-plugin.h @@ -1,58 +1,58 @@ /* Copyright (C) 2014 Martin Klapetek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KACCOUNTSKTPPLUGIN_H #define KACCOUNTSKTPPLUGIN_H #include namespace Tp { class PendingOperation; } namespace Accounts { class Manager; } class KAccountsKTpPlugin : public KAccountsDPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.kde.kaccounts.DPlugin") Q_INTERFACES(KAccountsDPlugin) public: - KAccountsKTpPlugin(QObject *parent = 0); + KAccountsKTpPlugin(QObject *parent = nullptr); ~KAccountsKTpPlugin() override; public Q_SLOTS: void onAccountCreated(const Accounts::AccountId accountId, const Accounts::ServiceList &serviceList) override; void onAccountRemoved(const Accounts::AccountId accountId) override; void onServiceEnabled(const Accounts::AccountId accountId, const Accounts::Service &service) override; void onServiceDisabled(const Accounts::AccountId accountId, const Accounts::Service &service) override; private Q_SLOTS: void onAccountManagerReady(Tp::PendingOperation *op); void onAccountSynced(); void onStorageProviderRetrieved(Tp::PendingOperation *op); private: class Private; Private * const d; }; #endif // KACCOUNTSKTPPLUGIN_H diff --git a/kpeople/uiplugins/chatplugin/chatlistviewdelegate.h b/kpeople/uiplugins/chatplugin/chatlistviewdelegate.h index 9d2bfe4..b524d65 100644 --- a/kpeople/uiplugins/chatplugin/chatlistviewdelegate.h +++ b/kpeople/uiplugins/chatplugin/chatlistviewdelegate.h @@ -1,40 +1,40 @@ /* Copyright 2014 Nilesh Suthar This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CHATLISTVIEWDELEGATE_H #define CHATLISTVIEWDELEGATE_H #include class QPainter; class ChatListviewDelegate : public QStyledItemDelegate { public: - ChatListviewDelegate(QWidget *parent = 0) : QStyledItemDelegate(parent) {} + ChatListviewDelegate(QWidget *parent = nullptr) : QStyledItemDelegate(parent) {} enum dataRole { senderAliasRole = Qt::UserRole + 100, messageRole, messageTimeRole }; void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; }; #endif // CHATLISTVIEWDELEGATE_H diff --git a/kpeople/uiplugins/imdetailswidget.cpp b/kpeople/uiplugins/imdetailswidget.cpp index e75c5ea..c7bf7c2 100644 --- a/kpeople/uiplugins/imdetailswidget.cpp +++ b/kpeople/uiplugins/imdetailswidget.cpp @@ -1,89 +1,89 @@ /* Copyright (C) 2013 David Edmundson This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "imdetailswidget.h" #include #include #include #include #include #include #include #include #include #include K_PLUGIN_FACTORY_WITH_JSON( ImDetailsWidgetFactory, "imdetailswidgetplugin.json", registerPlugin(); ) K_EXPORT_PLUGIN( ImDetailsWidgetFactory("imdetailswidgetplugin", "ktp-common-internals")) using namespace KPeople; ImDetailsWidget::ImDetailsWidget(QObject* parent, const QVariantList& args) { Q_UNUSED(parent); Q_UNUSED(args); } QString ImDetailsWidget::label() const { return i18n("IM"); } QWidget* ImDetailsWidget::createDetailsWidget(const KPeople::PersonData &person, QWidget *parent) const { QWidget *root = new QWidget(parent); QGridLayout *layout = new QGridLayout(root); root->setLayout(layout); int row = 0; for(const QString &contactId: person.contactUris()) { if (!contactId.startsWith(QStringLiteral("ktp://"))) { continue; } PersonData contact(contactId); const QString tpcontactId = contact.contactCustomProperty(QStringLiteral("telepathy-contactId")).toString(); const QString accountPath = contact.contactCustomProperty(QStringLiteral("telepathy-accountPath")).toString(); //probably unused till we fix everything properly Tp::AccountPtr account = KTp::accountManager()->accountForObjectPath(accountPath); if (!account) { continue; } QLabel *iconLabel = new QLabel(root); const int iconSize = root->style()->pixelMetric(QStyle::PM_SmallIconSize); iconLabel->setPixmap(QIcon::fromTheme(account->iconName()).pixmap(iconSize, iconSize)); layout->addWidget(iconLabel, row, 0); QLabel *label = new QLabel(tpcontactId, root); label->setTextInteractionFlags(Qt::TextSelectableByMouse); layout->addWidget(label, row, 1); row++; //FUTURE - presence here + blocked + presence subscription } if (layout->count()) { return root; } else { - return 0; + return nullptr; } } #include "imdetailswidget.moc" diff --git a/otr-proxy/KTpProxy/otr-manager.cpp b/otr-proxy/KTpProxy/otr-manager.cpp index ee65d64..3c8cb3e 100644 --- a/otr-proxy/KTpProxy/otr-manager.cpp +++ b/otr-proxy/KTpProxy/otr-manager.cpp @@ -1,621 +1,621 @@ /*************************************************************************** * Copyright (C) 2014 by Marcin Ziemiński * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA* ***************************************************************************/ #include "otr-manager.h" #include "otr-utils.h" #include "otr-constants.h" #include "ktp-proxy-debug.h" #include "KTp/OTR/constants.h" namespace OTR { namespace { /** OTR ops functions ------------------------------------------------------------------------- */ OtrlPolicy policy(void *opdata, ConnContext *context) { Q_UNUSED(context); Session *session = reinterpret_cast(opdata); return session->parent()->getPolicy(); } void create_privkey(void *opdata, const char *accountname, const char *protocol) { Q_UNUSED(accountname); Q_UNUSED(protocol); qCDebug(KTP_PROXY); Session *session = reinterpret_cast(opdata); session->parent()->createNewPrivateKey(session); } int is_logged_in(void *opdata, const char *accountname, const char *protocol, const char *recipient) { Q_UNUSED(accountname); Q_UNUSED(protocol); Q_UNUSED(recipient); Session *session = reinterpret_cast(opdata); return session->recipientStatus(); } void inject_message(void *opdata, const char *accountname, const char *protocol, const char *recipient, const char *message) { Q_UNUSED(accountname); Q_UNUSED(protocol); Q_UNUSED(recipient); Message msg; msg.setText(QLatin1String(message)); msg.setType(Tp::ChannelTextMessageTypeNormal); msg.setDirection(MessageDirection::TO_PEER); Session *session = reinterpret_cast(opdata); session->handleMessage(msg); } void update_context_list(void *opdata) { Q_UNUSED(opdata); // FIXME - all changes in state are caught gone_secure/gone_insecure } void new_fingerprint(void *opdata, OtrlUserState us, const char *accountname, const char *protocol, const char *username, unsigned char fingerprint[20]) { Q_UNUSED(us); Q_UNUSED(accountname); Q_UNUSED(protocol); Q_UNUSED(username); Session *session = reinterpret_cast(opdata); session->onNewFingerprintReceived(OTR::utils::humanReadable(fingerprint)); } void write_fingerprints(void *opdata) { Session *session = reinterpret_cast(opdata); session->parent()->saveFingerprints(session); } void gone_secure(void *opdata, ConnContext *context) { Session *session = reinterpret_cast(opdata); session->onTrustLevelChanged(context); } void gone_insecure(void *opdata, ConnContext *context) { Session *session = reinterpret_cast(opdata); session->onTrustLevelChanged(context); } void still_secure(void *opdata, ConnContext *context, int is_reply) { Q_UNUSED(context); Q_UNUSED(is_reply); Session *session = reinterpret_cast(opdata); session->onSessionRefreshed(); } int max_message_size(void *opdata, ConnContext *context) { Q_UNUSED(context); Session *session = reinterpret_cast(opdata); return session->maxMessageSize(); } const char* otr_error_message(void *opdata, ConnContext *context, OtrlErrorCode err_code) { Q_UNUSED(opdata); - char *err_msg = 0; + char *err_msg = nullptr; switch (err_code) { case OTRL_ERRCODE_NONE: break; case OTRL_ERRCODE_ENCRYPTION_ERROR: { QString message = QLatin1String("Error occurred encrypting message."); err_msg = new char[message.length() + 1]; err_msg[message.length()] = 0; memcpy(err_msg, message.toUtf8().data(), message.length()); break; } case OTRL_ERRCODE_MSG_NOT_IN_PRIVATE: if (context) { QString message = QString::fromLatin1("You sent encrypted data to %1, who wasn't expecting it."). arg(QLatin1String(context->accountname)); err_msg = new char[message.length() + 1]; err_msg[message.length()] = 0; memcpy(err_msg, message.toUtf8().data(), message.length()); } break; case OTRL_ERRCODE_MSG_UNREADABLE: { QString message = QLatin1String("You transmitted an unreadable encrypted message."); err_msg = new char[message.length() + 1]; err_msg[message.length()] = 0; memcpy(err_msg, message.toUtf8().data(), message.length()); break; } case OTRL_ERRCODE_MSG_MALFORMED: { QString message = QLatin1String("You transmitted a malformed data message."); err_msg = new char[message.length() + 1]; err_msg[message.length()] = 0; memcpy(err_msg, message.toUtf8().data(), message.length()); break; } } return err_msg; } void otr_error_message_free(void *opdata, const char *err_msg) { Q_UNUSED(opdata); if(err_msg) { delete [] const_cast(err_msg); } } const char* resent_msg_prefix(void *opdata, ConnContext *context) { Q_UNUSED(opdata); Q_UNUSED(context); return "[resent]"; } void resent_msg_prefix_free(void *opdata, const char *prefix) { Q_UNUSED(opdata); Q_UNUSED(prefix); return; } void handle_smp_event(void *opdata, OtrlSMPEvent smp_event, ConnContext *context, unsigned short progress_percent, char *question) { Q_UNUSED(progress_percent); Session *session = reinterpret_cast(opdata); qCDebug(KTP_PROXY) << session->context().accountName; switch (smp_event) { case OTRL_SMPEVENT_NONE: break; case OTRL_SMPEVENT_ASK_FOR_SECRET: session->onSMPQuery(QLatin1String("")); break; case OTRL_SMPEVENT_ASK_FOR_ANSWER: session->onSMPQuery(QLatin1String(question)); break; case OTRL_SMPEVENT_IN_PROGRESS: session->onSMPInProgress(); break; case OTRL_SMPEVENT_SUCCESS: session->onSMPFinished(true); session->onTrustLevelChanged(); break; case OTRL_SMPEVENT_FAILURE: session->onSMPFinished(false); session->onTrustLevelChanged(); break; case OTRL_SMPEVENT_ABORT: session->abortSMPAuthentiaction(context); session->onSMPAborted(); break; case OTRL_SMPEVENT_CHEATED: session->abortSMPAuthentiaction(context); session->onSMPCheated(); break; case OTRL_SMPEVENT_ERROR: session->abortSMPAuthentiaction(context); session->onSMPError(); break; } } void handle_msg_event(void *opdata, OtrlMessageEvent msg_event, ConnContext *context, const char *message, gcry_error_t err) { Message msg; msg.setType(Tp::ChannelTextMessageTypeNotice); msg.setOTRevent(msg_event); switch (msg_event) { case OTRL_MSGEVENT_NONE: return; case OTRL_MSGEVENT_ENCRYPTION_REQUIRED: msg.setText(QString::fromLatin1("You attempted to send an unencrypted message to %1.") .arg(QLatin1String(context->username))); msg.setDirection(MessageDirection::INTERNAL); break; case OTRL_MSGEVENT_ENCRYPTION_ERROR: msg.setText(QString::fromLatin1("An error occurred when encrypting your message. " "The message was not sent.")); msg.setDirection(MessageDirection::INTERNAL); break; case OTRL_MSGEVENT_CONNECTION_ENDED: msg.setText(QString::fromLatin1("%1 has already closed his/her private connection to you. " "Your message was not sent. " "Either end your private conversation, or restart it.") .arg(QLatin1String(context->username))); msg.setDirection(MessageDirection::INTERNAL); break; case OTRL_MSGEVENT_SETUP_ERROR: if(!err) { err = GPG_ERR_INV_VALUE; } switch (gcry_err_code(err)) { case GPG_ERR_INV_VALUE: { msg.setOTRheader(OTR_ERROR_HEADER, QLatin1String("Malformed message received")); msg.setText(QLatin1String("Error setting up private conversation: " "Malformed message received")); break; } default: { msg.setOTRheader(OTR_ERROR_HEADER, QLatin1String(gcry_strerror(err))); msg.setText(QString::fromLatin1("Error setting up private conversation: %1") .arg(QLatin1String(gcry_strerror(err)))); break; } } msg.setDirection(MessageDirection::INTERNAL); break; case OTRL_MSGEVENT_MSG_REFLECTED: msg.setText(QLatin1String("We are receiving our own OTR messages. " "You are either trying to talk to yourself, " "or someone is reflecting your messages back at you.")); msg.setDirection(MessageDirection::INTERNAL); break; case OTRL_MSGEVENT_MSG_RESENT: msg.setText(QString::fromLatin1("The last message to %1 was resent.") .arg(QLatin1String(context->username))); msg.setDirection(MessageDirection::INTERNAL); break; case OTRL_MSGEVENT_RCVDMSG_NOT_IN_PRIVATE: msg.setText(QString::fromLatin1("The encrypted message received from %1 is unreadable, " "as you are not currently communicating privately.") .arg(QLatin1String(context->username))); msg.setDirection(MessageDirection::FROM_PEER); break; case OTRL_MSGEVENT_RCVDMSG_UNREADABLE: msg.setText(QString::fromLatin1("We received an unreadable encrypted message from %1.") .arg(QLatin1String(context->username))); msg.setDirection(MessageDirection::INTERNAL); break; case OTRL_MSGEVENT_RCVDMSG_MALFORMED: msg.setText(QString::fromLatin1("We received a malformed data message from %1.") .arg(QLatin1String(context->username))); msg.setDirection(MessageDirection::INTERNAL); break; case OTRL_MSGEVENT_LOG_HEARTBEAT_RCVD: return; case OTRL_MSGEVENT_LOG_HEARTBEAT_SENT: break; case OTRL_MSGEVENT_RCVDMSG_GENERAL_ERR: msg.setOTRheader(OTR_ERROR_HEADER, QLatin1String(message)); msg.setText(QLatin1String(message)); msg.setDirection(MessageDirection::INTERNAL); break; case OTRL_MSGEVENT_RCVDMSG_UNENCRYPTED: msg.setOTRheader(OTR_UNENCRYPTED_MESSAGE_HEADER, QLatin1String(message)); msg.setText(QString::fromLatin1("The following message received from %1 was not encrypted: [%2]") .arg(QLatin1String(context->username), QLatin1String(message))); msg.setDirection(MessageDirection::FROM_PEER); break; case OTRL_MSGEVENT_RCVDMSG_UNRECOGNIZED: break; case OTRL_MSGEVENT_RCVDMSG_FOR_OTHER_INSTANCE: msg.setText(QString::fromLatin1("%1 has sent an encrypted message intended for a different session. " "If you are logged in multiple times, another session may have received the message.") .arg(QLatin1String(context->username))); msg.setDirection(MessageDirection::FROM_PEER); break; } Session *session = reinterpret_cast(opdata); session->handleMessage(msg); } void create_instag(void *opdata, const char *accountname, const char *protocol) { Q_UNUSED(accountname); Q_UNUSED(protocol); Session *session = reinterpret_cast(opdata); session->parent()->createInstag(session); } void timer_control(void *opdata, unsigned int interval) { Session *session = reinterpret_cast(opdata); session->userStateBox()->setInterval(interval); } } /* anonymous namespace */ /** OTR ops struct ---------------------------------------------------------------------------- */ namespace global { const OtrlMessageAppOps appOps = { policy, create_privkey, is_logged_in, inject_message, update_context_list, new_fingerprint, write_fingerprints, gone_secure, gone_insecure, still_secure, max_message_size, - NULL, /* account_name */ - NULL, /* account_name_free */ - NULL, /* received symkey */ + nullptr, /* account_name */ + nullptr, /* account_name_free */ + nullptr, /* received symkey */ otr_error_message, otr_error_message_free, resent_msg_prefix, resent_msg_prefix_free, handle_smp_event, handle_msg_event, create_instag, - NULL, /* convert_data */ - NULL, /* convert_data_free */ + nullptr, /* convert_data */ + nullptr, /* convert_data_free */ timer_control }; } /* global namespace */ /** Manager implementation -------------------------------------------------------------------- */ Manager::Manager(Config *otrConfig) : config(otrConfig) { } UserStateBox* Manager::getUserState(const QString &accountId) { auto usIt = userStates.find(accountId); if(usIt == userStates.end()) { // initiate new userstate OtrlUserState userstate = otrl_userstate_create(); QString path = config->saveLocation() + accountId + QLatin1String(".privkeys"); otrl_privkey_read(userstate, path.toLocal8Bit()); path = config->saveLocation() + accountId + QLatin1String(".fingerprints"); - otrl_privkey_read_fingerprints(userstate, path.toLocal8Bit(), NULL, NULL); + otrl_privkey_read_fingerprints(userstate, path.toLocal8Bit(), nullptr, nullptr); path = config->saveLocation() + accountId + QLatin1String(".instags"); otrl_instag_read(userstate, path.toLocal8Bit()); UserStateBoxPtr usPtr(new UserStateBox(userstate)); userStates.insert(accountId, usPtr); return usPtr.data(); } else { return usIt->data(); } } OtrlPolicy Manager::getPolicy() const { return config->getPolicy(); } void Manager::setPolicy(OtrlPolicy policy) { config->setPolicy(policy); } void Manager::createNewPrivateKey(Session *session) { const QString path = config->saveLocation() + session->context().accountId + QLatin1String(".privkeys"); otrl_privkey_generate(session->userStateBox()->userState(), path.toLocal8Bit(), session->context().accountName.toLocal8Bit(), session->context().protocol.toLocal8Bit()); } KeyGenerationWorker* Manager::createNewPrivateKey(const QString &accountId, const QString &accountName) { const QString path = config->saveLocation() + accountId + QLatin1String(".privkeys"); return new KeyGenerationWorker( accountId, accountName, utils::protocolFromAccountId(accountId), path, getUserState(accountId)->userState()); } QString Manager::getFingerprintFor(const QString &accountId, const QString &accountName) { OtrlUserState userState = getUserState(accountId)->userState(); unsigned char ourRawHash[20]; unsigned char *res = otrl_privkey_fingerprint_raw( userState, ourRawHash, accountName.toLocal8Bit(), OTR::utils::protocolFromAccountId(accountId).toLocal8Bit()); if(res == nullptr) { return QLatin1String(""); } else { return utils::humanReadable(ourRawHash); } } void Manager::saveFingerprints(const QString &accountId) { OtrlUserState userState = getUserState(accountId)->userState(); const QString path = config->saveLocation() + accountId + QLatin1String(".fingerprints"); otrl_privkey_write_fingerprints(userState, path.toLocal8Bit()); } void Manager::saveFingerprints(Session *session) { const QString path = config->saveLocation() + session->context().accountId + QLatin1String(".fingerprints"); otrl_privkey_write_fingerprints(session->userStateBox()->userState(), path.toLocal8Bit()); } void Manager::createInstag(Session *session) { const QString path = config->saveLocation() + session->context().accountId + QLatin1String(".instags"); otrl_instag_generate(session->userStateBox()->userState(), path.toLocal8Bit(), session->context().accountName.toLocal8Bit(), session->context().protocol.toLocal8Bit()); } TrustFpResult Manager::trustFingerprint(const SessionContext &ctx, Fingerprint *fingerprint, bool trust) { if(fingerprint == nullptr) { return TrustFpResult::NO_SUCH_FINGERPRINT; } UserStateBox* usBox = getUserState(ctx.accountId); if(trust) { otrl_context_set_trust(fingerprint, "VERIFIED"); } else { - otrl_context_set_trust(fingerprint, NULL); + otrl_context_set_trust(fingerprint, nullptr); } const QString path = config->saveLocation() + ctx.accountId + QLatin1String(".fingerprints"); otrl_privkey_write_fingerprints(usBox->userState(), path.toLocal8Bit()); return TrustFpResult::OK; } KTp::FingerprintInfoList Manager::getKnownFingerprints(const QString &accountId) { KTp::FingerprintInfoList fingerprints; for(ConnContext *context = getUserState(accountId)->userState()->context_root; context != nullptr; context = context->next) { for(Fingerprint *fingerprint = context->fingerprint_root.next; fingerprint != nullptr; fingerprint = fingerprint->next) { const QString username = QLatin1String(context->username); const QString hrFp = utils::humanReadable(fingerprint->fingerprint); const bool trusted = otrl_context_is_fingerprint_trusted(fingerprint); const bool used = utils::isFingerprintInUse(fingerprint); fingerprints << KTp::FingerprintInfo { username, hrFp, trusted, used }; } } return fingerprints; } bool Manager::trustFingerprint(const QString &accountId, const QString &contactName, const QString &fp, bool trust) { Fingerprint *fingerprint = utils::findFingerprint( getUserState(accountId)->userState(), fp, contactName); if(fingerprint != nullptr) { if(trust) { otrl_context_set_trust(fingerprint, "VERIFIED"); } else { - otrl_context_set_trust(fingerprint, NULL); + otrl_context_set_trust(fingerprint, nullptr); } Q_EMIT fingerprintTrusted(accountId, fp, trust); return true; } return false; } bool Manager::forgetFingerprint(const QString &accountId, const QString &contactName, const QString &fingerprint) { Fingerprint *fp = utils::findFingerprint( getUserState(accountId)->userState(), fingerprint, contactName); if(fp != nullptr && !utils::isFingerprintInUse(fp)) { otrl_context_forget_fingerprint(fp, 1); saveFingerprints(accountId); return true; } return false; } KeyGenerationWorker::KeyGenerationWorker( const QString &accountId, const QString &accountName, const QString &protocol, const QString &path, OtrlUserState userState) : accountId(accountId), accountName(accountName), protocol(protocol), path(path), userState(userState), err(0) { } gcry_error_t KeyGenerationWorker::prepareCreation() { return err = otrl_privkey_generate_start(userState, accountName.toLocal8Bit(), protocol.toLocal8Bit(), &newKey); } void KeyGenerationWorker::calculate() { if(!err) { err = otrl_privkey_generate_calculate(newKey); } Q_EMIT finished(); } gcry_error_t KeyGenerationWorker::error() const { return err; } gcry_error_t KeyGenerationWorker::finalizeCreation() { if(!err) { return err = otrl_privkey_generate_finish(userState, newKey, path.toLocal8Bit()); } else { return err; } } } /* namespace OTR */ diff --git a/otr-proxy/KTpProxy/otr-message.cpp b/otr-proxy/KTpProxy/otr-message.cpp index 9507f46..70f7869 100644 --- a/otr-proxy/KTpProxy/otr-message.cpp +++ b/otr-proxy/KTpProxy/otr-message.cpp @@ -1,195 +1,195 @@ /*************************************************************************** * Copyright (C) 2014 by Marcin Ziemiński * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA* ***************************************************************************/ #include "otr-message.h" #include "KTp/OTR/constants.h" namespace OTR { Message::Message() : dir(MessageDirection::TO_PEER) { message << Tp::MessagePart() << Tp::MessagePart(); setType(Tp::ChannelTextMessageTypeNormal); } Message::Message(const Tp::MessagePartList &message) : dir(MessageDirection::TO_PEER), message(message) { while(this->message.size() < 2) { this->message << Tp::MessagePart(); } if(!this->message[0].contains(QLatin1String("message-type"))) { setType(Tp::ChannelTextMessageTypeNormal); } } const Tp::MessagePartList& Message::parts() const { return message; } QString Message::text() const { auto it = message[1].find(QLatin1String("content")); if(it == message[1].end()) { return QLatin1String(""); } else { return it->variant().toString(); } } void Message::setText(const QString &text, const QString &contentType) { message[1].insert(QLatin1String("content-type"), QDBusVariant(contentType)); message[1].insert(QLatin1String("content"), QDBusVariant(text)); } QString Message::contentType() const { auto it = message[1].find(QLatin1String("content-type")); if(it == message[1].end()) { return QLatin1String(""); } else { return it->variant().toString(); } } void Message::setType(Tp::ChannelTextMessageType msgType) { message[0].insert(QLatin1String("message-type"), QDBusVariant(msgType)); } Tp::ChannelTextMessageType Message::type() const { return static_cast(message[0][QLatin1String("message-type")].variant().toUInt(nullptr)); } bool Message::isOTRmessage() const { return otrl_proto_message_type(text().toLocal8Bit()) != OTRL_MSGTYPE_NOTOTR; } MessageDirection Message::direction() const { return dir; } void Message::setDirection(MessageDirection direction) { dir = direction; } bool Message::isOTRevent() const { return message[0].contains(OTR_MESSAGE_EVENT_HEADER); } void Message::setOTRevent(OtrlMessageEvent msgEvent) { message[0].insert(OTR_MESSAGE_EVENT_HEADER, QDBusVariant(static_cast(msgEvent))); } OtrlMessageEvent Message::getOTRevent() const { if(isOTRevent()) { return static_cast(message[0][OTR_MESSAGE_EVENT_HEADER].variant().toUInt(nullptr)); } else { return OTRL_MSGEVENT_NONE; } } void Message::setOTRheader(const QString &header, const QString &text) { message[0].insert(header, QDBusVariant(text)); } QString Message::getOTRheader(const QString &header) { auto it = message[0].find(header); if(it == message[0].end()) { return QLatin1String(""); } else { return it->variant().toString(); } } void Message::setTimestamp(qint64 timestamp) { message[0].insert(QLatin1String("message-sent"), QDBusVariant(timestamp)); } qint64 Message::getTimestamp() const { auto it = message[0].find(QLatin1String("message-sent")); if(it == message[0].end()) { return 0; } else { - return it->variant().toLongLong(NULL); + return it->variant().toLongLong(nullptr); } } void Message::setSenderId(const QString &senderId) { message[0].insert(QLatin1String("message-sender-id"), QDBusVariant(senderId)); } QString Message::getSenderId() const { auto it = message[0].find(QLatin1String("message-sender-id")); if(it == message[0].end()) { return QLatin1String(""); } else { return it->variant().toString(); } } void Message::setSender(uint sender) { message[0].insert(QLatin1String("message-sender"), QDBusVariant(sender)); } uint Message::getSender() const { auto it = message[0].find(QLatin1String("message-sender")); if(it == message[0].end()) { return 0; } else { - return it->variant().toUInt(NULL); + return it->variant().toUInt(nullptr); } } void Message::setToken(const QString &token) { message[0].insert(QLatin1String("message-token"), QDBusVariant(token)); } QString Message::getToken() const { auto it = message[0].find(QLatin1String("message-sender")); if(it == message[0].end()) { return QLatin1String(""); } else { return it->variant().toString(); } } } /* namespace OTR */ diff --git a/otr-proxy/KTpProxy/otr-session.cpp b/otr-proxy/KTpProxy/otr-session.cpp index 1e1e0f7..f970429 100644 --- a/otr-proxy/KTpProxy/otr-session.cpp +++ b/otr-proxy/KTpProxy/otr-session.cpp @@ -1,419 +1,419 @@ /*************************************************************************** * Copyright (C) 2014 by Marcin Ziemiński * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA* ***************************************************************************/ #include "otr-session.h" #include "otr-manager.h" #include "otr-message.h" #include "otr-utils.h" #include "otr-proxy-channel-adaptee.h" #include "KTp/OTR/constants.h" extern "C" { #include #include #include #include } namespace OTR { // -------- UserStateBox -------------------------------------------- UserStateBox::UserStateBox(OtrlUserState userState) : us(userState) { uint interval = otrl_message_poll_get_default_interval(us); QObject::connect(&periodicTimer, SIGNAL(timeout()), SLOT(otrlMessagePoll())); periodicTimer.start(interval * 1000); } UserStateBox::~UserStateBox() { otrl_userstate_free(us); } OtrlUserState UserStateBox::userState() { return us; } void UserStateBox::setInterval(uint interval) { if(interval) { periodicTimer.start(interval * 1000); } else { periodicTimer.stop(); } } void UserStateBox::otrlMessagePoll() { - otrl_message_poll(us, 0, 0); + otrl_message_poll(us, nullptr, nullptr); } // -------- Session ------------------------------------------------- Session::Session(const SessionContext &ctx, Manager *parent) : instance(OTRL_INSTAG_BEST), ctx(ctx), pr(parent) { userstate = pr->getUserState(ctx.accountId); connect(parent, SIGNAL(fingerprintTrusted(const QString&, const QString&, bool)), SLOT(onFingerprintTrusted(const QString&, const QString&, bool))); } TrustLevel Session::trustLevel() const { return OTR::utils::getTrustLevel(ctx, userstate->userState(), instance); } UserStateBox* Session::userStateBox() const { return userstate; } Manager* Session::parent() const { return pr; } const SessionContext& Session::context() const { return ctx; } Fingerprint* Session::getFingerprint() const { ConnContext *context = findContext(); if(context && context->active_fingerprint) { return context->active_fingerprint; } else { return nullptr; } } ConnContext* Session::findContext() const { return otrl_context_find(userstate->userState(), ctx.recipientName.toLocal8Bit(), ctx.accountName.toLocal8Bit(), ctx.protocol.toLocal8Bit(), - instance, 0, NULL, NULL, NULL); + instance, 0, nullptr, nullptr, nullptr); } void Session::onFingerprintTrusted(const QString &accountId, const QString &fingerprint, bool trusted) { Q_UNUSED(trusted); if(accountId == ctx.accountId && fingerprint == remoteFingerprint()) { onTrustLevelChanged(); } } QString Session::remoteFingerprint() const { Fingerprint *fp = getFingerprint(); if(fp) { return utils::humanReadable(fp->fingerprint); } else { return QLatin1String(""); } } QString Session::localFingerprint() const { return parent()->getFingerprintFor(ctx.accountId, ctx.accountName); } void Session::forceUnencrypted() { if(trustLevel() == TrustLevel::NOT_PRIVATE) { return; } ConnContext *context = findContext(); otrl_context_force_plaintext(context); } Message Session::startSession() { Message msg; char *message = otrl_proto_default_query_msg(ctx.accountName.toLocal8Bit(), pr->getPolicy()); msg.setText(QLatin1String(message)); msg.setType(Tp::ChannelTextMessageTypeNormal); msg.setDirection(MessageDirection::TO_PEER); otrl_message_free(message); return msg; } void Session::stopSession() { otrl_message_disconnect( userstate->userState(), &global::appOps, this, ctx.accountName.toLocal8Bit(), ctx.protocol.toLocal8Bit(), ctx.recipientName.toLocal8Bit(), instance); onTrustLevelChanged(); } CryptResult Session::encrypt(Message &message) { if(otrl_proto_message_type(message.text().toLocal8Bit()) == OTRL_MSGTYPE_NOTOTR) { - char *encMessage = 0; + char *encMessage = nullptr; ConnContext *context; int err = otrl_message_sending( userstate->userState(), &global::appOps, this, ctx.accountName.toLocal8Bit(), ctx.protocol.toLocal8Bit(), ctx.recipientName.toLocal8Bit(), instance, message.text().toLocal8Bit(), - NULL, + nullptr, &encMessage, OTRL_FRAGMENT_SEND_ALL_BUT_LAST, &context, - NULL, - NULL); + nullptr, + nullptr); if(err) { return CryptResult::ERROR; } else if(encMessage != nullptr) { if(message.contentType().isEmpty()) { message.setText(QString::fromLocal8Bit(encMessage)); } else { message.setText(QString::fromLocal8Bit(encMessage), message.contentType()); } message.setType(Tp::ChannelTextMessageTypeNormal); if(context->active_fingerprint != nullptr) { const QString hrFingerprint = OTR::utils::humanReadable(context->active_fingerprint->fingerprint); message.setOTRheader(OTR_REMOTE_FINGERPRINT_HEADER, hrFingerprint); } otrl_message_free(encMessage); return CryptResult::CHANGED; } } return CryptResult::UNCHANGED; } CryptResult Session::decrypt(Message &message) { CryptResult result = CryptResult::OTR; char *decMsg = nullptr; OtrlTLV *tlvs = nullptr; ConnContext *context = nullptr; bool isFinished = false; int ignore = otrl_message_receiving( userstate->userState(), &global::appOps, this, ctx.accountName.toLocal8Bit(), ctx.protocol.toLocal8Bit(), ctx.recipientName.toLocal8Bit(), message.text().toLocal8Bit(), &decMsg, &tlvs, - &context, NULL, NULL); + &context, nullptr, nullptr); if(otrl_tlv_find(tlvs, OTRL_TLV_DISCONNECTED) != nullptr) { isFinished = true; } otrl_tlv_free(tlvs); if(!ignore) { if(decMsg != nullptr) { if(message.contentType().isEmpty()) { message.setText(QString::fromLocal8Bit(decMsg)); } else { message.setText(QString::fromLocal8Bit(decMsg), message.contentType()); } if(context->active_fingerprint != nullptr) { const QString hrFingerprint = OTR::utils::humanReadable(context->active_fingerprint->fingerprint); message.setOTRheader(OTR_REMOTE_FINGERPRINT_HEADER, hrFingerprint); } result = CryptResult::CHANGED; } else { result = CryptResult::UNCHANGED; } } else { result = CryptResult::OTR; } if(decMsg != nullptr) { otrl_message_free(decMsg); } if(isFinished) { onTrustLevelChanged(); } return result; } void Session::initSMPQuery(const QString &question, const QString &secret) { otrl_message_initiate_smp_q(userstate->userState(), &global::appOps, this, findContext(), (const char*)question.toLocal8Bit().data(), (unsigned char*)secret.toLocal8Bit().data(), secret.length()); } void Session::initSMPSecret(const QString &secret) { otrl_message_initiate_smp(userstate->userState(), &global::appOps, this, findContext(), (unsigned char*)secret.toLocal8Bit().data(), secret.length()); } void Session::abortSMPAuthentiaction(ConnContext *context) { - if(context == NULL) { + if(context == nullptr) { context = findContext(); } otrl_message_abort_smp(userstate->userState(), &global::appOps, this, context); } void Session::respondSMPAuthentication(const QString &answer) { otrl_message_respond_smp(userstate->userState(), &global::appOps, this, findContext(), (unsigned char*)answer.toLocal8Bit().data(), answer.length()); } TrustFpResult Session::trustFingerprint(bool trust) { Fingerprint* fp = getFingerprint(); if(fp != nullptr) { TrustFpResult res = pr->trustFingerprint(ctx, fp, trust); if(res == TrustFpResult::OK && trustLevel() != TrustLevel::FINISHED) { onTrustLevelChanged(); } return res; } else { return TrustFpResult::NO_SUCH_FINGERPRINT; } } void Session::onTrustLevelChanged(const ConnContext *context) { if(context != nullptr) { instance = context->their_instance; } Q_EMIT trustLevelChanged(trustLevel()); } void Session::onSessionRefreshed() { Q_EMIT sessionRefreshed(); } void Session::onNewFingerprintReceived(const QString &fingerprint) { Q_EMIT newFingerprintReceived(fingerprint); } void Session::onSMPFinished(bool success) { Q_EMIT authenticationConcluded(success); } void Session::onSMPInProgress() { Q_EMIT authenticationInProgress(); } void Session::onSMPError() { Q_EMIT authenticationError(); } void Session::onSMPAborted() { Q_EMIT authenticationAborted(); } void Session::onSMPCheated() { Q_EMIT authenticationCheated(); } void Session::onSMPQuery(const QString &question) { Q_EMIT authenticationRequested(question); } // -------- ProxySession -------------------------------------------- ProxySession::ProxySession(OtrProxyChannel::Adaptee *pca, const SessionContext &ctx, Manager *parent) : Session(ctx, parent), pca(pca) { } void ProxySession::handleMessage(const Message &message) { pca->processOTRmessage(message); } int ProxySession::recipientStatus() const { if(pca->channel()->hasChatStateInterface()) { switch(pca->channel()->chatState(pca->channel()->targetContact())) { case Tp::ChannelChatStateGone: return 0; default: return 1; } } else { return -1; } } unsigned int ProxySession::maxMessageSize() const { // FIXME cannot determine maximum message size with Telepathy return 0; } } /* namespace OTR */ diff --git a/otr-proxy/KTpProxy/otr-session.h b/otr-proxy/KTpProxy/otr-session.h index 0b7ab0c..15a55f7 100644 --- a/otr-proxy/KTpProxy/otr-session.h +++ b/otr-proxy/KTpProxy/otr-session.h @@ -1,151 +1,151 @@ /*************************************************************************** * Copyright (C) 2014 by Marcin Ziemiński * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA* ***************************************************************************/ #ifndef KTP_PROXY_OTR_SESSION_HEADER #define KTP_PROXY_OTR_SESSION_HEADER #include "otr-message.h" #include "otr-constants.h" #include "otr-proxy-channel.h" #include "otr-utils.h" #include #include extern "C" { #include #include } namespace OTR { class Manager; class UserStateBox : public QObject { Q_OBJECT public: UserStateBox(OtrlUserState userState); ~UserStateBox() override; OtrlUserState userState(); /** if zero timer is stopped */ void setInterval(uint interval); private Q_SLOTS: void otrlMessagePoll(); private: OtrlUserState us; QTimer periodicTimer; }; typedef QSharedPointer UserStateBoxPtr; class Session : public QObject { Q_OBJECT public: Session(const SessionContext &context, Manager *parent); ~Session() override = default; UserStateBox* userStateBox() const; Manager* parent() const; TrustLevel trustLevel() const; const SessionContext& context() const; QString remoteFingerprint() const; QString localFingerprint() const; /** forces OTR session into plain text state */ void forceUnencrypted(); /** Returns OTR init message */ Message startSession(); void stopSession(); CryptResult encrypt(Message &message); CryptResult decrypt(Message &message); void initSMPQuery(const QString &question, const QString &secret); void initSMPSecret(const QString &secret); - void abortSMPAuthentiaction(ConnContext *context = NULL); + void abortSMPAuthentiaction(ConnContext *context = nullptr); void respondSMPAuthentication(const QString &answer); TrustFpResult trustFingerprint(bool trust); // functions called by libotr --------------------------------------- virtual void handleMessage(const Message &message) = 0; /** Report whether you think the given user is online. Return 1 if you think he is, 0 if you think he isn't, -1 if you're not sure. */ virtual int recipientStatus() const = 0; virtual unsigned int maxMessageSize() const = 0; void onTrustLevelChanged(const ConnContext *context = nullptr); void onSessionRefreshed(); void onNewFingerprintReceived(const QString &fingeprint); void onSMPFinished(bool success); void onSMPInProgress(); void onSMPError(); void onSMPAborted(); void onSMPCheated(); void onSMPQuery(const QString &question); private: Fingerprint* getFingerprint() const; ConnContext* findContext() const; private Q_SLOTS: void onFingerprintTrusted(const QString &accountId, const QString &fingerprint, bool trusted); Q_SIGNALS: void trustLevelChanged(TrustLevel trustLevel); void sessionRefreshed(); void newFingerprintReceived(const QString &fingeprint); void authenticationConcluded(bool success); void authenticationError(); void authenticationAborted(); void authenticationCheated(); /** empty string if secret */ void authenticationRequested(const QString &question); void authenticationInProgress(); private: otrl_instag_t instance; SessionContext ctx; UserStateBox *userstate; Manager *pr; }; typedef QSharedPointer SessionPtr; class ProxySession : public Session { public: ProxySession(OtrProxyChannel::Adaptee *pca, const SessionContext &ctx, Manager *parent); void handleMessage(const Message &message) override; int recipientStatus() const override; unsigned int maxMessageSize() const override; private: OtrProxyChannel::Adaptee *pca; }; } /* namespace OTR */ #endif diff --git a/otr-proxy/KTpProxy/otr-utils.cpp b/otr-proxy/KTpProxy/otr-utils.cpp index a88aadd..f4167f9 100644 --- a/otr-proxy/KTpProxy/otr-utils.cpp +++ b/otr-proxy/KTpProxy/otr-utils.cpp @@ -1,96 +1,96 @@ /*************************************************************************** * Copyright (C) 2014 by Marcin Ziemiński * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA* ***************************************************************************/ #include "otr-utils.h" #include "ktp-proxy-debug.h" namespace OTR { namespace utils { Fingerprint* findFingerprint(OtrlUserState userState, const QString &fp, const QString &user) { Fingerprint *fingerprint = nullptr; for(ConnContext *context = userState->context_root; context != nullptr; context = context->next) { if(user != QLatin1String(context->username)) { continue; } for(fingerprint = context->fingerprint_root.next; fingerprint != nullptr; fingerprint = fingerprint->next) { if(humanReadable(fingerprint->fingerprint) == fp) { return fingerprint; } } } return fingerprint; } bool isFingerprintInUse(Fingerprint *fingerprint) { // check if used in all parent contexts for(ConnContext *ctx_iter = fingerprint->context->m_context; ctx_iter != nullptr && ctx_iter->m_context == fingerprint->context->m_context; ctx_iter = ctx_iter->next) { if(ctx_iter->active_fingerprint == fingerprint) { return true; } } return false; } TrustLevel getTrustLevel(const SessionContext &ctx, OtrlUserState userState, otrl_instag_t instance) { ConnContext *context = otrl_context_find( userState, ctx.recipientName.toLocal8Bit(), ctx.accountName.toLocal8Bit(), ctx.protocol.toLocal8Bit(), - instance, 0, NULL, NULL, NULL); + instance, 0, nullptr, nullptr, nullptr); if(context == nullptr) { qCWarning(KTP_PROXY) << "Could not get trust level"; return TrustLevel::NOT_PRIVATE; } switch(context->msgstate) { case OTRL_MSGSTATE_PLAINTEXT: return TrustLevel::NOT_PRIVATE; case OTRL_MSGSTATE_ENCRYPTED: { if(otrl_context_is_fingerprint_trusted(context->active_fingerprint)) { return TrustLevel::VERIFIED; } else { return TrustLevel::UNVERIFIED; } } case OTRL_MSGSTATE_FINISHED: return TrustLevel::FINISHED; } return TrustLevel::NOT_PRIVATE; } } /* namespace utils */ } /* namespace OTR */ diff --git a/tests/contact-list-model-view-main.cpp b/tests/contact-list-model-view-main.cpp index 1e78eaa..ff0bb12 100644 --- a/tests/contact-list-model-view-main.cpp +++ b/tests/contact-list-model-view-main.cpp @@ -1,77 +1,77 @@ /* * This file is part of telepathy-kde-models-test-ui * * Copyright (C) 2011 Collabora Ltd. * @Author George Goldberg * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "model-view.h" #include #include #include #include #include #include #include #include #include #include #include "KTp/Models/contacts-list-model.h" #include "KTp/contact-factory.h" #include "KTp/core.h" int main(int argc, char *argv[]) { KAboutData aboutData(QStringLiteral("telepathy-kde-models-test-ui"), i18n("Telepathy KDE Models Test UI"), QStringLiteral("0.1"), i18n("Telepathy KDE Models Test UI"), KAboutLicense::LGPL, i18n("(C) 2011 Collabora Ltd")); KAboutData::setApplicationData(aboutData); QApplication app(argc, argv); QCommandLineParser parser; aboutData.setupCommandLine(&parser); parser.process(app); aboutData.processCommandLine(&parser); Tp::registerTypes(); Tp::enableDebug(false); Tp::enableWarnings(true); const Tp::AccountManagerPtr accountManager = KTp::accountManager(); KTp::ContactsListModel *model = new KTp::ContactsListModel(&app); model->setAccountManager(accountManager); // Set up and show the main widget - ModelView *mainWidget = new ModelView(model, 0); + ModelView *mainWidget = new ModelView(model, nullptr); mainWidget->show(); // Start event loop. app.exec(); } diff --git a/tests/kpeople-model-view-main.cpp b/tests/kpeople-model-view-main.cpp index 7ff02b6..f92b39c 100644 --- a/tests/kpeople-model-view-main.cpp +++ b/tests/kpeople-model-view-main.cpp @@ -1,72 +1,72 @@ /* * This file is part of telepathy-kde-models-test-ui * * Copyright (C) 2014 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "model-view.h" #include #include #include #include #include #include #include #include #include #include #include "KTp/Models/kpeopletranslationproxy.h" #include "KTp/contact-factory.h" #include "KTp/core.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); KAboutData aboutData(QStringLiteral("telepathy-kde-models-test-ui"), i18n("Telepathy KDE Models Test UI"), QStringLiteral("0.1"), i18n("Telepathy KDE Models Test UI"), KAboutLicense::LGPL, i18n("(C) 2011 Collabora Ltd")); KAboutData::setApplicationData(aboutData); Tp::registerTypes(); Tp::enableDebug(false); Tp::enableWarnings(true); const Tp::AccountManagerPtr accountManager = KTp::accountManager(); KPeople::PersonsModel *pm = new KPeople::PersonsModel(&app); KPeopleTranslationProxy *model = new KPeopleTranslationProxy(&app); // model->setAccountManager(accountManager); model->setSourceModel(pm); // Set up and show the main widget - ModelView *mainWidget = new ModelView(model, 0); + ModelView *mainWidget = new ModelView(model, nullptr); mainWidget->show(); // Start event loop. app.exec(); } diff --git a/tests/model-view.h b/tests/model-view.h index 85d3c79..d4a719e 100644 --- a/tests/model-view.h +++ b/tests/model-view.h @@ -1,42 +1,42 @@ /* * This file is part of telepathy-kde-models-test-ui * * Copyright (C) 2011 Collabora Ltd. * Copyright (C) 2013 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MAIN_WIDGET_H #define MAIN_WIDGET_H #include "ui_model-view.h" #include #include class ModelView : public QWidget, protected Ui::MainWidget { Q_OBJECT public: - ModelView(QAbstractItemModel *model, QWidget *parent = 0); + ModelView(QAbstractItemModel *model, QWidget *parent = nullptr); ~ModelView() override; }; #endif diff --git a/tests/roles-proxy-model.h b/tests/roles-proxy-model.h index 4f8dc68..00676b3 100644 --- a/tests/roles-proxy-model.h +++ b/tests/roles-proxy-model.h @@ -1,59 +1,59 @@ /* * This file is part of telepathy-kde-models-test-ui * * Copyright (C) 2011 Collabora Ltd. * Copyright (C) 2013 David Edmundson * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ROLES_PROXY_MODEL_H #define ROLES_PROXY_MODEL_H #include class RolesProxyModel : public QAbstractProxyModel { Q_OBJECT public: - RolesProxyModel(QObject *parent = 0); + RolesProxyModel(QObject *parent = nullptr); ~RolesProxyModel() override; void setSourceModel(QAbstractItemModel *sourceModel) override; int rowCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex &index) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; Qt::ItemFlags flags(const QModelIndex &index) const override; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override; QModelIndex mapToSource(const QModelIndex &proxyIndex) const override; protected Q_SLOTS: virtual void onSourceRowsInserted(const QModelIndex &parent, int start, int end); virtual void onSourceRowsRemoved(const QModelIndex &parent, int start, int end); virtual void onSourceDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight); virtual void onSourceLayoutChanged(); }; #endif diff --git a/tools/debugger/debug-message-view.h b/tools/debugger/debug-message-view.h index 13808d0..53f20f4 100644 --- a/tools/debugger/debug-message-view.h +++ b/tools/debugger/debug-message-view.h @@ -1,48 +1,48 @@ /* Copyright (C) 2011 Collabora Ltd. @author George Kiagiadakis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #ifndef DEBUG_MESSAGES_MODEL_H #define DEBUG_MESSAGES_MODEL_H #include #include #include class TelepathyProcess; class DebugMessageView : public QWidget { Q_OBJECT public: - explicit DebugMessageView(QWidget *parent = 0); + explicit DebugMessageView(QWidget *parent = nullptr); ~DebugMessageView() override; void showEvent(QShowEvent *event) override; void setTelepathyProcess(TelepathyProcess *process); void saveLogFile(); private Q_SLOTS: void appendMessage(const Tp::DebugMessage &msg); void addDelayedMessages(); void clear(); private: Tp::DebugMessageList m_tmpCache; KTextEditor::Document *m_editor; }; #endif // DEBUG_MESSAGES_MODEL_H diff --git a/tools/debugger/main-window.h b/tools/debugger/main-window.h index 86b3594..ec6961c 100644 --- a/tools/debugger/main-window.h +++ b/tools/debugger/main-window.h @@ -1,48 +1,48 @@ /* Copyright (C) 2011 Collabora Ltd. @author George Kiagiadakis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #ifndef MAIN_WINDOW_H #define MAIN_WINDOW_H #include "ui_main-window.h" #include #include #include class MainWindow : public KXmlGuiWindow { Q_OBJECT public: - explicit MainWindow(QWidget *parent = 0); + explicit MainWindow(QWidget *parent = nullptr); ~MainWindow() override; public Q_SLOTS: void saveLogFile(); private Q_SLOTS: void onAccountManagerBecameReady(Tp::PendingOperation *pendingReady); private: void initConnectionManagerTabs(const QSet &connectionManagerSet); Tp::AccountManagerPtr m_AccountManager; Ui::MainWindow m_ui; }; #endif // MAIN_WINDOW_H