From 4fce5d61ccbebc01721fc5022eb230353b569b68 Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 3 Feb 2019 19:39:19 +0100 Subject: [PATCH 01/81] added basic model file for Mail message tree --- libretroshare/src/retroshare/rstypes.h | 4 +- retroshare-gui/src/gui/msgs/MessageModel.cpp | 552 +++++++++++++++++++ retroshare-gui/src/gui/msgs/MessageModel.h | 172 ++++++ retroshare-gui/src/retroshare-gui.pro | 2 + 4 files changed, 728 insertions(+), 2 deletions(-) create mode 100644 retroshare-gui/src/gui/msgs/MessageModel.cpp create mode 100644 retroshare-gui/src/gui/msgs/MessageModel.h diff --git a/libretroshare/src/retroshare/rstypes.h b/libretroshare/src/retroshare/rstypes.h index 71a8406a1..cec7034ba 100644 --- a/libretroshare/src/retroshare/rstypes.h +++ b/libretroshare/src/retroshare/rstypes.h @@ -50,8 +50,8 @@ typedef Sha1CheckSum RsFileHash ; typedef Sha1CheckSum RsMessageId ; const uint32_t FT_STATE_FAILED = 0x0000 ; -const uint32_t FT_STATE_OKAY = 0x0001 ; -const uint32_t FT_STATE_WAITING = 0x0002 ; +const uint32_t FT_STATE_OKAY = 0x0001 ; +const uint32_t FT_STATE_WAITING = 0x0002 ; const uint32_t FT_STATE_DOWNLOADING = 0x0003 ; const uint32_t FT_STATE_COMPLETE = 0x0004 ; const uint32_t FT_STATE_QUEUED = 0x0005 ; diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp new file mode 100644 index 000000000..b1572a844 --- /dev/null +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -0,0 +1,552 @@ +/******************************************************************************* + * retroshare-gui/src/gui/msgs/RsMessageModel.cpp * + * * + * Copyright 2019 by Cyril Soler * + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU Affero General Public License as * + * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. * + * * + * You should have received a copy of the GNU Affero General Public License * + * along with this program. If not, see . * + * * + *******************************************************************************/ + +#include + +#include +#include +#include +#include +#include + +#include "util/HandleRichText.h" +#include "util/DateTime.h" +#include "gui/gxs/GxsIdDetails.h" +#include "MessageModel.h" +#include "retroshare/rsexpr.h" + +//#define DEBUG_MESSAGE_MODEL + +#define IS_MESSAGE_UNREAD(flags) (flags & RS_MSG_UNREAD_BY_USER) + +std::ostream& operator<<(std::ostream& o, const QModelIndex& i);// defined elsewhere + +const QString RsMessageModel::FilterString("filtered"); + +RsMessageModel::RsMessageModel(QObject *parent) + : QAbstractItemModel(parent) +{ + mFilteringEnabled=false; +} + +void RsMessageModel::preMods() +{ + emit layoutAboutToBeChanged(); +} +void RsMessageModel::postMods() +{ + emit dataChanged(createIndex(0,0,(void*)NULL), createIndex(0,COLUMN_THREAD_NB_COLUMNS-1,(void*)NULL)); +} + +// void RsGxsForumModel::setSortMode(SortMode mode) +// { +// preMods(); +// +// mSortMode = mode; +// +// postMods(); +// } + +int RsMessageModel::rowCount(const QModelIndex& parent) const +{ + if(!parent.isValid()) + return 0; + + if(parent.column() > 0) + return 0; + + if(mMessages.empty()) // security. Should never happen. + return 0; + + if(parent.internalPointer() == NULL) + return mMessages.size(); + + return 0; +} + +int RsMessageModel::columnCount(const QModelIndex &parent) const +{ + return COLUMN_THREAD_NB_COLUMNS ; +} + +bool RsMessageModel::getMessageData(const QModelIndex& i,Rs::Msgs::MessageInfo& fmpe) const +{ + if(!i.isValid()) + return true; + + quintptr ref = i.internalId(); + uint32_t index = 0; + + if(!convertInternalIdToMsgIndex(ref,index) || index >= mMessages.size()) + return false ; + + return rsMsgs->getMessage(mMessages[index].msgId,fmpe); +} + +bool RsMessageModel::hasChildren(const QModelIndex &parent) const +{ + if(!parent.isValid()) + return true; + + return false ; +} + +bool RsMessageModel::convertMsgIndexToInternalId(uint32_t index,quintptr& id) +{ + // the internal id is set to the place in the table of items. We simply shift to allow 0 to mean something special. + + id = index + 1 ; + + return true; +} + +bool RsMessageModel::convertInternalIdToMsgIndex(quintptr ref,uint32_t& index) +{ + if(ref == 0) + return false ; + + index = ref - 1; + return true; +} + +QModelIndex RsMessageModel::index(int row, int column, const QModelIndex & parent) const +{ + if(row < 0 || column < 0 || column >= COLUMN_THREAD_NB_COLUMNS) + return QModelIndex(); + + quintptr ref ; + + if(parent.internalId() == 0 && convertMsgIndexToInternalId(row,ref)) + return createIndex(row,column,ref) ; + + return QModelIndex(); +} + +QModelIndex RsMessageModel::parent(const QModelIndex& index) const +{ + if(!index.isValid()) + return QModelIndex(); + + return QModelIndex(); +} + +Qt::ItemFlags RsMessageModel::flags(const QModelIndex& index) const +{ + if (!index.isValid()) + return 0; + + return QAbstractItemModel::flags(index); +} + +QVariant RsMessageModel::headerData(int section, Qt::Orientation orientation, int role) const +{ + if(role == Qt::DisplayRole) + switch(section) + { + case COLUMN_THREAD_DATE: return tr("Date"); + case COLUMN_THREAD_AUTHOR: return tr("Author"); + default: + return QVariant(); + } + + if(role == Qt::DecorationRole) + switch(section) + { + case COLUMN_THREAD_READ: return QIcon(":/images/message-state-read.png"); + default: + return QVariant(); + } + + return QVariant(); +} + +QVariant RsMessageModel::data(const QModelIndex &index, int role) const +{ +#ifdef DEBUG_FORUMMODEL + std::cerr << "calling data(" << index << ") role=" << role << std::endl; +#endif + + if(!index.isValid()) + return QVariant(); + + switch(role) + { + case Qt::SizeHintRole: return sizeHintRole(index.column()) ; + case Qt::StatusTipRole:return QVariant(); + default: break; + } + + quintptr ref = (index.isValid())?index.internalId():0 ; + uint32_t entry = 0; + +#ifdef DEBUG_FORUMMODEL + std::cerr << "data(" << index << ")" ; +#endif + + if(!ref) + { +#ifdef DEBUG_FORUMMODEL + std::cerr << " [empty]" << std::endl; +#endif + return QVariant() ; + } + + if(!convertInternalIdToMsgIndex(ref,entry) || entry >= mMessages.size()) + { +#ifdef DEBUG_FORUMMODEL + std::cerr << "Bad pointer: " << (void*)ref << std::endl; +#endif + return QVariant() ; + } + + const Rs::Msgs::MsgInfoSummary& fmpe(mMessages[entry]); + + if(role == Qt::FontRole) + { + QFont font ; +// font.setBold( (fmpe.mPostFlags & (ForumModelPostEntry::FLAG_POST_HAS_UNREAD_CHILDREN | ForumModelPostEntry::FLAG_POST_IS_PINNED)) || IS_MSG_UNREAD(fmpe.mMsgStatus)); + return QVariant(font); + } + +#ifdef DEBUG_FORUMMODEL + std::cerr << " [ok]" << std::endl; +#endif + + switch(role) + { + case Qt::DisplayRole: return displayRole (fmpe,index.column()) ; + case Qt::DecorationRole: return decorationRole(fmpe,index.column()) ; + case Qt::ToolTipRole: return toolTipRole (fmpe,index.column()) ; + case Qt::UserRole: return userRole (fmpe,index.column()) ; + case Qt::TextColorRole: return textColorRole (fmpe,index.column()) ; + case Qt::BackgroundRole: return backgroundRole(fmpe,index.column()) ; + + case FilterRole: return filterRole (fmpe,index.column()) ; + case StatusRole: return statusRole (fmpe,index.column()) ; + case SortRole: return sortRole (fmpe,index.column()) ; + default: + return QVariant(); + } +} + +QVariant RsMessageModel::textColorRole(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const +{ +// if( (fmpe.msgflags & ForumModelPostEntry::FLAG_POST_IS_MISSING)) +// return QVariant(mTextColorMissing); +// +// if(IS_MSG_UNREAD(fmpe.mMsgStatus) || (fmpe.mPostFlags & ForumModelPostEntry::FLAG_POST_IS_PINNED)) +// return QVariant(mTextColorUnread); +// else +// return QVariant(mTextColorRead); + + return QVariant(); +} + +QVariant RsMessageModel::statusRole(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const +{ +// if(column != COLUMN_THREAD_DATA) +// return QVariant(); + + return QVariant();//fmpe.mMsgStatus); +} + +QVariant RsMessageModel::filterRole(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const +{ + if(!mFilteringEnabled) + return QVariant(FilterString); + + return QVariant(QString()); +} + +uint32_t RsMessageModel::updateFilterStatus(ForumModelIndex i,int column,const QStringList& strings) +{ + QString s ; + uint32_t count = 0; + + return count; +} + + +void RsMessageModel::setFilter(int column,const QStringList& strings,uint32_t& count) +{ + preMods(); + + if(!strings.empty()) + { + count = updateFilterStatus(ForumModelIndex(0),column,strings); + mFilteringEnabled = true; + } + else + { + count=0; + mFilteringEnabled = false; + } + + postMods(); +} + +QVariant RsMessageModel::toolTipRole(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const +{ + if(column == COLUMN_THREAD_AUTHOR) + { + QString str,comment ; + QList icons; + + if(!GxsIdDetails::MakeIdDesc(RsGxsId(fmpe.srcId.toStdString()), true, str, icons, comment,GxsIdDetails::ICON_TYPE_AVATAR)) + return QVariant(); + + int S = QFontMetricsF(QApplication::font()).height(); + QImage pix( (*icons.begin()).pixmap(QSize(4*S,4*S)).toImage()); + + QString embeddedImage; + if(RsHtml::makeEmbeddedImage(pix.scaled(QSize(4*S,4*S), Qt::KeepAspectRatio, Qt::SmoothTransformation), embeddedImage, 8*S * 8*S)) + comment = "
" + embeddedImage + "" + comment + "
"; + + return comment; + } + + return QVariant(); +} + +QVariant RsMessageModel::backgroundRole(const Rs::Msgs::MsgInfoSummary &fmpe, int column) const +{ + return QVariant(); +} + +QVariant RsMessageModel::sizeHintRole(int col) const +{ + float factor = QFontMetricsF(QApplication::font()).height()/14.0f ; + + switch(col) + { + default: + case COLUMN_THREAD_SUBJECT: return QVariant( QSize(factor * 170, factor*14 )); + case COLUMN_THREAD_DATE: return QVariant( QSize(factor * 75 , factor*14 )); + case COLUMN_THREAD_AUTHOR: return QVariant( QSize(factor * 75 , factor*14 )); + } +} + +QVariant RsMessageModel::authorRole(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const +{ +// if(column == COLUMN_THREAD_DATA) +// return QVariant(QString::fromStdString(fmpe.mAuthorId.toStdString())); + + return QVariant(); +} + +QVariant RsMessageModel::sortRole(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const +{ + switch(column) + { + case COLUMN_THREAD_DATE: return QVariant(QString::number(fmpe.ts)); // we should probably have leading zeroes here + + case COLUMN_THREAD_READ: return QVariant((bool)IS_MESSAGE_UNREAD(fmpe.msgflags)); + case COLUMN_THREAD_AUTHOR: + { + QString str,comment ; + QList icons; + GxsIdDetails::MakeIdDesc(RsGxsId(fmpe.srcId), false, str, icons, comment,GxsIdDetails::ICON_TYPE_NONE); + + return QVariant(str); + } + default: + return displayRole(fmpe,column); + } +} + +QVariant RsMessageModel::displayRole(const Rs::Msgs::MsgInfoSummary& fmpe,int col) const +{ + switch(col) + { + case COLUMN_THREAD_SUBJECT: return QVariant(QString::fromUtf8(fmpe.title.c_str())); + + case COLUMN_THREAD_READ:return QVariant(); + case COLUMN_THREAD_DATE:{ + QDateTime qtime; + qtime.setTime_t(fmpe.ts); + + return QVariant(DateTime::formatDateTime(qtime)); + } + + case COLUMN_THREAD_AUTHOR: return QVariant(); + + default: + return QVariant("[ TODO ]"); + } + + + return QVariant("[ERROR]"); +} + +QVariant RsMessageModel::userRole(const Rs::Msgs::MsgInfoSummary& fmpe,int col) const +{ + switch(col) + { + case COLUMN_THREAD_AUTHOR: return QVariant(QString::fromStdString(fmpe.srcId.toStdString())); + case COLUMN_THREAD_MSGID: return QVariant(QString::fromStdString(fmpe.msgId)); + default: + return QVariant(); + } +} + +QVariant RsMessageModel::decorationRole(const Rs::Msgs::MsgInfoSummary& fmpe,int col) const +{ + if(col == COLUMN_THREAD_READ) + return QVariant(IS_MESSAGE_UNREAD(fmpe.msgflags)); + else + return QVariant(); +} + +void RsMessageModel::clear() +{ + preMods(); + + mMessages.clear(); + + postMods(); + + emit messagesLoaded(); +} + +void RsMessageModel::setMessages(const std::list& msgs) +{ + preMods(); + + beginRemoveRows(QModelIndex(),0,mMessages.size()-1); + endRemoveRows(); + + mMessages.clear(); + + for(auto it(msgs.begin());it!=msgs.end();++it) + mMessages.push_back(*it); + + // now update prow for all posts + +#ifdef DEBUG_FORUMMODEL + debug_dump(); +#endif + + beginInsertRows(QModelIndex(),0,mMessages.size()-1); + endInsertRows(); + postMods(); + + emit messagesLoaded(); +} + +void RsMessageModel::updateMessages() +{ + std::list msgs ; + + rsMsgs->getMessageSummaries(msgs); + setMessages(msgs); +} + +// RsThread::async([this, group_id]() +// { +// // 1 - get message data from p3GxsForums +// +// std::list forumIds; +// std::vector msg_metas; +// std::vector groups; +// +// forumIds.push_back(group_id); +// +// if(!rsGxsForums->getForumsInfo(forumIds,groups)) +// { +// std::cerr << __PRETTY_FUNCTION__ << " failed to retrieve forum group info for forum " << group_id << std::endl; +// return; +// } +// +// if(!rsGxsForums->getForumMsgMetaData(group_id,msg_metas)) +// { +// std::cerr << __PRETTY_FUNCTION__ << " failed to retrieve forum message info for forum " << group_id << std::endl; +// return; +// } +// +// // 2 - sort the messages into a proper hierarchy +// +// auto post_versions = new std::map > >() ; +// std::vector *vect = new std::vector(); +// RsGxsForumGroup group = groups[0]; +// +// computeMessagesHierarchy(group,msg_metas,*vect,*post_versions); +// +// // 3 - update the model in the UI thread. +// +// RsQThreadUtils::postToObject( [group,vect,post_versions,this]() +// { +// /* Here it goes any code you want to be executed on the Qt Gui +// * thread, for example to update the data model with new information +// * after a blocking call to RetroShare API complete, note that +// * Qt::QueuedConnection is important! +// */ +// +// setPosts(group,*vect,*post_versions) ; +// +// delete vect; +// delete post_versions; +// +// +// }, this ); +// +// }); + +static bool decreasing_time_comp(const std::pair& e1,const std::pair& e2) { return e2.first < e1.first ; } + +void RsMessageModel::setMsgReadStatus(const QModelIndex& i,bool read_status) +{ + if(!i.isValid()) + return ; + + preMods(); + + quintptr ref = i.internalId(); + uint32_t index = 0; + + if(!convertInternalIdToMsgIndex(ref,index) || index >= mMessages.size()) + return ; + + rsMsgs->MessageRead(mMessages[index].msgId,!read_status); + + postMods(); +} + +QModelIndex RsMessageModel::getIndexOfMessage(const std::string& mid) const +{ + // Brutal search. This is not so nice, so dont call that in a loop! If too costly, we'll use a map. + + for(uint32_t i=0;imsgId << ": from " << it->srcId << ": flags=" << it->msgflags << ": title=\"" << it->title << "\"" << std::endl; +} + diff --git a/retroshare-gui/src/gui/msgs/MessageModel.h b/retroshare-gui/src/gui/msgs/MessageModel.h new file mode 100644 index 000000000..5cf13f370 --- /dev/null +++ b/retroshare-gui/src/gui/msgs/MessageModel.h @@ -0,0 +1,172 @@ +/******************************************************************************* + * retroshare-gui/src/gui/msgs/RsMessageModel.h * + * * + * Copyright 2019 by Cyril Soler * + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU Affero General Public License as * + * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. * + * * + * You should have received a copy of the GNU Affero General Public License * + * along with this program. If not, see . * + * * + *******************************************************************************/ + +#pragma once + +#include +#include + +#include "retroshare/rsmsgs.h" + +// This class holds the actual hierarchy of posts, represented by identifiers +// It is responsible for auto-updating when necessary and holds a mutex to allow the Model to +// safely access the data. + +// The model contains a post in place 0 that is the parent of all posts. + +typedef uint32_t ForumModelIndex; + +struct ForumModelPostEntry +{ + ForumModelPostEntry() : mPublishTs(0),mMostRecentTsInThread(0),mPostFlags(0),mReputationWarningLevel(0),mMsgStatus(0),prow(0) {} + + enum { // flags for display of posts. To be used in mPostFlags + FLAG_POST_IS_PINNED = 0x0001, + FLAG_POST_IS_MISSING = 0x0002, + FLAG_POST_IS_REDACTED = 0x0004, + FLAG_POST_HAS_UNREAD_CHILDREN = 0x0008, + FLAG_POST_HAS_READ_CHILDREN = 0x0010, + FLAG_POST_PASSES_FILTER = 0x0020, + FLAG_POST_CHILDREN_PASSES_FILTER = 0x0040, + }; + + std::string mTitle ; + RsGxsId mAuthorId ; + RsGxsMessageId mMsgId; + uint32_t mPublishTs; + uint32_t mMostRecentTsInThread; + uint32_t mPostFlags; + int mReputationWarningLevel; + int mMsgStatus; + + std::vector mChildren; + ForumModelIndex mParent; + int prow ; // parent row +}; + +// This class is the item model used by Qt to display the information + +class RsMessageModel : public QAbstractItemModel +{ + Q_OBJECT + +public: + explicit RsMessageModel(QObject *parent = NULL); + ~RsMessageModel(){} + + enum Columns { + COLUMN_THREAD_STAR =0x00, + COLUMN_THREAD_ATTACHMENT =0x01, + COLUMN_THREAD_SUBJECT =0x02, + COLUMN_THREAD_READ =0x03, + COLUMN_THREAD_AUTHOR =0x04, + COLUMN_THREAD_DATE =0x05, + COLUMN_THREAD_TAGS =0x06, + COLUMN_THREAD_MSGID =0x07, + COLUMN_THREAD_NB_COLUMNS =0x08, + }; + + enum Roles{ SortRole = Qt::UserRole+1, + StatusRole = Qt::UserRole+2, + UnreadRole = Qt::UserRole+3, + FilterRole = Qt::UserRole+4, + }; + + QModelIndex root() const{ return createIndex(0,0,(void*)NULL) ;} + QModelIndex getIndexOfMessage(const std::string &mid) const; + + static const QString FilterString ; + + // This method will asynchroneously update the data + + void updateMessages(); + const RsMessageId& currentMessageId() const; + + void setMsgReadStatus(const QModelIndex& i, bool read_status); + void setFilter(int column, const QStringList& strings, uint32_t &count) ; + + int rowCount(const QModelIndex& parent = QModelIndex()) const override; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; + bool hasChildren(const QModelIndex &parent = QModelIndex()) const override; + + QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const override; + QModelIndex parent(const QModelIndex& child) const override; + Qt::ItemFlags flags(const QModelIndex& index) const override; + + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + + bool getMessageData(const QModelIndex& i,Rs::Msgs::MessageInfo& fmpe) const; + void clear() ; + + QVariant sizeHintRole (int col) const; + + QVariant displayRole (const Rs::Msgs::MsgInfoSummary& fmpe, int col) const; + QVariant decorationRole(const Rs::Msgs::MsgInfoSummary& fmpe, int col) const; + QVariant toolTipRole (const Rs::Msgs::MsgInfoSummary& fmpe, int col) const; + QVariant userRole (const Rs::Msgs::MsgInfoSummary& fmpe, int col) const; + QVariant statusRole (const Rs::Msgs::MsgInfoSummary& fmpe, int col) const; + QVariant authorRole (const Rs::Msgs::MsgInfoSummary& fmpe, int col) const; + QVariant sortRole (const Rs::Msgs::MsgInfoSummary& fmpe, int col) const; + QVariant fontRole (const Rs::Msgs::MsgInfoSummary& fmpe, int col) const; + QVariant filterRole (const Rs::Msgs::MsgInfoSummary& fmpe, int col) const; + QVariant textColorRole (const Rs::Msgs::MsgInfoSummary& fmpe, int col) const; + QVariant backgroundRole(const Rs::Msgs::MsgInfoSummary& fmpe, int col) const; + + /*! + * \brief debug_dump + * Dumps the hierarchy of posts in the terminal, to allow checking whether the internal representation is correct. + */ + void debug_dump() const; + +signals: + void messagesLoaded(); // emitted after the messages have been set. Can be used to updated the UI. + +private: + bool mFilteringEnabled; + + void preMods() ; + void postMods() ; + + void *getParentRef(void *ref,int& row) const; + void *getChildRef(void *ref,int row) const; + //bool hasIndex(int row,int column,const QModelIndex& parent)const; + int getChildrenCount(void *ref) const; + + static bool convertMsgIndexToInternalId(uint32_t entry,quintptr& ref); + static bool convertInternalIdToMsgIndex(quintptr ref,uint32_t& index); + static void computeReputationLevel(uint32_t forum_sign_flags, ForumModelPostEntry& entry); + + void update_posts(const RsGxsGroupId &group_id); + uint32_t updateFilterStatus(ForumModelIndex i,int column,const QStringList& strings); + + static void generateMissingItem(const RsGxsMessageId &msgId,ForumModelPostEntry& entry); + static ForumModelIndex addEntry(std::vector& posts,const ForumModelPostEntry& entry,ForumModelIndex parent); + + void setMessages(const std::list& msgs); + + QColor mTextColorRead ; + QColor mTextColorUnread ; + QColor mTextColorUnreadChildren; + QColor mTextColorNotSubscribed ; + QColor mTextColorMissing ; + + std::vector mMessages; +}; diff --git a/retroshare-gui/src/retroshare-gui.pro b/retroshare-gui/src/retroshare-gui.pro index 692deba9a..5769274b8 100644 --- a/retroshare-gui/src/retroshare-gui.pro +++ b/retroshare-gui/src/retroshare-gui.pro @@ -447,6 +447,7 @@ HEADERS += rshare.h \ gui/msgs/MessageComposer.h \ gui/msgs/MessageWindow.h \ gui/msgs/MessageWidget.h \ + gui/msgs/MessageModel.h \ gui/msgs/TagsMenu.h \ gui/msgs/textformat.h \ gui/msgs/MessageUserNotify.h \ @@ -802,6 +803,7 @@ SOURCES += main.cpp \ gui/msgs/MessageComposer.cpp \ gui/msgs/MessageWidget.cpp \ gui/msgs/MessageWindow.cpp \ + gui/msgs/MessageModel.cpp \ gui/msgs/TagsMenu.cpp \ gui/msgs/MessageUserNotify.cpp \ gui/common/RsButtonOnText.cpp \ From b7c8c16e2931c6841f2f4a0d08f92450ce021bc9 Mon Sep 17 00:00:00 2001 From: csoler Date: Fri, 8 Feb 2019 15:41:20 +0100 Subject: [PATCH 02/81] inserted the model into the widget --- retroshare-gui/src/gui/MessagesDialog.cpp | 135 +++++++++++++++--- retroshare-gui/src/gui/MessagesDialog.h | 7 +- retroshare-gui/src/gui/MessagesDialog.ui | 14 +- .../src/gui/gxs/GxsIdTreeWidgetItem.h | 81 +++++++++++ retroshare-gui/src/gui/msgs/MessageModel.h | 10 ++ retroshare-gui/src/gui/msgs/MessageWidget.cpp | 2 +- 6 files changed, 214 insertions(+), 35 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 0f9419f07..74f370540 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -40,6 +40,7 @@ #include "msgs/MessageUserNotify.h" #include "msgs/MessageWidget.h" #include "msgs/TagsMenu.h" +#include "msgs/MessageModel.h" #include "settings/rsharesettings.h" #include "util/DateTime.h" @@ -99,20 +100,24 @@ MessagesDialog::LockUpdate::LockUpdate (MessagesDialog *pDialog, bool bUpdate) { +#ifdef TODO m_pDialog = pDialog; m_bUpdate = bUpdate; ++m_pDialog->lockUpdate; +#endif } MessagesDialog::LockUpdate::~LockUpdate () { +#ifdef TODO if(--m_pDialog->lockUpdate < 0) m_pDialog->lockUpdate = 0; if (m_bUpdate && m_pDialog->lockUpdate == 0) { m_pDialog->insertMessages(); } +#endif } void MessagesDialog::LockUpdate::setUpdate(bool bUpdate) @@ -120,6 +125,25 @@ void MessagesDialog::LockUpdate::setUpdate(bool bUpdate) m_bUpdate = bUpdate; } +class MessageSortFilterProxyModel: public QSortFilterProxyModel +{ +public: + MessageSortFilterProxyModel(const QHeaderView *header,QObject *parent = NULL): QSortFilterProxyModel(parent),m_header(header) {} + + bool lessThan(const QModelIndex& left, const QModelIndex& right) const override + { + return left.data(RsMessageModel::SortRole) < right.data(RsMessageModel::SortRole) ; + } + + bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override + { + return sourceModel()->index(source_row,0,source_parent).data(RsMessageModel::FilterRole).toString() == RsMessageModel::FilterString ; + } + +private: + const QHeaderView *m_header ; +}; + /** Constructor */ MessagesDialog::MessagesDialog(QWidget *parent) : MainPage(parent) @@ -165,6 +189,22 @@ MessagesDialog::MessagesDialog(QWidget *parent) mCurrMsgId = ""; + mMessageModel = new RsMessageModel(this); + mMessageProxyModel = new MessageSortFilterProxyModel(ui.messageTreeWidget->header(),this); + mMessageProxyModel->setSourceModel(mMessageModel); + mMessageProxyModel->setSortRole(RsMessageModel::SortRole); + ui.messageTreeWidget->setModel(mMessageProxyModel); + + mMessageProxyModel->setFilterRole(RsMessageModel::FilterRole); + mMessageProxyModel->setFilterRegExp(QRegExp(QString(RsMessageModel::FilterString))) ; + + ui.messageTreeWidget->setSortingEnabled(true); + + //ui.messageTreeWidget->setItemDelegateForColumn(RsMessageModel::COLUMN_THREAD_DISTRIBUTION,new DistributionItemDelegate()) ; + ui.messageTreeWidget->setItemDelegateForColumn(RsMessageModel::COLUMN_THREAD_AUTHOR,new GxsIdTreeItemDelegate()) ; + //ui.messageTreeWidget->setItemDelegateForColumn(RsGxsForumModel::COLUMN_THREAD_READ,new ReadStatusItemDelegate()) ; + +#ifdef TO_REMOVE // Set the QStandardItemModel ui.messageTreeWidget->setColumnCount(COLUMN_COUNT); QTreeWidgetItem *headerItem = ui.messageTreeWidget->headerItem(); @@ -190,6 +230,7 @@ MessagesDialog::MessagesDialog(QWidget *parent) headerItem->setToolTip(COLUMN_DATE, tr("Click to sort by date")); headerItem->setToolTip(COLUMN_TAGS, tr("Click to sort by tags")); headerItem->setToolTip(COLUMN_STAR, tr("Click to sort by star")); +#endif mMessageCompareRole = new RSTreeWidgetItemCompareRole; mMessageCompareRole->setRole(COLUMN_SUBJECT, ROLE_SORT); @@ -287,9 +328,11 @@ MessagesDialog::MessagesDialog(QWidget *parent) // create timer for navigation timer = new RsProtectedTimer(this); +#ifdef TODO timer->setInterval(300); timer->setSingleShot(true); connect(timer, SIGNAL(timeout()), this, SLOT(updateCurrentMessage())); +#endif ui.messageTreeWidget->installEventFilter(this); @@ -380,6 +423,7 @@ void MessagesDialog::processSettings(bool load) bool MessagesDialog::eventFilter(QObject *obj, QEvent *event) { +#ifdef TODO if (obj == ui.messageTreeWidget) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast(event); @@ -390,12 +434,14 @@ bool MessagesDialog::eventFilter(QObject *obj, QEvent *event) } } } +#endif // pass the event on to the parent class return MainPage::eventFilter(obj, event); } void MessagesDialog::changeEvent(QEvent *e) { +#ifdef TODO QWidget::changeEvent(e); switch (e->type()) { case QEvent::StyleChange: @@ -405,6 +451,7 @@ void MessagesDialog::changeEvent(QEvent *e) // remove compiler warnings break; } +#endif } void MessagesDialog::fillQuickView() @@ -486,17 +533,32 @@ void MessagesDialog::fillQuickView() // else // MainPage::keyPressEvent(e) ; //} +int MessagesDialog::getSelectedMessages(QList& mid) +{ + //To check if the selection has more than one row. + + mid.clear(); + QModelIndexList qmil = ui.messageTreeWidget->selectionModel()->selectedRows(); + + foreach(const QModelIndex& m, qmil) + mid.push_back(m.sibling(m.row(),COLUMN_DATA).data(ROLE_MSGID).toString()) ; + + return mid.size(); +} int MessagesDialog::getSelectedMsgCount (QList *items, QList *itemsRead, QList *itemsUnread, QList *itemsStar) { +#ifdef TODO if (items) items->clear(); if (itemsRead) itemsRead->clear(); if (itemsUnread) itemsUnread->clear(); if (itemsStar) itemsStar->clear(); //To check if the selection has more than one row. - QList selectedItems = ui.messageTreeWidget->selectedItems(); - foreach (QTreeWidgetItem *item, selectedItems) + QList selectedMessages; + getSelectedMessages(selectedMessages); + + foreach (const QString&, selectedMessages) { if (items || itemsRead || itemsUnread || itemsStar) { if (items) items->append(item); @@ -516,6 +578,8 @@ int MessagesDialog::getSelectedMsgCount (QList *items, QListclear(); +// ui.messageTreeWidget->clear(); ui.quickViewWidget->setCurrentItem(NULL); listMode = LIST_BOX; - insertMessages(); - insertMsgTxtAndFiles(ui.messageTreeWidget->currentItem()); +// insertMessages(); +// insertMsgTxtAndFiles(ui.messageTreeWidget->currentItem()); + switch(box_row) + { + case 0: mMessageModel->setCurrentBox(RsMessageModel::BOX_INBOX ); break; + case 1: mMessageModel->setCurrentBox(RsMessageModel::BOX_OUTBOX); break; + case 2: mMessageModel->setCurrentBox(RsMessageModel::BOX_DRAFTS); break; + case 3: mMessageModel->setCurrentBox(RsMessageModel::BOX_SENT ); break; + case 4: mMessageModel->setCurrentBox(RsMessageModel::BOX_TRASH ); break; + default: + mMessageModel->setCurrentBox(RsMessageModel::BOX_NONE); break; + } inChange = false; } void MessagesDialog::changeQuickView(int newrow) { +#warning Missing code here! +#ifdef TODO Q_UNUSED(newrow); if (inChange) { @@ -799,16 +875,20 @@ void MessagesDialog::changeQuickView(int newrow) insertMsgTxtAndFiles(ui.messageTreeWidget->currentItem()); inChange = false; +#endif } void MessagesDialog::messagesTagsChanged() { +#ifdef TODO if (lockUpdate) { return; } fillQuickView(); insertMessages(); +#endif +#warning Missing code here! } static void InitIconAndFont(QTreeWidgetItem *item) @@ -877,6 +957,7 @@ static void InitIconAndFont(QTreeWidgetItem *item) item->setData(COLUMN_DATA, ROLE_UNREAD, isNew); } +#ifdef TO_REMOVE void MessagesDialog::insertMessages() { if (lockUpdate) { @@ -1336,10 +1417,12 @@ void MessagesDialog::insertMessages() updateMessageSummaryList(); } +#endif // current row in messageTreeWidget has changed void MessagesDialog::currentItemChanged(QTreeWidgetItem *item) { +#ifdef TODO timer->stop(); if (item) { @@ -1350,6 +1433,7 @@ void MessagesDialog::currentItemChanged(QTreeWidgetItem *item) } updateInterface(); +#endif } // click in messageTreeWidget @@ -1377,9 +1461,10 @@ void MessagesDialog::clicked(QTreeWidgetItem *item, int column) return; } } - +#ifdef TODO timer->stop(); timerIndex = ui.messageTreeWidget->indexOfTopLevelItem(item); +#endif // show current message directly updateCurrentMessage(); @@ -1421,8 +1506,10 @@ void MessagesDialog::doubleClicked(QTreeWidgetItem *item, int column) // show current message directly void MessagesDialog::updateCurrentMessage() { +#ifdef TODO timer->stop(); insertMsgTxtAndFiles(ui.messageTreeWidget->topLevelItem(timerIndex)); +#endif } void MessagesDialog::setMsgAsReadUnread(const QList &items, bool read) @@ -1573,10 +1660,11 @@ void MessagesDialog::insertMsgTxtAndFiles(QTreeWidgetItem *item, bool bSetToRead bool MessagesDialog::getCurrentMsg(std::string &cid, std::string &mid) { - QTreeWidgetItem *item = ui.messageTreeWidget->currentItem(); + QModelIndex indx = ui.messageTreeWidget->currentIndex(); +#ifdef TODO /* get its Ids */ - if (!item) + if (!indx.isValid()) { //If no message is selected. assume first message is selected. if (ui.messageTreeWidget->topLevelItemCount() == 0) @@ -1588,8 +1676,13 @@ bool MessagesDialog::getCurrentMsg(std::string &cid, std::string &mid) if (!item) { return false; } - cid = item->data(COLUMN_DATA, ROLE_SRCID).toString().toStdString(); - mid = item->data(COLUMN_DATA, ROLE_MSGID).toString().toStdString(); +#endif + if(!indx.isValid()) + return false ; + + cid = indx.sibling(indx.row(),COLUMN_DATA).data(ROLE_SRCID).toString().toStdString(); + mid = indx.sibling(indx.row(),COLUMN_DATA).data(ROLE_MSGID).toString().toStdString(); + return true; } @@ -1597,7 +1690,8 @@ void MessagesDialog::removemessage() { LockUpdate Lock (this, true); - QList selectedItems = ui.messageTreeWidget->selectedItems(); + QList selectedMessages ; + getSelectedMessages(selectedMessages); bool doDelete = false; int listrow = ui.listWidget->currentRow(); @@ -1609,16 +1703,11 @@ void MessagesDialog::removemessage() } } - foreach (QTreeWidgetItem *item, selectedItems) { - QString mid = item->data(COLUMN_DATA, ROLE_MSGID).toString(); - - // close tab showing this message -// closeTab(mid.toStdString()); - + foreach (const QString& m, selectedMessages) { if (doDelete) { - rsMail->MessageDelete(mid.toStdString()); + rsMail->MessageDelete(m.toStdString()); } else { - rsMail->MessageToTrash(mid.toStdString(), true); + rsMail->MessageToTrash(m.toStdString(), true); } } @@ -1658,7 +1747,9 @@ void MessagesDialog::buttonStyle() void MessagesDialog::filterChanged(const QString& text) { +#ifdef TODO ui.messageTreeWidget->filterItems(ui.filterLineEdit->currentFilter(), text); +#endif } void MessagesDialog::filterColumnChanged(int column) @@ -1669,9 +1760,11 @@ void MessagesDialog::filterColumnChanged(int column) if (column == COLUMN_CONTENT) { // need content ... refill - insertMessages(); + //insertMessages(); } +#ifdef TODO ui.messageTreeWidget->filterItems(column, ui.filterLineEdit->text()); +#endif // save index Settings->setValueToGroup("MessageDialog", "filterColumn", column); diff --git a/retroshare-gui/src/gui/MessagesDialog.h b/retroshare-gui/src/gui/MessagesDialog.h index 5801a6320..8b3a96dcd 100644 --- a/retroshare-gui/src/gui/MessagesDialog.h +++ b/retroshare-gui/src/gui/MessagesDialog.h @@ -30,6 +30,8 @@ class RSTreeWidgetItemCompareRole; class MessageWidget; +class QTreeWidgetItem; +class RsMessageModel; class MessagesDialog : public MainPage { @@ -59,9 +61,10 @@ public: protected: bool eventFilter(QObject *obj, QEvent *ev); void changeEvent(QEvent *e); + int getSelectedMessages(QList& mid); public slots: - void insertMessages(); + //void insertMessages(); void messagesTagsChanged(); private slots: @@ -153,6 +156,8 @@ private: RSTreeWidgetItemCompareRole *mMessageCompareRole; MessageWidget *msgWidget; + RsMessageModel *mMessageModel; + QSortFilterProxyModel *mMessageProxyModel; /* Color definitions (for standard see qss.default) */ QColor mTextColorInbox; diff --git a/retroshare-gui/src/gui/MessagesDialog.ui b/retroshare-gui/src/gui/MessagesDialog.ui index 1203a1eb2..1ea2a904b 100644 --- a/retroshare-gui/src/gui/MessagesDialog.ui +++ b/retroshare-gui/src/gui/MessagesDialog.ui @@ -6,7 +6,7 @@ 0 0 - 775 + 842 485 @@ -726,7 +726,7 @@ Qt::Vertical - + Qt::CustomContextMenu @@ -745,11 +745,6 @@ false - - - 1 - - @@ -843,11 +838,6 @@ QLineEdit
gui/common/LineEditClear.h
- - RSTreeWidget - QTreeWidget -
gui/common/RSTreeWidget.h
-
RSTabWidget QTabWidget diff --git a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h index edb8515e4..c8b83dbe0 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h +++ b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h @@ -21,6 +21,8 @@ #ifndef _GXS_ID_TREEWIDGETITEM_H #define _GXS_ID_TREEWIDGETITEM_H +#include +#include #include #include "gui/common/RSTreeWidgetItem.h" @@ -69,4 +71,83 @@ private: RsGxsImage mAvatar; }; +// This class is responsible of rendering authors of type RsGxsId in tree views. Used in forums, messages, etc. + +class GxsIdTreeItemDelegate: public QStyledItemDelegate +{ +public: + GxsIdTreeItemDelegate() {} + + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override + { + QStyleOptionViewItemV4 opt = option; + initStyleOption(&opt, index); + + // disable default icon + opt.icon = QIcon(); + const QRect r = option.rect; + + RsGxsId id(index.data(Qt::UserRole).toString().toStdString()); + QString str; + QList icons; + QString comment; + + QFontMetricsF fm(option.font); + float f = fm.height(); + + QIcon icon ; + + if(!GxsIdDetails::MakeIdDesc(id, true, str, icons, comment,GxsIdDetails::ICON_TYPE_AVATAR)) + icon = GxsIdDetails::getLoadingIcon(id); + else + icon = *icons.begin(); + + QPixmap pix = icon.pixmap(r.size()); + + return QSize(1.2*(pix.width() + fm.width(str)),std::max(1.1*pix.height(),1.4*fm.height())); + } + + virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex& index) const override + { + if(!index.isValid()) + { + std::cerr << "(EE) attempt to draw an invalid index." << std::endl; + return ; + } + + QStyleOptionViewItemV4 opt = option; + initStyleOption(&opt, index); + + // disable default icon + opt.icon = QIcon(); + // draw default item + QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &opt, painter, 0); + + const QRect r = option.rect; + + RsGxsId id(index.data(Qt::UserRole).toString().toStdString()); + QString str; + QList icons; + QString comment; + + QFontMetricsF fm(painter->font()); + float f = fm.height(); + + QIcon icon ; + + if(!GxsIdDetails::MakeIdDesc(id, true, str, icons, comment,GxsIdDetails::ICON_TYPE_AVATAR)) + icon = GxsIdDetails::getLoadingIcon(id); + else + icon = *icons.begin(); + + QPixmap pix = icon.pixmap(r.size()); + const QPoint p = QPoint(r.height()/2.0, (r.height() - pix.height())/2); + + // draw pixmap at center of item + painter->drawPixmap(r.topLeft() + p, pix); + painter->drawText(r.topLeft() + QPoint(r.height()+ f/2.0 + f/2.0,f*1.0), str); + } +}; + + #endif diff --git a/retroshare-gui/src/gui/msgs/MessageModel.h b/retroshare-gui/src/gui/msgs/MessageModel.h index 5cf13f370..89b0894f8 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.h +++ b/retroshare-gui/src/gui/msgs/MessageModel.h @@ -71,6 +71,15 @@ public: explicit RsMessageModel(QObject *parent = NULL); ~RsMessageModel(){} + enum BoxName { + BOX_NONE = 0x00, + BOX_INBOX = 0x01, + BOX_OUTBOX = 0x02, + BOX_DRAFTS = 0x03, + BOX_SENT = 0x04, + BOX_TRASH = 0x05 + }; + enum Columns { COLUMN_THREAD_STAR =0x00, COLUMN_THREAD_ATTACHMENT =0x01, @@ -96,6 +105,7 @@ public: // This method will asynchroneously update the data + void setCurrentBox(BoxName bn) {} void updateMessages(); const RsMessageId& currentMessageId() const; diff --git a/retroshare-gui/src/gui/msgs/MessageWidget.cpp b/retroshare-gui/src/gui/msgs/MessageWidget.cpp index 02d74b5da..5294c1d26 100644 --- a/retroshare-gui/src/gui/msgs/MessageWidget.cpp +++ b/retroshare-gui/src/gui/msgs/MessageWidget.cpp @@ -108,7 +108,7 @@ MessageWidget *MessageWidget::openMsg(const std::string &msgId, bool window) msgWidget->isWindow = window; msgWidget->fill(msgId); - if (parent) { + if (parent) { parent->addWidget(msgWidget); } From 7a7ebed9d2f3764afb7e89371ee195f265acc74b Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 10 Feb 2019 15:13:39 +0100 Subject: [PATCH 03/81] improved Mail model --- retroshare-gui/src/gui/MessagesDialog.cpp | 2 ++ retroshare-gui/src/gui/msgs/MessageModel.cpp | 19 ++++++++++++------- retroshare-gui/src/gui/msgs/MessageModel.h | 1 - 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 74f370540..684c08de9 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -195,6 +195,8 @@ MessagesDialog::MessagesDialog(QWidget *parent) mMessageProxyModel->setSortRole(RsMessageModel::SortRole); ui.messageTreeWidget->setModel(mMessageProxyModel); + mMessageModel->updateMessages(); + mMessageProxyModel->setFilterRole(RsMessageModel::FilterRole); mMessageProxyModel->setFilterRegExp(QRegExp(QString(RsMessageModel::FilterString))) ; diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index b1572a844..47430fab3 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -36,6 +36,8 @@ #define IS_MESSAGE_UNREAD(flags) (flags & RS_MSG_UNREAD_BY_USER) +#define IMAGE_STAR_ON ":/images/star-on-16.png" + std::ostream& operator<<(std::ostream& o, const QModelIndex& i);// defined elsewhere const QString RsMessageModel::FilterString("filtered"); @@ -161,7 +163,9 @@ QVariant RsMessageModel::headerData(int section, Qt::Orientation orientation, in switch(section) { case COLUMN_THREAD_DATE: return tr("Date"); - case COLUMN_THREAD_AUTHOR: return tr("Author"); + case COLUMN_THREAD_AUTHOR: return tr("From"); + case COLUMN_THREAD_SUBJECT: return tr("Subject"); + case COLUMN_THREAD_TAGS: return tr("Tags"); default: return QVariant(); } @@ -169,6 +173,7 @@ QVariant RsMessageModel::headerData(int section, Qt::Orientation orientation, in if(role == Qt::DecorationRole) switch(section) { + case COLUMN_THREAD_STAR: return QIcon(IMAGE_STAR_ON); case COLUMN_THREAD_READ: return QIcon(":/images/message-state-read.png"); default: return QVariant(); @@ -179,7 +184,7 @@ QVariant RsMessageModel::headerData(int section, Qt::Orientation orientation, in QVariant RsMessageModel::data(const QModelIndex &index, int role) const { -#ifdef DEBUG_FORUMMODEL +#ifdef DEBUG_MESSAGE_MODEL std::cerr << "calling data(" << index << ") role=" << role << std::endl; #endif @@ -196,13 +201,13 @@ QVariant RsMessageModel::data(const QModelIndex &index, int role) const quintptr ref = (index.isValid())?index.internalId():0 ; uint32_t entry = 0; -#ifdef DEBUG_FORUMMODEL +#ifdef DEBUG_MESSAGE_MODEL std::cerr << "data(" << index << ")" ; #endif if(!ref) { -#ifdef DEBUG_FORUMMODEL +#ifdef DEBUG_MESSAGE_MODEL std::cerr << " [empty]" << std::endl; #endif return QVariant() ; @@ -210,7 +215,7 @@ QVariant RsMessageModel::data(const QModelIndex &index, int role) const if(!convertInternalIdToMsgIndex(ref,entry) || entry >= mMessages.size()) { -#ifdef DEBUG_FORUMMODEL +#ifdef DEBUG_MESSAGE_MODEL std::cerr << "Bad pointer: " << (void*)ref << std::endl; #endif return QVariant() ; @@ -225,7 +230,7 @@ QVariant RsMessageModel::data(const QModelIndex &index, int role) const return QVariant(font); } -#ifdef DEBUG_FORUMMODEL +#ifdef DEBUG_MESSAGE_MODEL std::cerr << " [ok]" << std::endl; #endif @@ -439,7 +444,7 @@ void RsMessageModel::setMessages(const std::list& msgs // now update prow for all posts -#ifdef DEBUG_FORUMMODEL +#ifdef DEBUG_MESSAGE_MODEL debug_dump(); #endif diff --git a/retroshare-gui/src/gui/msgs/MessageModel.h b/retroshare-gui/src/gui/msgs/MessageModel.h index 89b0894f8..438a3aa5f 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.h +++ b/retroshare-gui/src/gui/msgs/MessageModel.h @@ -164,7 +164,6 @@ private: static bool convertInternalIdToMsgIndex(quintptr ref,uint32_t& index); static void computeReputationLevel(uint32_t forum_sign_flags, ForumModelPostEntry& entry); - void update_posts(const RsGxsGroupId &group_id); uint32_t updateFilterStatus(ForumModelIndex i,int column,const QStringList& strings); static void generateMissingItem(const RsGxsMessageId &msgId,ForumModelPostEntry& entry); From 7a2c81d06b64fd5923906d3c8ca3634adf91c0bb Mon Sep 17 00:00:00 2001 From: Gioacchino Mazzurco Date: Wed, 13 Feb 2019 17:07:03 -0300 Subject: [PATCH 04/81] Deprecate rs_usleep as it is not useful anymore C++11 standard library offer better functions --- libretroshare/src/util/rstime.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libretroshare/src/util/rstime.h b/libretroshare/src/util/rstime.h index cc3208dbc..397edfee1 100644 --- a/libretroshare/src/util/rstime.h +++ b/libretroshare/src/util/rstime.h @@ -28,6 +28,7 @@ #include #endif #include // Added for comfort of users of this util header +#include "util/rsdeprecate.h" /** * Safer alternative to time_t. @@ -47,7 +48,7 @@ namespace rstime { /*! * \brief This is a cross-system definition of usleep, which accepts any 32 bits number of micro-seconds. */ - + RS_DEPRECATED_FOR("std::this_thread::sleep_for") int rs_usleep(uint32_t micro_seconds); /* Use this class to measure and display time duration of a given environment: From ac1d24dba4c09f5660ea05a15b988482aee8608b Mon Sep 17 00:00:00 2001 From: Gioacchino Mazzurco Date: Wed, 13 Feb 2019 17:07:59 -0300 Subject: [PATCH 05/81] Remove misleading comment from channels public API --- libretroshare/src/retroshare/rsgxschannels.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libretroshare/src/retroshare/rsgxschannels.h b/libretroshare/src/retroshare/rsgxschannels.h index 2f51f2652..4d28cad22 100644 --- a/libretroshare/src/retroshare/rsgxschannels.h +++ b/libretroshare/src/retroshare/rsgxschannels.h @@ -42,7 +42,7 @@ class RsGxsChannels; */ extern RsGxsChannels* rsGxsChannels; -// These should be in rsgxscommon.h + struct RsGxsChannelGroup : RsSerializable { RsGroupMetaData mMeta; From 6633e8bb28e579dd6ab4841cfaebe09f977881ea Mon Sep 17 00:00:00 2001 From: Gioacchino Mazzurco Date: Wed, 13 Feb 2019 17:08:38 -0300 Subject: [PATCH 06/81] Expose RsIdentity JSON API --- libretroshare/src/retroshare/rsidentity.h | 269 +++++++++++++++++----- libretroshare/src/services/p3idservice.cc | 163 ++++++++++++- libretroshare/src/services/p3idservice.h | 51 +++- 3 files changed, 411 insertions(+), 72 deletions(-) diff --git a/libretroshare/src/retroshare/rsidentity.h b/libretroshare/src/retroshare/rsidentity.h index b7895ad44..72917e159 100644 --- a/libretroshare/src/retroshare/rsidentity.h +++ b/libretroshare/src/retroshare/rsidentity.h @@ -4,7 +4,7 @@ * libretroshare: retroshare core library * * * * Copyright (C) 2012 Robert Fernie * - * Copyright (C) 2018 Gioacchino Mazzurco * + * Copyright (C) 2019 Gioacchino Mazzurco * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * @@ -20,12 +20,12 @@ * along with this program. If not, see . * * * *******************************************************************************/ -#ifndef RETROSHARE_IDENTITY_GUI_INTERFACE_H -#define RETROSHARE_IDENTITY_GUI_INTERFACE_H +#pragma once -#include +#include #include #include +#include #include "retroshare/rstokenservice.h" #include "retroshare/rsgxsifacehelper.h" @@ -37,9 +37,13 @@ #include "serialiser/rstypeserializer.h" #include "util/rsdeprecate.h" -/* The Main Interface Class - for information about your Peers */ struct RsIdentity; -extern RsIdentity *rsIdentity; + +/** + * Pointer to global instance of RsIdentity service implementation + * @jsonapi{development} + */ +extern RsIdentity* rsIdentity; // GroupFlags: Only one so far: @@ -106,7 +110,7 @@ struct RsGxsIdGroup : RsSerializable { RsGxsIdGroup() : mLastUsageTS(0), mPgpKnown(false), mIsAContact(false) {} - ~RsGxsIdGroup() {} + virtual ~RsGxsIdGroup() {} RsGroupMetaData mMeta; @@ -144,18 +148,18 @@ struct RsGxsIdGroup : RsSerializable /// @see RsSerializable void serial_process( RsGenericSerializer::SerializeJob j, - RsGenericSerializer::SerializeContext& ctx ); + RsGenericSerializer::SerializeContext& ctx ) override; }; std::ostream &operator<<(std::ostream &out, const RsGxsIdGroup &group); // DATA TYPE FOR EXTERNAL INTERFACE. -class RsRecognTag +struct RsRecognTag { - public: - RsRecognTag(uint16_t tc, uint16_t tt, bool v) - :tag_class(tc), tag_type(tt), valid(v) { return; } + RsRecognTag(uint16_t tc, uint16_t tt, bool v) : + tag_class(tc), tag_type(tt), valid(v) {} + uint16_t tag_class; uint16_t tag_type; bool valid; @@ -268,11 +272,11 @@ struct RsIdentityUsage : RsSerializable std::string mComment; bool operator<(const RsIdentityUsage& u) const { return mHash < u.mHash; } - RsFileHash mHash ; + RsFileHash mHash; /// @see RsSerializable void serial_process( RsGenericSerializer::SerializeJob j, - RsGenericSerializer::SerializeContext& ctx ) + RsGenericSerializer::SerializeContext& ctx ) override { RS_SERIAL_PROCESS(mServiceId); RS_SERIAL_PROCESS(mUsageCode); @@ -329,7 +333,7 @@ struct RsIdentityDetails : RsSerializable RS_SERIAL_PROCESS(mFlags); RS_SERIAL_PROCESS(mPgpId); //RS_SERIAL_PROCESS(mReputation); - //RS_SERIAL_PROCESS(mAvatar); + RS_SERIAL_PROCESS(mAvatar); RS_SERIAL_PROCESS(mPublishTS); RS_SERIAL_PROCESS(mLastUsageTS); RS_SERIAL_PROCESS(mUseCases); @@ -338,73 +342,214 @@ struct RsIdentityDetails : RsSerializable - +/** The Main Interface Class for GXS people identities */ struct RsIdentity : RsGxsIfaceHelper { - explicit RsIdentity(RsGxsIface& gxs): RsGxsIfaceHelper(gxs) {} - virtual ~RsIdentity() {} + explicit RsIdentity(RsGxsIface& gxs) : RsGxsIfaceHelper(gxs) {} + virtual ~RsIdentity() {} - /********************************************************************************************/ - /********************************************************************************************/ + /** + * @brief Create a new identity + * @jsonapi{development} + * @param[out] id storage for the created identity Id + * @param[in] name Name of the identity + * @param[in] avatar Image associated to the identity + * @param[in] pseudonimous true for unsigned identity, false otherwise + * @param[in] pgpPassword password to unlock PGP to sign identity, + * not implemented yet + * @return false on error, true otherwise + */ + virtual bool createIdentity( + RsGxsId& id, + const std::string& name, const RsGxsImage& avatar = RsGxsImage(), + bool pseudonimous = true, const std::string& pgpPassword = "" ) = 0; - // For Other Services.... - // It should be impossible for them to get a message which we don't have the identity. - // Its a major error if we don't have the identity. + /** + * @brief Locally delete given identity + * @jsonapi{development} + * @param[in] id Id of the identity + * @return false on error, true otherwise + */ + virtual bool deleteIdentity(RsGxsId& id) = 0; - // We cache all identities, and provide alternative (instantaneous) - // functions to extract info, rather than the standard Token system. + /** + * @brief Update identity data (name, avatar...) + * @jsonapi{development} + * @param[in] identityData updated identiy data + * @return false on error, true otherwise + */ + virtual bool updateIdentity(RsGxsIdGroup& identityData) = 0; - //virtual bool getNickname(const RsGxsId &id, std::string &nickname) = 0; - virtual bool getIdDetails(const RsGxsId &id, RsIdentityDetails &details) = 0; + /** + * @brief Get identity details, from the cache + * @param[in] id Id of the identity + * @param[out] details Storage for the identity details + * @return false on error, true otherwise + */ + virtual bool getIdDetails(const RsGxsId& id, RsIdentityDetails& details) = 0; - // Fills up list of all own ids. Returns false if ids are not yet loaded. - virtual bool getOwnIds(std::list &ownIds,bool only_signed_ids = false) = 0; - virtual bool isOwnId(const RsGxsId& id) = 0; + /** + * @brief Get last seen usage time of given identity + * @jsonapi{development} + * @param[in] id Id of the identity + * @return timestamp of last seen usage + */ + virtual rstime_t getLastUsageTS(const RsGxsId& id) = 0; - // - virtual bool submitOpinion(uint32_t& token, const RsGxsId &id, - bool absOpinion, int score) = 0; - virtual bool createIdentity(uint32_t& token, RsIdentityParameters ¶ms) = 0; + /** + * @brief Get own signed ids + * @jsonapi{development} + * @param[out] ids storage for the ids + * @return false on error, true otherwise + */ + virtual bool getOwnSignedIds(std::vector ids) = 0; - virtual bool updateIdentity(uint32_t& token, RsGxsIdGroup &group) = 0; - virtual bool deleteIdentity(uint32_t& token, RsGxsIdGroup &group) = 0; + /** + * @brief Get own pseudonimous (unsigned) ids + * @jsonapi{development} + * @param[out] ids storage for the ids + * @return false on error, true otherwise + */ + virtual bool getOwnPseudonimousIds(std::vector ids) = 0; - virtual void setDeleteBannedNodesThreshold(uint32_t days) =0; - virtual uint32_t deleteBannedNodesThreshold() =0; + /** + * @brief Check if an id is own + * @jsonapi{development} + * @param[in] id Id to check + * @return true if the id is own, false otherwise + */ + virtual bool isOwnId(const RsGxsId& id) = 0; - virtual bool parseRecognTag(const RsGxsId &id, const std::string &nickname, - const std::string &tag, RsRecognTagDetails &details) = 0; - virtual bool getRecognTagRequest(const RsGxsId &id, const std::string &comment, - uint16_t tag_class, uint16_t tag_type, std::string &tag) = 0; + /** + * @brief Get base64 representation of an identity + * @jsonapi{development} + * @param[in] id Id of the identity + * @param[out] base64String storage for the identity base64 + * @return false on error, true otherwise + */ + virtual bool identityToBase64( const RsGxsId& id, + std::string& base64String ) = 0; - virtual bool setAsRegularContact(const RsGxsId& id,bool is_a_contact) = 0 ; - virtual bool isARegularContact(const RsGxsId& id) = 0 ; + /** + * @brief Import identity from base64 representation + * @jsonapi{development} + * @param[in] base64String base64 representation of the identity to import + * @param[out] id storage for the identity id + * @return false on error, true otherwise + */ + virtual bool identityFromBase64( const std::string& base64String, + RsGxsId& id ) = 0; + + /** + * @brief Get identities summaries list. + * @jsonapi{development} + * @param[out] ids list where to store the identities + * @return false if something failed, true otherwhise + */ + virtual bool getIdentitiesSummaries(std::list& ids) = 0; + + /** + * @brief Get identities information (name, avatar...). + * Blocking API. + * @jsonapi{development} + * @param[in] ids ids of the channels of which to get the informations + * @param[out] idsInfo storage for the identities informations + * @return false if something failed, true otherwhise + */ + virtual bool getIdentitiesInfo( + const std::set& ids, + std::vector& idsInfo ) = 0; + + /** + * @brief Check if an identity is contact + * @jsonapi{development} + * @param[in] id Id of the identity + * @return true if it is a conctact, false otherwise + */ + virtual bool isARegularContact(const RsGxsId& id) = 0; + + /** + * @brief Set/unset identity as contact + * @param[in] id Id of the identity + * @param[in] isContact true to set, false to unset + * @return false on error, true otherwise + */ + virtual bool setAsRegularContact(const RsGxsId& id, bool isContact) = 0; + + /** + * @brief Toggle automatic flagging signed by friends identity as contact + * @jsonapi{development} + * @param[in] enabled true to enable, false to disable + */ + virtual void setAutoAddFriendIdsAsContact(bool enabled) = 0; + + /** + * @brief Check if automatic signed by friend identity contact flagging is + * enabled + * @jsonapi{development} + * @return true if enabled, false otherwise + */ + virtual bool autoAddFriendIdsAsContact() = 0; + + /** + * @brief Get number of days after which delete a banned identities + * @jsonapi{development} + * @return number of days + */ + virtual uint32_t deleteBannedNodesThreshold() = 0; + + /** + * @brief Set number of days after which delete a banned identities + * @jsonapi{development} + * @param[in] days number of days + */ + virtual void setDeleteBannedNodesThreshold(uint32_t days) = 0; + + + RS_DEPRECATED + virtual bool getGroupSerializedData( + const uint32_t& token, + std::map& serialized_groups ) = 0; + + RS_DEPRECATED + virtual bool parseRecognTag( + const RsGxsId &id, const std::string& nickname, + const std::string& tag, RsRecognTagDetails& details) = 0; + + RS_DEPRECATED + virtual bool getRecognTagRequest( + const RsGxsId& id, const std::string& comment, uint16_t tag_class, + uint16_t tag_type, std::string& tag) = 0; + + RS_DEPRECATED virtual uint32_t nbRegularContacts() =0; - virtual void setAutoAddFriendIdsAsContact(bool b) =0; - virtual bool autoAddFriendIdsAsContact() =0; + RS_DEPRECATED_FOR(identityToBase64) virtual bool serialiseIdentityToMemory( const RsGxsId& id, std::string& radix_string ) = 0; + RS_DEPRECATED_FOR(identityFromBase64) virtual bool deserialiseIdentityFromMemory( const std::string& radix_string, RsGxsId* id = nullptr ) = 0; - /*! - * \brief overallReputationLevel - * Returns the overall reputation level of the supplied identity. See rsreputations.h - * \param id - * \return - */ - virtual rstime_t getLastUsageTS(const RsGxsId &id) =0; + /// Fills up list of all own ids. Returns false if ids are not yet loaded. + RS_DEPRECATED_FOR("getOwnSignedIds getOwnPseudonimousIds") + virtual bool getOwnIds( std::list &ownIds, + bool only_signed_ids = false ) = 0; - // Specific RsIdentity Functions.... - /* Specific Service Data */ - /* We expose these initially for testing / GUI purposes. - */ + RS_DEPRECATED + virtual bool createIdentity(uint32_t& token, RsIdentityParameters ¶ms) = 0; - virtual bool getGroupData(const uint32_t &token, std::vector &groups) = 0; - virtual bool getGroupSerializedData(const uint32_t &token, std::map& serialized_groups)=0; - //virtual bool getMsgData(const uint32_t &token, std::vector &opinions) = 0; + RS_DEPRECATED_FOR(RsReputations) + virtual bool submitOpinion(uint32_t& token, const RsGxsId &id, + bool absOpinion, int score) = 0; + RS_DEPRECATED + virtual bool updateIdentity(uint32_t& token, RsGxsIdGroup &group) = 0; + + RS_DEPRECATED + virtual bool deleteIdentity(uint32_t& token, RsGxsIdGroup &group) = 0; + + RS_DEPRECATED_FOR("getIdentitiesSummaries getIdentitiesInfo") + virtual bool getGroupData( const uint32_t& token, + std::vector& groups) = 0; }; - -#endif // RETROSHARE_IDENTITY_GUI_INTERFACE_H diff --git a/libretroshare/src/services/p3idservice.cc b/libretroshare/src/services/p3idservice.cc index 10650b800..e4046210b 100644 --- a/libretroshare/src/services/p3idservice.cc +++ b/libretroshare/src/services/p3idservice.cc @@ -21,6 +21,7 @@ * * *******************************************************************************/ #include +#include #include "services/p3idservice.h" #include "pgp/pgpauxutils.h" @@ -207,6 +208,29 @@ void p3IdService::setNes(RsNetworkExchangeService *nes) mNes = nes; } +bool p3IdService::getIdentitiesInfo( + const std::set& ids, std::vector& idsInfo ) +{ + uint32_t token; + RsTokReqOptions opts; + opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; + std::list idsList(ids.begin(), ids.end()); + + if( !requestGroupInfo(token, opts, idsList) + || waitToken(token) != RsTokenService::COMPLETE ) return false; + return getGroupData(token, idsInfo); +} + +bool p3IdService::getIdentitiesSummaries(std::list& ids) +{ + uint32_t token; + RsTokReqOptions opts; + opts.mReqType = GXS_REQUEST_TYPE_GROUP_META; + if( !requestGroupInfo(token, opts) + || waitToken(token) != RsTokenService::COMPLETE ) return false; + return getGroupSummary(token, ids); +} + uint32_t p3IdService::idAuthenPolicy() { uint32_t policy = 0; @@ -727,6 +751,46 @@ bool p3IdService::isOwnId(const RsGxsId& id) return std::find(mOwnIds.begin(),mOwnIds.end(),id) != mOwnIds.end() ; } + + +bool p3IdService::getOwnSignedIds(std::vector ids) +{ + ids.clear(); + + std::chrono::seconds maxWait(5); + auto timeout = std::chrono::steady_clock::now() + maxWait; + while( !ownIdsAreLoaded() && std::chrono::steady_clock::now() < timeout ) + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + if(ownIdsAreLoaded()) + { + RS_STACK_MUTEX(mIdMtx); + ids.reserve(mOwnSignedIds.size()); + ids.insert(ids.end(), mOwnSignedIds.begin(), mOwnSignedIds.end()); + return true; + } + + return false; +} + +bool p3IdService::getOwnPseudonimousIds(std::vector ids) +{ + ids.clear(); + std::vector signedV; + + // this implicitely ensure ids are already loaded ;) + if(!getOwnSignedIds(signedV)) return false; + std::set signedS(signedV.begin(), signedV.end()); + + { + RS_STACK_MUTEX(mIdMtx); + std::copy_if(mOwnIds.begin(), mOwnIds.end(), ids.end(), + [&](const RsGxsId& id) {return !signedS.count(id);}); + } + + return true; +} + bool p3IdService::getOwnIds(std::list &ownIds,bool signed_only) { RsStackMutex stack(mIdMtx); /********** STACK LOCKED MTX ******/ @@ -742,6 +806,11 @@ bool p3IdService::getOwnIds(std::list &ownIds,bool signed_only) return true ; } + +bool p3IdService::identityToBase64( const RsGxsId& id, + std::string& base64String ) +{ return serialiseIdentityToMemory(id, base64String); } + bool p3IdService::serialiseIdentityToMemory( const RsGxsId& id, std::string& radix_string ) { @@ -803,6 +872,10 @@ void p3IdService::handle_get_serialized_grp(uint32_t token) mSerialisedIdentities[RsGxsId(id)] = s ; } +bool p3IdService::identityFromBase64( + const std::string& base64String, RsGxsId& id ) +{ return deserialiseIdentityFromMemory(base64String, &id); } + bool p3IdService::deserialiseIdentityFromMemory(const std::string& radix_string, RsGxsId* id /* = nullptr */) { @@ -826,6 +899,47 @@ bool p3IdService::deserialiseIdentityFromMemory(const std::string& radix_string, return true; } +bool p3IdService::createIdentity( + RsGxsId& id, + const std::string& name, const RsGxsImage& avatar, + bool pseudonimous, const std::string& pgpPassword) +{ + if(!pgpPassword.empty()) + std::cerr<< __PRETTY_FUNCTION__ << " Warning! PGP Password handling " + << "not implemented yet!" << std::endl; + + RsIdentityParameters params; + params.isPgpLinked = !pseudonimous; + params.nickname = name; + params.mImage = avatar; + + uint32_t token; + if(!createIdentity(token, params)) + { + std::cerr << __PRETTY_FUNCTION__ << " Error! Failed creating group." + << std::endl; + return false; + } + + if(waitToken(token) != RsTokenService::COMPLETE) + { + std::cerr << __PRETTY_FUNCTION__ << " Error! GXS operation failed." + << std::endl; + return false; + } + + RsGroupMetaData meta; + if(!RsGenExchange::getPublishedGroupMeta(token, meta)) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! Failure getting updated " + << " group data." << std::endl; + return false; + } + + id = RsGxsId(meta.mGroupId); + return true; +} + bool p3IdService::createIdentity(uint32_t& token, RsIdentityParameters ¶ms) { @@ -863,6 +977,26 @@ bool p3IdService::createIdentity(uint32_t& token, RsIdentityParameters ¶ms) return true; } +bool p3IdService::updateIdentity(RsGxsIdGroup& identityData) +{ + uint32_t token; + if(!updateGroup(token, identityData)) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! Failed updating group." + << std::endl; + return false; + } + + if(waitToken(token) != RsTokenService::COMPLETE) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! GXS operation failed." + << std::endl; + return false; + } + + return true; +} + bool p3IdService::updateIdentity(uint32_t& token, RsGxsIdGroup &group) { #ifdef DEBUG_IDS @@ -876,6 +1010,27 @@ bool p3IdService::updateIdentity(uint32_t& token, RsGxsIdGroup &group) return false; } +bool p3IdService::deleteIdentity(RsGxsId& id) +{ + uint32_t token; + RsGxsGroupId grouId = RsGxsGroupId(id); + if(!deleteGroup(token, grouId)) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! Failed deleting group." + << std::endl; + return false; + } + + if(waitToken(token) != RsTokenService::COMPLETE) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! GXS operation failed." + << std::endl; + return false; + } + + return true; +} + bool p3IdService::deleteIdentity(uint32_t& token, RsGxsIdGroup &group) { #ifdef DEBUG_IDS @@ -883,7 +1038,7 @@ bool p3IdService::deleteIdentity(uint32_t& token, RsGxsIdGroup &group) std::cerr << std::endl; #endif - deleteGroup(token, group); + deleteGroup(token, group.mMeta.mGroupId); return false; } @@ -1796,16 +1951,16 @@ bool p3IdService::updateGroup(uint32_t& token, RsGxsIdGroup &group) return true; } -bool p3IdService::deleteGroup(uint32_t& token, RsGxsIdGroup &group) +bool p3IdService::deleteGroup(uint32_t& token, RsGxsGroupId& groupId) { - RsGxsId id(group.mMeta.mGroupId); + RsGxsId id(groupId); #ifdef DEBUG_IDS std::cerr << "p3IdService::deleteGroup() Deleting RsGxsId: " << id; std::cerr << std::endl; #endif - RsGenExchange::deleteGroup(token,group.mMeta.mGroupId); + RsGenExchange::deleteGroup(token, groupId); // if its in the cache - clear it. { diff --git a/libretroshare/src/services/p3idservice.h b/libretroshare/src/services/p3idservice.h index 0d0d47636..f585804a9 100644 --- a/libretroshare/src/services/p3idservice.h +++ b/libretroshare/src/services/p3idservice.h @@ -215,9 +215,8 @@ struct SerialisedIdentityStruct rstime_t mLastUsageTS; }; -// Not sure exactly what should be inherited here? -// Chris - please correct as necessary. - +// We cache all identities, and provide alternative (instantaneous) +// functions to extract info, rather than the horrible Token system. class p3IdService: public RsGxsIdExchange, public RsIdentity, public GxsTokenQueue, public RsTickEvent, public p3Config { public: @@ -239,6 +238,13 @@ public: /* Data Specific Interface */ + /// @see RsIdentity + bool getIdentitiesInfo(const std::set& ids, + std::vector& idsInfo ) override; + + /// @see RsIdentity + bool getIdentitiesSummaries(std::list& ids) override; + // These are exposed via RsIdentity. virtual bool getGroupData(const uint32_t &token, std::vector &groups); virtual bool getGroupSerializedData(const uint32_t &token, std::map& serialized_groups); @@ -248,7 +254,7 @@ public: // These are local - and not exposed via RsIdentity. virtual bool createGroup(uint32_t& token, RsGxsIdGroup &group); virtual bool updateGroup(uint32_t& token, RsGxsIdGroup &group); - virtual bool deleteGroup(uint32_t& token, RsGxsIdGroup &group); + virtual bool deleteGroup(uint32_t& token, RsGxsGroupId& group); //virtual bool createMsg(uint32_t& token, RsGxsIdOpinion &opinion); /**************** RsIdentity External Interface. @@ -263,12 +269,28 @@ public: //virtual bool getNickname(const RsGxsId &id, std::string &nickname); virtual bool getIdDetails(const RsGxsId &id, RsIdentityDetails &details); - // + RS_DEPRECATED_FOR(RsReputations) virtual bool submitOpinion(uint32_t& token, const RsGxsId &id, bool absOpinion, int score); + + /// @see RsIdentity + virtual bool createIdentity( + RsGxsId& id, + const std::string& name, const RsGxsImage& avatar = RsGxsImage(), + bool pseudonimous = true, const std::string& pgpPassword = "" ) override; + virtual bool createIdentity(uint32_t& token, RsIdentityParameters ¶ms); + /// @see RsIdentity + bool updateIdentity(RsGxsIdGroup& identityData) override; + + RS_DEPRECATED virtual bool updateIdentity(uint32_t& token, RsGxsIdGroup &group); + + /// @see RsIdentity + bool deleteIdentity(RsGxsId& id) override; + + RS_DEPRECATED virtual bool deleteIdentity(uint32_t& token, RsGxsIdGroup &group); virtual void setDeleteBannedNodesThreshold(uint32_t days) ; @@ -289,6 +311,12 @@ public: /**************** RsGixs Implementation ***************/ + /// @see RsIdentity + bool getOwnSignedIds(std::vector ids) override; + + /// @see RsIdentity + bool getOwnPseudonimousIds(std::vector ids) override; + virtual bool getOwnIds(std::list &ownIds, bool signed_only = false); //virtual bool getPublicKey(const RsGxsId &id, RsTlvSecurityKey &key) ; @@ -350,6 +378,15 @@ public: const RsIdentityUsage &use_info ); virtual bool requestPrivateKey(const RsGxsId &id); + + /// @see RsIdentity + bool identityToBase64( const RsGxsId& id, + std::string& base64String ) override; + + /// @see RsIdentity + bool identityFromBase64( const std::string& base64String, + RsGxsId& id ) override; + virtual bool serialiseIdentityToMemory(const RsGxsId& id, std::string& radix_string); virtual bool deserialiseIdentityFromMemory(const std::string& radix_string, @@ -599,7 +636,9 @@ private: rstime_t mLastKeyCleaningTime ; rstime_t mLastConfigUpdate ; - bool mOwnIdsLoaded ; + bool mOwnIdsLoaded; + bool ownIdsAreLoaded() { RS_STACK_MUTEX(mIdMtx); return mOwnIdsLoaded; } + bool mAutoAddFriendsIdentitiesAsContacts; uint32_t mMaxKeepKeysBanned ; }; From 598521d1ac162500f470790dd47688c127069eca Mon Sep 17 00:00:00 2001 From: Gioacchino Mazzurco Date: Thu, 14 Feb 2019 18:52:35 -0300 Subject: [PATCH 07/81] Implement JSON API for circles --- libretroshare/src/retroshare/rsgxscircles.h | 255 +++++++++++++----- .../src/retroshare/rsgxsifacetypes.h | 4 +- libretroshare/src/services/p3gxscircles.cc | 137 ++++++++-- libretroshare/src/services/p3gxscircles.h | 25 +- retroshare.pri | 1 + 5 files changed, 324 insertions(+), 98 deletions(-) diff --git a/libretroshare/src/retroshare/rsgxscircles.h b/libretroshare/src/retroshare/rsgxscircles.h index f01e92ef3..d5f3543d0 100644 --- a/libretroshare/src/retroshare/rsgxscircles.h +++ b/libretroshare/src/retroshare/rsgxscircles.h @@ -3,7 +3,8 @@ * * * libretroshare: retroshare core library * * * - * Copyright 2012-2012 by Robert Fernie * + * Copyright (C) 2012 Robert Fernie * + * Copyright (C) 2018 Gioacchino Mazzurco * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * @@ -19,34 +20,31 @@ * along with this program. If not, see . * * * *******************************************************************************/ -#ifndef RETROSHARE_GXSCIRCLES_INTERFACE_H -#define RETROSHARE_GXSCIRCLES_INTERFACE_H +#pragma once -#include +#include #include #include #include #include "retroshare/rstypes.h" - -//typedef std::string RsGxsCircleId; -//typedef RsPgpId RsPgpId; -//typedef std::string RsCircleInternalId; - #include "retroshare/rstokenservice.h" #include "retroshare/rsgxsifacehelper.h" - #include "retroshare/rsidentity.h" +#include "serialiser/rsserializable.h" -/* The Main Interface Class - for information about your Peers */ class RsGxsCircles; -extern RsGxsCircles *rsGxsCircles; -typedef RsPgpId RsPgpId; +/** + * Pointer to global instance of RsGxsCircles service implementation + * @jsonapi{development} + */ +extern RsGxsCircles* rsGxsCircles; + +// TODO: convert to enum /// The meaning of the different circle types is: -/// TODO: convert to enum static const uint32_t GXS_CIRCLE_TYPE_UNKNOWN = 0x0000 ; /// Used to detect uninizialized values. static const uint32_t GXS_CIRCLE_TYPE_PUBLIC = 0x0001 ; // not restricted to a circle static const uint32_t GXS_CIRCLE_TYPE_EXTERNAL = 0x0002 ; // restricted to an external circle, made of RsGxsId @@ -62,90 +60,207 @@ static const uint32_t GXS_EXTERNAL_CIRCLE_FLAGS_ALLOWED = 0x0007 ;// user static const uint32_t GXS_CIRCLE_FLAGS_IS_EXTERNAL = 0x0008 ;// user is allowed -/* Permissions is part of GroupMetaData */ -class GxsPermissions +struct RsGxsCircleGroup : RsSerializable { -public: - uint32_t mCircleType; // PUBLIC, EXTERNAL or YOUREYESONLY. - RsGxsCircleId mCircleId; // If EXTERNAL, otherwise Blank. + virtual ~RsGxsCircleGroup() {} - // BELOW IS NOT SERIALISED - BUT MUST BE STORED LOCALLY BY GXS. (If YOUREYESONLY) - RsPeerId mOriginator; - RsGxsCircleId mInternalCircle; // if Originator == ownId, otherwise blank. + RsGroupMetaData mMeta; + + std::set mLocalFriends; + std::set mInvitedMembers; + std::set mSubCircles; +#ifdef V07_NON_BACKWARD_COMPATIBLE_CHANGE_UNNAMED +# error "Add description, and multiple owners/administrators to circles" + // or better in general to GXS groups +#endif + + /// @see RsSerializable + void serial_process( RsGenericSerializer::SerializeJob j, + RsGenericSerializer::SerializeContext& ctx) override + { + RS_SERIAL_PROCESS(mMeta); + RS_SERIAL_PROCESS(mLocalFriends); + RS_SERIAL_PROCESS(mInvitedMembers); + RS_SERIAL_PROCESS(mSubCircles); + } }; -class RsGxsCircleGroup +struct RsGxsCircleMsg : RsSerializable { - public: - RsGroupMetaData mMeta; // includes GxsPermissions, for control of group distribution. + virtual ~RsGxsCircleMsg() {} - std::set mLocalFriends; - std::set mInvitedMembers; - std::set mSubCircles; - - // Not Serialised. - // Internally inside rsCircles, this will be turned into: - // std::list mAllowedFriends; -}; - -class RsGxsCircleMsg -{ - public: RsMsgMetaData mMeta; - // Signature by user signifying that they want to be part of the group. - // maybe Phase 3. +#ifndef V07_NON_BACKWARD_COMPATIBLE_CHANGE_UNNAMED + /* This is horrible and should be changed into yet to be defined something + * reasonable in next non retrocompatible version */ std::string stuff; +#endif + + /// @see RsSerializable + void serial_process( RsGenericSerializer::SerializeJob j, + RsGenericSerializer::SerializeContext& ctx) override + { + RS_SERIAL_PROCESS(mMeta); + RS_SERIAL_PROCESS(stuff); + } }; -class RsGxsCircleDetails +struct RsGxsCircleDetails : RsSerializable { - public: - RsGxsCircleDetails() : mCircleType(GXS_CIRCLE_TYPE_EXTERNAL), mAmIAllowed(false) {} - - RsGxsCircleId mCircleId; - std::string mCircleName; + RsGxsCircleDetails() : + mCircleType(GXS_CIRCLE_TYPE_EXTERNAL), mAmIAllowed(false) {} + ~RsGxsCircleDetails() {} - uint32_t mCircleType; - RsGxsCircleId mRestrictedCircleId; - - bool mAmIAllowed ; // true when one of load GXS ids belong to the circle allowed list (admin list & subscribed list). + RsGxsCircleId mCircleId; + std::string mCircleName; - std::set mAllowedGxsIds; // This crosses admin list and subscribed list - std::set mAllowedNodes; - - std::map mSubscriptionFlags ; // subscription flags for all ids + uint32_t mCircleType; + RsGxsCircleId mRestrictedCircleId; + + /** true when one of load GXS ids belong to the circle allowed list (admin + * list & subscribed list). */ + bool mAmIAllowed; + + /// This crosses admin list and subscribed list + std::set mAllowedGxsIds; + std::set mAllowedNodes; + + /// subscription flags for all ids + std::map mSubscriptionFlags; + + /// @see RsSerializable + void serial_process( RsGenericSerializer::SerializeJob j, + RsGenericSerializer::SerializeContext& ctx) override + { + RS_SERIAL_PROCESS(mCircleId); + RS_SERIAL_PROCESS(mCircleName); + RS_SERIAL_PROCESS(mCircleType); + RS_SERIAL_PROCESS(mRestrictedCircleId); + RS_SERIAL_PROCESS(mAmIAllowed); + RS_SERIAL_PROCESS(mAllowedGxsIds); + RS_SERIAL_PROCESS(mAllowedNodes); + RS_SERIAL_PROCESS(mSubscriptionFlags); + } }; class RsGxsCircles: public RsGxsIfaceHelper { public: - RsGxsCircles(RsGxsIface& gxs) :RsGxsIfaceHelper(gxs) {} + RsGxsCircles(RsGxsIface& gxs) : RsGxsIfaceHelper(gxs) {} virtual ~RsGxsCircles() {} - /* External Interface (Cached stuff) */ - virtual bool getCircleDetails(const RsGxsCircleId &id, RsGxsCircleDetails &details) = 0; - virtual bool getCircleExternalIdList(std::list &circleIds) = 0; - virtual bool getCirclePersonalIdList(std::list &circleIds) = 0; + /** + * @brief Create new circle + * @jsonapi{development} + * @param[inout] cData input name and flags of the circle, storage for + * generated circle data id etc. + * @return false if something failed, true otherwhise + */ + virtual bool createCircle(RsGxsCircleGroup& cData) = 0; - /* membership management for external circles */ + /** + * @brief Edit own existing circle + * @jsonapi{development} + * @param[inout] cData Circle data with modifications, storage for data + * updatedad during the operation. + * @return false if something failed, true otherwhise + */ + virtual bool editCircle(RsGxsCircleGroup& cData) = 0; - virtual bool requestCircleMembership(const RsGxsId& own_gxsid,const RsGxsCircleId& circle_id)=0 ; - virtual bool cancelCircleMembership(const RsGxsId& own_gxsid,const RsGxsCircleId& circle_id)=0 ; + /** + * @brief Get circle details. Memory cached + * @jsonapi{development} + * @param[in] id Id of the circle + * @param[out] details Storage for the circle details + * @return false if something failed, true otherwhise + */ + virtual bool getCircleDetails( + const RsGxsCircleId& id, RsGxsCircleDetails& details ) = 0; - /* standard load */ - virtual bool getGroupData(const uint32_t &token, std::vector &groups) = 0; - virtual bool getMsgData(const uint32_t &token, std::vector &msgs) = 0; + /** + * @brief Get list of known external circles ids. Memory cached + * @jsonapi{development} + * @param[in] circleIds Storage for circles id list + * @return false if something failed, true otherwhise + */ + virtual bool getCircleExternalIdList( + std::list& circleIds ) = 0; - /* make new group */ + /** + * @brief Get circles summaries list. + * @jsonapi{development} + * @param[out] circles list where to store the circles summaries + * @return false if something failed, true otherwhise + */ + virtual bool getCirclesSummaries(std::list& circles) = 0; + + /** + * @brief Get circles information + * @jsonapi{development} + * @param[in] circlesIds ids of the circles of which to get the informations + * @param[out] circlesInfo storage for the circles informations + * @return false if something failed, true otherwhise + */ + virtual bool getCirclesInfo( + const std::list& circlesIds, + std::vector& circlesInfo ) = 0; + + /** + * @brief Get circle requests + * @jsonapi{development} + * @param[in] circleId id of the circle of which the requests are requested + * @param[out] requests storage for the circle requests + * @return false if something failed, true otherwhise + */ + virtual bool getCircleRequests( const RsGxsGroupId& circleId, + std::vector& requests ) = 0; + + /** + * @brief Invite identities to circle + * @jsonapi{development} + * @param[in] identities ids of the identities to invite + * @param[in] circleId Id of the circle you own and want to invite ids in + * @return false if something failed, true otherwhise + */ + virtual bool inviteIdsToCircle( const std::set& identities, + const RsGxsCircleId& circleId ) = 0; + + /** + * @brief Request circle membership, or accept circle invitation + * @jsonapi{development} + * @param[in] ownGxsId Id of own identity to introduce to the circle + * @param[in] circleId Id of the circle to which ask for inclusion + * @return false if something failed, true otherwhise + */ + virtual bool requestCircleMembership( + const RsGxsId& ownGxsId, const RsGxsCircleId& circleId ) = 0; + + /** + * @brief Leave given circle + * @jsonapi{development} + * @param[in] ownGxsId Own id to remove from the circle + * @param[in] circleId Id of the circle to leave + * @return false if something failed, true otherwhise + */ + virtual bool cancelCircleMembership( + const RsGxsId& ownGxsId, const RsGxsCircleId& circleId ) = 0; + + RS_DEPRECATED_FOR("getCirclesSummaries getCirclesInfo") + virtual bool getGroupData( + const uint32_t& token, std::vector& groups ) = 0; + + RS_DEPRECATED_FOR(getCirclesRequests) + virtual bool getMsgData( + const uint32_t& token, std::vector& msgs ) = 0; + + /// make new group + RS_DEPRECATED_FOR(createCircle) virtual void createGroup(uint32_t& token, RsGxsCircleGroup &group) = 0; - /* update an existing group */ + /// update an existing group + RS_DEPRECATED_FOR("editCircle, inviteIdsToCircle") virtual void updateGroup(uint32_t &token, RsGxsCircleGroup &group) = 0; }; - - - -#endif diff --git a/libretroshare/src/retroshare/rsgxsifacetypes.h b/libretroshare/src/retroshare/rsgxsifacetypes.h index c80ce3afa..d5a9d8d7d 100644 --- a/libretroshare/src/retroshare/rsgxsifacetypes.h +++ b/libretroshare/src/retroshare/rsgxsifacetypes.h @@ -90,7 +90,9 @@ struct RsGroupMetaData : RsSerializable rstime_t mLastPost; // Timestamp for last message. Not used yet. uint32_t mGroupStatus; - std::string mServiceString; // Service Specific Free-Form extra storage. + + /// Service Specific Free-Form local (non-synced) extra storage. + std::string mServiceString; RsPeerId mOriginator; RsGxsCircleId mInternalCircle; diff --git a/libretroshare/src/services/p3gxscircles.cc b/libretroshare/src/services/p3gxscircles.cc index ebf979fe7..ed5dc74ff 100644 --- a/libretroshare/src/services/p3gxscircles.cc +++ b/libretroshare/src/services/p3gxscircles.cc @@ -153,7 +153,118 @@ RsServiceInfo p3GxsCircles::getServiceInfo() GXS_CIRCLES_MIN_MINOR_VERSION); } +bool p3GxsCircles::createCircle(RsGxsCircleGroup& cData) +{ + uint32_t token; + createGroup(token, cData); + if(waitToken(token) != RsTokenService::COMPLETE) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! GXS operation failed." + << std::endl; + return false; + } + + if(!RsGenExchange::getPublishedGroupMeta(token, cData.mMeta)) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! Failure getting created" + << " group data." << std::endl; + return false; + } + + return true; +} + +bool p3GxsCircles::editCircle(RsGxsCircleGroup& cData) +{ + uint32_t token; + updateGroup(token, cData); + + if(waitToken(token) != RsTokenService::COMPLETE) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! GXS operation failed." + << std::endl; + return false; + } + + if(!RsGenExchange::getPublishedGroupMeta(token, cData.mMeta)) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! Failure getting updated" + << " group data." << std::endl; + return false; + } + + return true; +} + +bool p3GxsCircles::getCirclesSummaries(std::list& circles) +{ + uint32_t token; + RsTokReqOptions opts; + opts.mReqType = GXS_REQUEST_TYPE_GROUP_META; + if( !requestGroupInfo(token, opts) + || waitToken(token) != RsTokenService::COMPLETE ) return false; + return getGroupSummary(token, circles); +} + +bool p3GxsCircles::getCirclesInfo( const std::list& circlesIds, + std::vector& circlesInfo ) +{ + uint32_t token; + RsTokReqOptions opts; + opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; + if( !requestGroupInfo(token, opts, circlesIds) + || waitToken(token) != RsTokenService::COMPLETE ) return false; + return getGroupData(token, circlesInfo); +} + +bool p3GxsCircles::getCircleRequests( const RsGxsGroupId& circleId, + std::vector& requests ) +{ + uint32_t token; + std::list grpIds { circleId }; + RsTokReqOptions opts; + opts.mReqType = GXS_REQUEST_TYPE_MSG_DATA; + + if( !requestMsgInfo(token, opts, grpIds) || + waitToken(token) != RsTokenService::COMPLETE ) return false; + + return getMsgData(token, requests); +} + +bool p3GxsCircles::inviteIdsToCircle( const std::set& identities, + const RsGxsCircleId& circleId ) +{ + const std::list circlesIds{ RsGxsGroupId(circleId) }; + std::vector circlesInfo; + + if(!getCirclesInfo(circlesIds, circlesInfo)) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! Failure getting group data." + << std::endl; + return false; + } + + if(circlesInfo.empty()) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! Circle: " + << circleId.toStdString() << " not found!" << std::endl; + return false; + } + + RsGxsCircleGroup& circleGrp = circlesInfo[0]; + + if(!(circleGrp.mMeta.mSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_ADMIN)) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! Attempt to edit non-own " + << "circle: " << circleId.toStdString() << std::endl; + return false; + } + + circleGrp.mInvitedMembers.insert(identities.begin(), identities.end()); + + return editCircle(circleGrp); +} uint32_t p3GxsCircles::circleAuthenPolicy() { @@ -320,32 +431,6 @@ bool p3GxsCircles:: getCircleDetails(const RsGxsCircleId &id, RsGxsCircleDetails return false; } - -bool p3GxsCircles:: getCirclePersonalIdList(std::list &circleIds) -{ -#ifdef DEBUG_CIRCLES - std::cerr << "p3GxsCircles::getCircleIdList()"; - std::cerr << std::endl; -#endif // DEBUG_CIRCLES - - RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/ - if (circleIds.empty()) - { - circleIds = mCirclePersonalIdList; - } - else - { - std::list::const_iterator it; - for(it = mCirclePersonalIdList.begin(); it != mCirclePersonalIdList.begin(); ++it) - { - circleIds.push_back(*it); - } - } - - return true; -} - - bool p3GxsCircles:: getCircleExternalIdList(std::list &circleIds) { #ifdef DEBUG_CIRCLES diff --git a/libretroshare/src/services/p3gxscircles.h b/libretroshare/src/services/p3gxscircles.h index 8b8cef4a8..a23ecbd88 100644 --- a/libretroshare/src/services/p3gxscircles.h +++ b/libretroshare/src/services/p3gxscircles.h @@ -179,9 +179,30 @@ virtual RsServiceInfo getServiceInfo(); /*********** External Interface ***************/ + /// @see RsGxsCircles + bool createCircle(RsGxsCircleGroup& cData) override; + + /// @see RsGxsCircles + bool editCircle(RsGxsCircleGroup& cData) override; + + /// @see RsGxsCircles + bool getCirclesSummaries(std::list& circles) override; + + /// @see RsGxsCircles + bool getCirclesInfo( + const std::list& circlesIds, + std::vector& circlesInfo ) override; + + /// @see RsGxsCircles + bool getCircleRequests( const RsGxsGroupId& circleId, + std::vector& requests ) override; + + /// @see RsGxsCircles + bool inviteIdsToCircle( const std::set& identities, + const RsGxsCircleId& circleId ) override; + virtual bool getCircleDetails(const RsGxsCircleId &id, RsGxsCircleDetails &details); virtual bool getCircleExternalIdList(std::list &circleIds); - virtual bool getCirclePersonalIdList(std::list &circleIds); virtual bool isLoaded(const RsGxsCircleId &circleId); virtual bool loadCircle(const RsGxsCircleId &circleId); @@ -257,6 +278,8 @@ virtual RsServiceInfo getServiceInfo(); // put a circle id into the external or personal circle id list // this function locks the mutex // if the id is already in the list, it will not be added again + // G10h4ck: this is terrible, an std::set instead of a list should be used + // to guarantee uniqueness void addCircleIdToList(const RsGxsCircleId& circleId, uint32_t circleType); RsMutex mCircleMtx; /* Locked Below Here */ diff --git a/retroshare.pri b/retroshare.pri index be9951915..df632f031 100644 --- a/retroshare.pri +++ b/retroshare.pri @@ -241,6 +241,7 @@ rs_v07_changes { DEFINES += V07_NON_BACKWARD_COMPATIBLE_CHANGE_001 DEFINES += V07_NON_BACKWARD_COMPATIBLE_CHANGE_002 DEFINES += V07_NON_BACKWARD_COMPATIBLE_CHANGE_003 + DEFINES += V07_NON_BACKWARD_COMPATIBLE_CHANGE_UNNAMED } ################################################################################ From ea7773f86d8a38c6a38992ab6c2705259df0ffe3 Mon Sep 17 00:00:00 2001 From: Gioacchino Mazzurco Date: Fri, 15 Feb 2019 15:29:36 -0300 Subject: [PATCH 08/81] Refactor RsReputations for compatibility with JSON API --- libresapi/src/api/IdentityHandler.cpp | 16 +- libretroshare/src/chat/distributedchat.cc | 8 +- libretroshare/src/grouter/p3grouter.cc | 3 +- libretroshare/src/gxs/rsgenexchange.cc | 6 +- libretroshare/src/gxs/rsgenexchange.h | 3 +- libretroshare/src/gxs/rsgixs.h | 22 ++- libretroshare/src/gxs/rsgxsnetservice.cc | 7 +- libretroshare/src/gxs/rsgxsnetutils.cc | 3 +- libretroshare/src/gxs/rsgxsutil.cc | 10 +- libretroshare/src/gxs/rsnxs.h | 19 ++- libretroshare/src/gxstrans/p3gxstrans.cc | 45 ++--- libretroshare/src/libretroshare.pro | 1 + libretroshare/src/retroshare/rsgxsiface.h | 3 +- .../src/retroshare/rsgxsifacehelper.h | 3 +- libretroshare/src/retroshare/rsidentity.h | 2 +- libretroshare/src/retroshare/rsreputations.h | 140 ++++++++++------ .../src/rsitems/rsgxsreputationitems.h | 2 +- libretroshare/src/services/p3gxsreputation.cc | 156 ++++++++++-------- libretroshare/src/services/p3gxsreputation.h | 28 ++-- libretroshare/src/services/p3idservice.cc | 11 +- 20 files changed, 280 insertions(+), 208 deletions(-) diff --git a/libresapi/src/api/IdentityHandler.cpp b/libresapi/src/api/IdentityHandler.cpp index 71c2c79b4..e82b857a0 100644 --- a/libresapi/src/api/IdentityHandler.cpp +++ b/libresapi/src/api/IdentityHandler.cpp @@ -504,7 +504,7 @@ void IdentityHandler::handleGetIdentityDetails(Request& req, Response& resp) resp.mDataStream << makeKeyValue("bannned_node", rsReputations->isNodeBanned(data.mPgpId)); - RsReputations::ReputationInfo info; + RsReputationInfo info; rsReputations->getReputationInfo(RsGxsId(data.mMeta.mGroupId), data.mPgpId, info); resp.mDataStream << makeKeyValue("friends_positive_votes", info.mFriendsPositiveVotes); resp.mDataStream << makeKeyValue("friends_negative_votes", info.mFriendsNegativeVotes); @@ -637,18 +637,12 @@ void IdentityHandler::handleSetOpinion(Request& req, Response& resp) int own_opinion; req.mStream << makeKeyValueReference("own_opinion", own_opinion); - RsReputations::Opinion opinion; + RsOpinion opinion; switch(own_opinion) { - case 0: - opinion = RsReputations::OPINION_NEGATIVE; - break; - case 1: opinion = - RsReputations::OPINION_NEUTRAL; - break; - case 2: - opinion = RsReputations::OPINION_POSITIVE; - break; + case 0: opinion = RsOpinion::NEGATIVE; break; + case 1: opinion = RsOpinion::NEUTRAL; break; + case 2: opinion = RsOpinion::POSITIVE; break; default: resp.setFail(); return; diff --git a/libretroshare/src/chat/distributedchat.cc b/libretroshare/src/chat/distributedchat.cc index 2726e8ec0..aeb88b7f1 100644 --- a/libretroshare/src/chat/distributedchat.cc +++ b/libretroshare/src/chat/distributedchat.cc @@ -136,7 +136,8 @@ bool DistributedChatService::handleRecvChatLobbyMsgItem(RsChatMsgItem *ci) return false ; } - if(rsReputations->overallReputationLevel(cli->signature.keyId) == RsReputations::REPUTATION_LOCALLY_NEGATIVE) + if( rsReputations->overallReputationLevel(cli->signature.keyId) == + RsReputationLevel::LOCALLY_NEGATIVE ) { std::cerr << "(WW) Received lobby msg/item from banned identity " << cli->signature.keyId << ". Dropping it." << std::endl; return false ; @@ -677,9 +678,10 @@ void DistributedChatService::handleRecvChatLobbyEventItem(RsChatLobbyEventItem * #ifdef DEBUG_CHAT_LOBBIES std::cerr << "Received ChatLobbyEvent item of type " << (int)(item->event_type) << ", and string=" << item->string1 << std::endl; #endif - rstime_t now = time(NULL) ; + rstime_t now = time(nullptr); - if(rsReputations->overallReputationLevel(item->signature.keyId) == RsReputations::REPUTATION_LOCALLY_NEGATIVE) + if( rsReputations->overallReputationLevel(item->signature.keyId) == + RsReputationLevel::LOCALLY_NEGATIVE ) { std::cerr << "(WW) Received lobby msg/item from banned identity " << item->signature.keyId << ". Dropping it." << std::endl; return ; diff --git a/libretroshare/src/grouter/p3grouter.cc b/libretroshare/src/grouter/p3grouter.cc index 2cba77e8a..6dbc444aa 100644 --- a/libretroshare/src/grouter/p3grouter.cc +++ b/libretroshare/src/grouter/p3grouter.cc @@ -2014,7 +2014,8 @@ bool p3GRouter::verifySignedDataItem(RsGRouterAbstractMsgItem *item,const RsIden { try { - if(rsReputations->overallReputationLevel(item->signature.keyId) == RsReputations::REPUTATION_LOCALLY_NEGATIVE) + if( rsReputations->overallReputationLevel(item->signature.keyId) == + RsReputationLevel::LOCALLY_NEGATIVE ) { std::cerr << "(WW) received global router message from banned identity " << item->signature.keyId << ". Rejecting the message." << std::endl; return false ; diff --git a/libretroshare/src/gxs/rsgenexchange.cc b/libretroshare/src/gxs/rsgenexchange.cc index 27c8c260a..c5da0df55 100644 --- a/libretroshare/src/gxs/rsgenexchange.cc +++ b/libretroshare/src/gxs/rsgenexchange.cc @@ -912,7 +912,8 @@ int RsGenExchange::validateMsg(RsNxsMsg *msg, const uint32_t& grpFlag, const uin // now check reputation of the message author. The reputation will need to be at least as high as this value for the msg to validate. // At validation step, we accept all messages, except the ones signed by locally rejected identities. - if(details.mReputation.mOverallReputationLevel == RsReputations::REPUTATION_LOCALLY_NEGATIVE) + if( details.mReputation.mOverallReputationLevel == + RsReputationLevel::LOCALLY_NEGATIVE ) { #ifdef GEN_EXCH_DEBUG std::cerr << "RsGenExchange::validateMsg(): message from " << metaData.mAuthorId << ", rejected because reputation level (" << details.mReputation.mOverallReputationLevel <<") indicate that you banned this ID." << std::endl; @@ -1848,7 +1849,8 @@ uint32_t RsGenExchange::getDefaultSyncPeriod() } } -RsReputations::ReputationLevel RsGenExchange::minReputationForForwardingMessages(uint32_t group_sign_flags,uint32_t identity_sign_flags) +RsReputationLevel RsGenExchange::minReputationForForwardingMessages( + uint32_t group_sign_flags, uint32_t identity_sign_flags ) { return RsNetworkExchangeService::minReputationForForwardingMessages(group_sign_flags,identity_sign_flags); } diff --git a/libretroshare/src/gxs/rsgenexchange.h b/libretroshare/src/gxs/rsgenexchange.h index ea3a43d7c..fd7e5a60a 100644 --- a/libretroshare/src/gxs/rsgenexchange.h +++ b/libretroshare/src/gxs/rsgenexchange.h @@ -712,7 +712,8 @@ public: uint16_t serviceType() const { return mServType ; } uint32_t serviceFullType() const { return ((uint32_t)mServType << 8) + (((uint32_t) RS_PKT_VERSION_SERVICE) << 24); } - virtual RsReputations::ReputationLevel minReputationForForwardingMessages(uint32_t group_sign_flags,uint32_t identity_flags); + virtual RsReputationLevel minReputationForForwardingMessages( + uint32_t group_sign_flags, uint32_t identity_flags ); protected: /** Notifications **/ diff --git a/libretroshare/src/gxs/rsgixs.h b/libretroshare/src/gxs/rsgixs.h index 43cdf059f..0175bbda9 100644 --- a/libretroshare/src/gxs/rsgixs.h +++ b/libretroshare/src/gxs/rsgixs.h @@ -178,25 +178,23 @@ public: uint32_t reputation_level ; }; -class RsGixsReputation +struct RsGixsReputation { -public: - // get Reputation. - virtual RsReputations::ReputationLevel overallReputationLevel(const RsGxsId& id,uint32_t *identity_flags=NULL) = 0; + virtual RsReputationLevel overallReputationLevel( + const RsGxsId& id, uint32_t* identity_flags = nullptr ) = 0; virtual ~RsGixsReputation(){} }; /*** This Class pulls all the GXS Interfaces together ****/ -class RsGxsIdExchange: - public RsGenExchange, - public RsGixs +struct RsGxsIdExchange : RsGenExchange, RsGixs { -public: - RsGxsIdExchange(RsGeneralDataService* gds, RsNetworkExchangeService* ns, RsSerialType* serviceSerialiser, uint16_t mServType, uint32_t authenPolicy) - :RsGenExchange(gds,ns,serviceSerialiser,mServType, this, authenPolicy) { return; } -virtual ~RsGxsIdExchange() { return; } - + RsGxsIdExchange( + RsGeneralDataService* gds, RsNetworkExchangeService* ns, + RsSerialType* serviceSerialiser, uint16_t mServType, + uint32_t authenPolicy ) + : RsGenExchange( + gds, ns, serviceSerialiser, mServType, this, authenPolicy ) {} }; diff --git a/libretroshare/src/gxs/rsgxsnetservice.cc b/libretroshare/src/gxs/rsgxsnetservice.cc index a7b558e2b..989ddf305 100644 --- a/libretroshare/src/gxs/rsgxsnetservice.cc +++ b/libretroshare/src/gxs/rsgxsnetservice.cc @@ -3034,7 +3034,8 @@ void RsGxsNetService::locked_genReqMsgTransaction(NxsTransaction* tr) // - if author is locally banned, do not download. // - if author is not locally banned, download, whatever friends' opinion might be. - if(mReputations->overallReputationLevel(syncItem->authorId) == RsReputations::REPUTATION_LOCALLY_NEGATIVE) + if( mReputations->overallReputationLevel(syncItem->authorId) == + RsReputationLevel::LOCALLY_NEGATIVE ) { #ifdef NXS_NET_DEBUG_1 GXSNETDEBUG_PG(item->PeerId(),grpId) << ", Identity " << syncItem->authorId << " is banned. Not requesting message!" << std::endl; @@ -3239,7 +3240,9 @@ void RsGxsNetService::locked_genReqGrpTransaction(NxsTransaction* tr) // FIXTESTS global variable rsReputations not available in unittests! #warning csoler 2016-12-23: Update the code below to correctly send/recv dependign on reputation - if(!grpSyncItem->authorId.isNull() && mReputations->overallReputationLevel(grpSyncItem->authorId) == RsReputations::REPUTATION_LOCALLY_NEGATIVE) + if( !grpSyncItem->authorId.isNull() && + mReputations->overallReputationLevel(grpSyncItem->authorId) == + RsReputationLevel::LOCALLY_NEGATIVE ) { #ifdef NXS_NET_DEBUG_0 GXSNETDEBUG_PG(tr->mTransaction->PeerId(),grpId) << " Identity " << grpSyncItem->authorId << " is banned. Not syncing group." << std::endl; diff --git a/libretroshare/src/gxs/rsgxsnetutils.cc b/libretroshare/src/gxs/rsgxsnetutils.cc index 1b0166f65..6f80cc261 100644 --- a/libretroshare/src/gxs/rsgxsnetutils.cc +++ b/libretroshare/src/gxs/rsgxsnetutils.cc @@ -40,7 +40,8 @@ bool AuthorPending::expired() const bool AuthorPending::getAuthorRep(GixsReputation& rep, const RsGxsId& authorId, const RsPeerId& /*peerId*/) { rep.id = authorId ; - rep.reputation_level = mRep->overallReputationLevel(authorId); + rep.reputation_level = + static_cast(mRep->overallReputationLevel(authorId)); #warning csoler 2017-01-10: Can it happen that reputations do not have the info yet? return true ; diff --git a/libretroshare/src/gxs/rsgxsutil.cc b/libretroshare/src/gxs/rsgxsutil.cc index f678c7966..de7644ab4 100644 --- a/libretroshare/src/gxs/rsgxsutil.cc +++ b/libretroshare/src/gxs/rsgxsutil.cc @@ -204,7 +204,10 @@ bool RsGxsIntegrityCheck::check() #ifdef DEBUG_GXSUTIL GXSUTIL_DEBUG() << "TimeStamping group authors' key ID " << grp->metaData->mAuthorId << " in group ID " << grp->grpId << std::endl; #endif - if( rsReputations && rsReputations->overallReputationLevel(grp->metaData->mAuthorId ) > RsReputations::REPUTATION_LOCALLY_NEGATIVE ) + if( rsReputations && + rsReputations->overallReputationLevel( + grp->metaData->mAuthorId ) > + RsReputationLevel::LOCALLY_NEGATIVE ) used_gxs_ids.insert(std::make_pair(grp->metaData->mAuthorId, RsIdentityUsage(mGenExchangeClient->serviceType(), RsIdentityUsage::GROUP_AUTHOR_KEEP_ALIVE,grp->grpId))); } } @@ -388,7 +391,10 @@ bool RsGxsIntegrityCheck::check() #ifdef DEBUG_GXSUTIL GXSUTIL_DEBUG() << "TimeStamping message authors' key ID " << msg->metaData->mAuthorId << " in message " << msg->msgId << ", group ID " << msg->grpId<< std::endl; #endif - if(rsReputations!=NULL && rsReputations->overallReputationLevel(msg->metaData->mAuthorId) > RsReputations::REPUTATION_LOCALLY_NEGATIVE) + if( rsReputations && + rsReputations->overallReputationLevel( + msg->metaData->mAuthorId ) > + RsReputationLevel::LOCALLY_NEGATIVE ) used_gxs_ids.insert(std::make_pair(msg->metaData->mAuthorId,RsIdentityUsage(mGenExchangeClient->serviceType(),RsIdentityUsage::MESSAGE_AUTHOR_KEEP_ALIVE,msg->metaData->mGroupId,msg->metaData->mMsgId))) ; } } diff --git a/libretroshare/src/gxs/rsnxs.h b/libretroshare/src/gxs/rsnxs.h index 298e63ac8..2752fa6bf 100644 --- a/libretroshare/src/gxs/rsnxs.h +++ b/libretroshare/src/gxs/rsnxs.h @@ -253,13 +253,14 @@ public: * \param identity_flags Flags of the identity * \return */ - static RsReputations::ReputationLevel minReputationForRequestingMessages(uint32_t /* group_sign_flags */, uint32_t /* identity_flags */) + static RsReputationLevel minReputationForRequestingMessages( + uint32_t /* group_sign_flags */, uint32_t /* identity_flags */ ) { // We always request messages, except if the author identity is locally banned. - - return RsReputations::REPUTATION_REMOTELY_NEGATIVE; + return RsReputationLevel::REMOTELY_NEGATIVE; } - static RsReputations::ReputationLevel minReputationForForwardingMessages(uint32_t group_sign_flags, uint32_t identity_flags) + static RsReputationLevel minReputationForForwardingMessages( + uint32_t group_sign_flags, uint32_t identity_flags ) { // If anti-spam is enabled, do not send messages from authors with bad reputation. The policy is to only forward messages if the reputation of the author is at least // equal to the minimal reputation in the table below (R=remotely, L=locally, P=positive, N=negative, O=neutral) : @@ -277,20 +278,20 @@ public: // if(identity_flags & RS_IDENTITY_FLAGS_PGP_KNOWN) - return RsReputations::REPUTATION_NEUTRAL; + return RsReputationLevel::NEUTRAL; else if(identity_flags & RS_IDENTITY_FLAGS_PGP_LINKED) { if(group_sign_flags & GXS_SERV::FLAG_AUTHOR_AUTHENTICATION_GPG_KNOWN) - return RsReputations::REPUTATION_REMOTELY_POSITIVE; + return RsReputationLevel::REMOTELY_POSITIVE; else - return RsReputations::REPUTATION_NEUTRAL; + return RsReputationLevel::NEUTRAL; } else { if( (group_sign_flags & GXS_SERV::FLAG_AUTHOR_AUTHENTICATION_GPG_KNOWN) || (group_sign_flags & GXS_SERV::FLAG_AUTHOR_AUTHENTICATION_GPG)) - return RsReputations::REPUTATION_REMOTELY_POSITIVE; + return RsReputationLevel::REMOTELY_POSITIVE; else - return RsReputations::REPUTATION_NEUTRAL; + return RsReputationLevel::NEUTRAL; } } }; diff --git a/libretroshare/src/gxstrans/p3gxstrans.cc b/libretroshare/src/gxstrans/p3gxstrans.cc index c9f471ddb..899dcd177 100644 --- a/libretroshare/src/gxstrans/p3gxstrans.cc +++ b/libretroshare/src/gxstrans/p3gxstrans.cc @@ -1256,31 +1256,38 @@ bool p3GxsTrans::acceptNewMessage(const RsGxsMsgMetaData *msgMeta,uint32_t msg_s uint32_t max_size = 0 ; uint32_t identity_flags = 0 ; - RsReputations::ReputationLevel rep_lev = rsReputations->overallReputationLevel(msgMeta->mAuthorId,&identity_flags); + RsReputationLevel rep_lev = + rsReputations->overallReputationLevel( + msgMeta->mAuthorId, &identity_flags ); switch(rep_lev) { - case RsReputations::REPUTATION_REMOTELY_NEGATIVE: max_count = GXSTRANS_MAX_COUNT_REMOTELY_NEGATIVE_DEFAULT; - max_size = GXSTRANS_MAX_SIZE_REMOTELY_NEGATIVE_DEFAULT; - break ; - case RsReputations::REPUTATION_NEUTRAL: max_count = GXSTRANS_MAX_COUNT_NEUTRAL_DEFAULT; - max_size = GXSTRANS_MAX_SIZE_NEUTRAL_DEFAULT; - break ; - case RsReputations::REPUTATION_REMOTELY_POSITIVE: max_count = GXSTRANS_MAX_COUNT_REMOTELY_POSITIVE_DEFAULT; - max_size = GXSTRANS_MAX_SIZE_REMOTELY_POSITIVE_DEFAULT; - break ; - case RsReputations::REPUTATION_LOCALLY_POSITIVE: max_count = GXSTRANS_MAX_COUNT_LOCALLY_POSITIVE_DEFAULT; - max_size = GXSTRANS_MAX_SIZE_LOCALLY_POSITIVE_DEFAULT; - break ; - default: - case RsReputations::REPUTATION_LOCALLY_NEGATIVE: max_count = 0 ; - max_size = 0 ; + case RsReputationLevel::REMOTELY_NEGATIVE: + max_count = GXSTRANS_MAX_COUNT_REMOTELY_NEGATIVE_DEFAULT; + max_size = GXSTRANS_MAX_SIZE_REMOTELY_NEGATIVE_DEFAULT; break ; + case RsReputationLevel::NEUTRAL: + max_count = GXSTRANS_MAX_COUNT_NEUTRAL_DEFAULT; + max_size = GXSTRANS_MAX_SIZE_NEUTRAL_DEFAULT; + break; + case RsReputationLevel::REMOTELY_POSITIVE: + max_count = GXSTRANS_MAX_COUNT_REMOTELY_POSITIVE_DEFAULT; + max_size = GXSTRANS_MAX_SIZE_REMOTELY_POSITIVE_DEFAULT; + break; + case RsReputationLevel::LOCALLY_POSITIVE: + max_count = GXSTRANS_MAX_COUNT_LOCALLY_POSITIVE_DEFAULT; + max_size = GXSTRANS_MAX_SIZE_LOCALLY_POSITIVE_DEFAULT; + break; + case RsReputationLevel::LOCALLY_NEGATIVE: // fallthrough + default: + max_count = 0; + max_size = 0; + break; } - bool pgp_linked = identity_flags & RS_IDENTITY_FLAGS_PGP_LINKED ; + bool pgp_linked = identity_flags & RS_IDENTITY_FLAGS_PGP_LINKED; - if(rep_lev <= RsReputations::REPUTATION_NEUTRAL && !pgp_linked) + if(rep_lev <= RsReputationLevel::NEUTRAL && !pgp_linked) { max_count /= 10 ; max_size /= 10 ; @@ -1288,7 +1295,7 @@ bool p3GxsTrans::acceptNewMessage(const RsGxsMsgMetaData *msgMeta,uint32_t msg_s RS_STACK_MUTEX(mPerUserStatsMutex); - MsgSizeCount& s(per_user_statistics[msgMeta->mAuthorId]) ; + MsgSizeCount& s(per_user_statistics[msgMeta->mAuthorId]); #ifdef DEBUG_GXSTRANS std::cerr << "GxsTrans::acceptMessage(): size=" << msg_size << ", grp=" << msgMeta->mGroupId << ", gxs_id=" << msgMeta->mAuthorId << ", pgp_linked=" << pgp_linked << ", current (size,cnt)=(" diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 22d2d1235..163118115 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -754,6 +754,7 @@ SOURCES += serialiser/rsserializable.cc \ # Identity Service HEADERS += retroshare/rsidentity.h \ + retroshare/rsreputations.h \ gxs/rsgixs.h \ services/p3idservice.h \ rsitems/rsgxsiditems.h \ diff --git a/libretroshare/src/retroshare/rsgxsiface.h b/libretroshare/src/retroshare/rsgxsiface.h index 8b057501a..268c8cc75 100644 --- a/libretroshare/src/retroshare/rsgxsiface.h +++ b/libretroshare/src/retroshare/rsgxsiface.h @@ -217,7 +217,8 @@ struct RsGxsIface virtual uint32_t getSyncPeriod(const RsGxsGroupId& grpId) = 0; virtual void setSyncPeriod(const RsGxsGroupId& grpId,uint32_t age_in_secs) = 0; - virtual RsReputations::ReputationLevel minReputationForForwardingMessages(uint32_t group_sign_flags,uint32_t identity_flags)=0; + virtual RsReputationLevel minReputationForForwardingMessages( + uint32_t group_sign_flags,uint32_t identity_flags ) = 0; }; diff --git a/libretroshare/src/retroshare/rsgxsifacehelper.h b/libretroshare/src/retroshare/rsgxsifacehelper.h index f5fc69f13..09cf40dbf 100644 --- a/libretroshare/src/retroshare/rsgxsifacehelper.h +++ b/libretroshare/src/retroshare/rsgxsifacehelper.h @@ -228,7 +228,8 @@ struct RsGxsIfaceHelper mGxs.setSyncPeriod(grpId,age_in_secs); } - RsReputations::ReputationLevel minReputationForForwardingMessages(uint32_t group_sign_flags,uint32_t identity_flags) + RsReputationLevel minReputationForForwardingMessages( + uint32_t group_sign_flags, uint32_t identity_flags ) { return mGxs.minReputationForForwardingMessages(group_sign_flags,identity_flags); } diff --git a/libretroshare/src/retroshare/rsidentity.h b/libretroshare/src/retroshare/rsidentity.h index 72917e159..8be685d24 100644 --- a/libretroshare/src/retroshare/rsidentity.h +++ b/libretroshare/src/retroshare/rsidentity.h @@ -315,7 +315,7 @@ struct RsIdentityDetails : RsSerializable * reputation system is not finished yet, I leave this in place. We should * decide what to do with it. */ - RsReputations::ReputationInfo mReputation; + RsReputationInfo mReputation; RsGxsImage mAvatar; diff --git a/libretroshare/src/retroshare/rsreputations.h b/libretroshare/src/retroshare/rsreputations.h index 6f8c7ecaf..68f49c058 100644 --- a/libretroshare/src/retroshare/rsreputations.h +++ b/libretroshare/src/retroshare/rsreputations.h @@ -19,74 +19,104 @@ * along with this program. If not, see . * * * *******************************************************************************/ - #pragma once #include "retroshare/rsids.h" #include "retroshare/rsgxsifacetypes.h" +class RsReputations; + +/** + * Pointer to global instance of RsReputations service implementation + * @jsonapi{development} + */ +extern RsReputations* rsReputations; + + +const float REPUTATION_THRESHOLD_DEFAULT = 1.0f; +const float REPUTATION_THRESHOLD_ANTI_SPAM = 1.4f; + +enum struct RsOpinion : uint8_t +{ + NEGATIVE = 0, + NEUTRAL = 1, + POSITIVE = 2 +}; + +enum struct RsReputationLevel : uint8_t +{ + /// local opinion is negative + LOCALLY_NEGATIVE = 0x00, + + /// local opinion is neutral and friends are positive in average + REMOTELY_NEGATIVE = 0x01, + + /// no reputation information + NEUTRAL = 0x02, + + /// local opinion is neutral and friends are positive in average + REMOTELY_POSITIVE = 0x03, + + /// local opinion is positive + LOCALLY_POSITIVE = 0x04, + + /// missing info + UNKNOWN = 0x05 +}; + +struct RsReputationInfo +{ + RsReputationInfo() : + mOwnOpinion(RsOpinion::NEUTRAL), mFriendsPositiveVotes(0), + mFriendsNegativeVotes(0), + mFriendAverageScore(REPUTATION_THRESHOLD_DEFAULT), + mOverallReputationLevel(RsReputationLevel::NEUTRAL) {} + + RsOpinion mOwnOpinion; + + uint32_t mFriendsPositiveVotes; + uint32_t mFriendsNegativeVotes; + + float mFriendAverageScore; + + /// this should help clients in taking decisions + RsReputationLevel mOverallReputationLevel; +}; + + class RsReputations { public: - static const float REPUTATION_THRESHOLD_ANTI_SPAM; - static const float REPUTATION_THRESHOLD_DEFAULT; - - // This is the interface file for the reputation system - // - enum Opinion { OPINION_NEGATIVE = 0, OPINION_NEUTRAL = 1, OPINION_POSITIVE = 2 } ; + virtual ~RsReputations() {} - enum ReputationLevel { REPUTATION_LOCALLY_NEGATIVE = 0x00, // local opinion is positive - REPUTATION_REMOTELY_NEGATIVE = 0x01, // local opinion is neutral and friends are positive in average - REPUTATION_NEUTRAL = 0x02, // no reputation information ; - REPUTATION_REMOTELY_POSITIVE = 0x03, // local opinion is neutral and friends are negative in average - REPUTATION_LOCALLY_POSITIVE = 0x04, // local opinion is negative - REPUTATION_UNKNOWN = 0x05 // missing info - }; + virtual bool setOwnOpinion(const RsGxsId& key_id, RsOpinion op) = 0; + virtual bool getOwnOpinion(const RsGxsId& key_id, RsOpinion& op) = 0; + virtual bool getReputationInfo( + const RsGxsId& id, const RsPgpId& ownerNode, RsReputationInfo& info, + bool stamp = true ) = 0; - struct ReputationInfo - { - ReputationInfo() : mOwnOpinion(OPINION_NEUTRAL),mFriendsPositiveVotes(0),mFriendsNegativeVotes(0), mFriendAverageScore(REPUTATION_THRESHOLD_DEFAULT),mOverallReputationLevel(REPUTATION_NEUTRAL){} - - RsReputations::Opinion mOwnOpinion ; + /** This returns the reputation level and also the flags of the identity + * service for that id. This is useful in order to get these flags without + * relying on the async method of p3Identity */ + RS_DEPRECATED + virtual RsReputationLevel overallReputationLevel( + const RsGxsId& id, uint32_t* identity_flags = nullptr) = 0; - uint32_t mFriendsPositiveVotes ; - uint32_t mFriendsNegativeVotes ; + virtual void setNodeAutoPositiveOpinionForContacts(bool b) = 0; + virtual bool nodeAutoPositiveOpinionForContacts() = 0; - float mFriendAverageScore ; + virtual uint32_t thresholdForRemotelyNegativeReputation() = 0; + virtual uint32_t thresholdForRemotelyPositiveReputation() = 0; + virtual void setThresholdForRemotelyNegativeReputation(uint32_t thresh) = 0; + virtual void setThresholdForRemotelyPositiveReputation(uint32_t thresh) = 0; - RsReputations::ReputationLevel mOverallReputationLevel; // this should help clients in taking decisions - }; + virtual void setRememberDeletedNodesThreshold(uint32_t days) = 0; + virtual uint32_t rememberDeletedNodesThreshold() = 0; - virtual bool setOwnOpinion(const RsGxsId& key_id, const Opinion& op) =0; - virtual bool getOwnOpinion(const RsGxsId& key_id, Opinion& op) =0; - virtual bool getReputationInfo(const RsGxsId& id, const RsPgpId &ownerNode, ReputationInfo& info,bool stamp=true) =0; + /** This one is a proxy designed to allow fast checking of a GXS id. + * It basically returns true if assessment is not ASSESSMENT_OK */ + virtual bool isIdentityBanned(const RsGxsId& id) = 0; - // This returns the reputation level and also the flags of the identity service for that id. This is useful in order to get these flags without relying on the async method of p3Identity - - virtual ReputationLevel overallReputationLevel(const RsGxsId& id,uint32_t *identity_flags=NULL)=0; - - // parameters - - virtual void setNodeAutoPositiveOpinionForContacts(bool b) =0; - virtual bool nodeAutoPositiveOpinionForContacts() =0; - - virtual uint32_t thresholdForRemotelyNegativeReputation()=0; - virtual uint32_t thresholdForRemotelyPositiveReputation()=0; - virtual void setThresholdForRemotelyNegativeReputation(uint32_t thresh)=0; - virtual void setThresholdForRemotelyPositiveReputation(uint32_t thresh)=0; - - virtual void setRememberDeletedNodesThreshold(uint32_t days) =0; - virtual uint32_t rememberDeletedNodesThreshold() =0; - - // This one is a proxy designed to allow fast checking of a GXS id. - // it basically returns true if assessment is not ASSESSMENT_OK - - virtual bool isIdentityBanned(const RsGxsId& id) =0; - - virtual bool isNodeBanned(const RsPgpId& id) =0; - virtual void banNode(const RsPgpId& id,bool b) =0; + virtual bool isNodeBanned(const RsPgpId& id) = 0; + virtual void banNode(const RsPgpId& id, bool b) = 0; }; - -// To access reputations from anywhere -// -extern RsReputations *rsReputations ; diff --git a/libretroshare/src/rsitems/rsgxsreputationitems.h b/libretroshare/src/rsitems/rsgxsreputationitems.h index 6bcd77451..8028e63f1 100644 --- a/libretroshare/src/rsitems/rsgxsreputationitems.h +++ b/libretroshare/src/rsitems/rsgxsreputationitems.h @@ -100,7 +100,7 @@ class RsGxsReputationSetItem: public RsReputationItem public: RsGxsReputationSetItem() :RsReputationItem(RS_PKT_SUBTYPE_GXS_REPUTATION_SET_ITEM) { - mOwnOpinion = RsReputations::OPINION_NEUTRAL ; + mOwnOpinion = static_cast(RsOpinion::NEUTRAL); mOwnOpinionTS = 0; mIdentityFlags = 0; mLastUsedTS = 0; diff --git a/libretroshare/src/services/p3gxsreputation.cc b/libretroshare/src/services/p3gxsreputation.cc index 412360d0e..e99c07b2e 100644 --- a/libretroshare/src/services/p3gxsreputation.cc +++ b/libretroshare/src/services/p3gxsreputation.cc @@ -382,7 +382,10 @@ void p3GxsReputation::cleanup() { bool should_delete = false ; - if(it->second.mOwnOpinion == RsReputations::OPINION_NEGATIVE && mMaxPreventReloadBannedIds != 0 && it->second.mOwnOpinionTs + mMaxPreventReloadBannedIds < now) + if( it->second.mOwnOpinion == + static_cast(RsOpinion::NEGATIVE) && + mMaxPreventReloadBannedIds != 0 && + it->second.mOwnOpinionTs + mMaxPreventReloadBannedIds < now ) { #ifdef DEBUG_REPUTATION std::cerr << " ID " << it->first << ": own is negative for more than " << mMaxPreventReloadBannedIds/86400 << " days. Reseting it!" << std::endl; @@ -392,7 +395,10 @@ void p3GxsReputation::cleanup() // Delete slots with basically no information - if(it->second.mOpinions.empty() && it->second.mOwnOpinion == RsReputations::OPINION_NEUTRAL && (it->second.mOwnerNode.isNull())) + if( it->second.mOpinions.empty() && + it->second.mOwnOpinion == + static_cast(RsOpinion::NEUTRAL) && + it->second.mOwnerNode.isNull() ) { #ifdef DEBUG_REPUTATION std::cerr << " ID " << it->first << ": own is neutral and no opinions from friends => remove entry" << std::endl; @@ -461,23 +467,20 @@ void p3GxsReputation::cleanup() RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/ for(std::map::iterator it(mReputations.begin());it!=mReputations.end();++it) - if(it->second.mOwnOpinion == RsReputations::OPINION_NEUTRAL) + if( it->second.mOwnOpinion == + static_cast(RsOpinion::NEUTRAL) ) should_set_to_positive_candidates.push_back(it->first) ; } for(std::list::const_iterator it(should_set_to_positive_candidates.begin());it!=should_set_to_positive_candidates.end();++it) if(rsIdentity->isARegularContact(*it)) - setOwnOpinion(*it,RsReputations::OPINION_POSITIVE) ; + setOwnOpinion(*it, RsOpinion::POSITIVE); } } -const float RsReputations::REPUTATION_THRESHOLD_ANTI_SPAM = 1.4f ; -const float RsReputations::REPUTATION_THRESHOLD_DEFAULT = 1.0f ; - - -static RsReputations::Opinion safe_convert_uint32t_to_opinion(uint32_t op) +static RsOpinion safe_convert_uint32t_to_opinion(uint32_t op) { - return RsReputations::Opinion(std::min((uint32_t)op,UPPER_LIMIT)) ; + return RsOpinion(std::min( static_cast(op), UPPER_LIMIT )); } /***** Implementation ******/ @@ -631,13 +634,14 @@ bool p3GxsReputation::SendReputations(RsGxsReputationRequestItem *request) return true; } -void p3GxsReputation::locked_updateOpinion(const RsPeerId& from,const RsGxsId& about,RsReputations::Opinion op) +void p3GxsReputation::locked_updateOpinion( + const RsPeerId& from, const RsGxsId& about, RsOpinion op ) { /* find matching Reputation */ std::map::iterator rit = mReputations.find(about); - RsReputations::Opinion new_opinion = safe_convert_uint32t_to_opinion(op); - RsReputations::Opinion old_opinion = RsReputations::OPINION_NEUTRAL ; // default if not set + RsOpinion new_opinion = op; + RsOpinion old_opinion = RsOpinion::NEUTRAL ; // default if not set bool updated = false ; @@ -658,9 +662,9 @@ void p3GxsReputation::locked_updateOpinion(const RsPeerId& from,const RsGxsId& a std::cerr << " no preview record"<< std::endl; #endif - if(new_opinion != RsReputations::OPINION_NEUTRAL) + if(new_opinion != RsOpinion::NEUTRAL) { - mReputations[about] = Reputation(about); + mReputations[about] = Reputation(); rit = mReputations.find(about); } else @@ -674,11 +678,11 @@ void p3GxsReputation::locked_updateOpinion(const RsPeerId& from,const RsGxsId& a Reputation& reputation = rit->second; - std::map::iterator it2 = reputation.mOpinions.find(from) ; + std::map::iterator it2 = reputation.mOpinions.find(from) ; if(it2 == reputation.mOpinions.end()) { - if(new_opinion != RsReputations::OPINION_NEUTRAL) + if(new_opinion != RsOpinion::NEUTRAL) { reputation.mOpinions[from] = new_opinion; // filters potentially tweaked reputation score sent by friend updated = true ; @@ -688,7 +692,7 @@ void p3GxsReputation::locked_updateOpinion(const RsPeerId& from,const RsGxsId& a { old_opinion = it2->second ; - if(new_opinion == RsReputations::OPINION_NEUTRAL) + if(new_opinion == RsOpinion::NEUTRAL) { reputation.mOpinions.erase(it2) ; // don't store when the opinion is neutral updated = true ; @@ -700,7 +704,8 @@ void p3GxsReputation::locked_updateOpinion(const RsPeerId& from,const RsGxsId& a } } - if(reputation.mOpinions.empty() && reputation.mOwnOpinion == RsReputations::OPINION_NEUTRAL) + if( reputation.mOpinions.empty() && + reputation.mOwnOpinion == static_cast(RsOpinion::NEUTRAL) ) { mReputations.erase(rit) ; #ifdef DEBUG_REPUTATION @@ -766,9 +771,10 @@ bool p3GxsReputation::updateLatestUpdate(RsPeerId peerid,rstime_t latest_update) * Opinion ****/ -RsReputations::ReputationLevel p3GxsReputation::overallReputationLevel(const RsGxsId& id,uint32_t *identity_flags) +RsReputationLevel p3GxsReputation::overallReputationLevel( + const RsGxsId& id, uint32_t* identity_flags ) { - ReputationInfo info ; + RsReputationInfo info ; getReputationInfo(id,RsPgpId(),info) ; RsPgpId owner_id ; @@ -805,12 +811,14 @@ bool p3GxsReputation::getIdentityFlagsAndOwnerId(const RsGxsId& gxsid, uint32_t& return true ; } -bool p3GxsReputation::getReputationInfo(const RsGxsId& gxsid, const RsPgpId& ownerNode, RsReputations::ReputationInfo& info, bool stamp) +bool p3GxsReputation::getReputationInfo( + const RsGxsId& gxsid, const RsPgpId& ownerNode, RsReputationInfo& info, + bool stamp ) { if(gxsid.isNull()) return false ; - rstime_t now = time(NULL) ; + rstime_t now = time(nullptr); RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/ @@ -822,7 +830,7 @@ bool p3GxsReputation::getReputationInfo(const RsGxsId& gxsid, const RsPgpId& own if(it == mReputations.end()) { - info.mOwnOpinion = RsReputations::OPINION_NEUTRAL ; + info.mOwnOpinion = RsOpinion::NEUTRAL ; info.mFriendAverageScore = REPUTATION_THRESHOLD_DEFAULT ; info.mFriendsNegativeVotes = 0 ; info.mFriendsPositiveVotes = 0 ; @@ -833,7 +841,9 @@ bool p3GxsReputation::getReputationInfo(const RsGxsId& gxsid, const RsPgpId& own { Reputation& rep(it->second) ; - info.mOwnOpinion = RsReputations::Opinion(rep.mOwnOpinion) ; + info.mOwnOpinion = + safe_convert_uint32t_to_opinion( + static_cast(rep.mOwnOpinion) ); info.mFriendAverageScore = rep.mFriendAverage ; info.mFriendsNegativeVotes = rep.mFriendsNegative ; info.mFriendsPositiveVotes = rep.mFriendsPositive ; @@ -853,18 +863,18 @@ bool p3GxsReputation::getReputationInfo(const RsGxsId& gxsid, const RsPgpId& own // 0 - check for own opinion. If positive or negative, it decides on the result - if(info.mOwnOpinion == RsReputations::OPINION_NEGATIVE) + if(info.mOwnOpinion == RsOpinion::NEGATIVE) { // own opinion is always read in priority - info.mOverallReputationLevel = RsReputations::REPUTATION_LOCALLY_NEGATIVE ; + info.mOverallReputationLevel = RsReputationLevel::LOCALLY_NEGATIVE; return true ; } - if(info.mOwnOpinion == RsReputations::OPINION_POSITIVE) + if(info.mOwnOpinion == RsOpinion::POSITIVE) { // own opinion is always read in priority - info.mOverallReputationLevel = RsReputations::REPUTATION_LOCALLY_POSITIVE ; + info.mOverallReputationLevel = RsReputationLevel::LOCALLY_POSITIVE; return true ; } @@ -889,7 +899,7 @@ bool p3GxsReputation::getReputationInfo(const RsGxsId& gxsid, const RsPgpId& own #ifdef DEBUG_REPUTATION2 std::cerr << "p3GxsReputations: identity " << gxsid << " is banned because owner node ID " << owner_id << " is banned (found in banned nodes list)." << std::endl; #endif - info.mOverallReputationLevel = RsReputations::REPUTATION_LOCALLY_NEGATIVE ; + info.mOverallReputationLevel = RsReputationLevel::LOCALLY_NEGATIVE; return true ; } // also check the proxy @@ -899,17 +909,17 @@ bool p3GxsReputation::getReputationInfo(const RsGxsId& gxsid, const RsPgpId& own #ifdef DEBUG_REPUTATION2 std::cerr << "p3GxsReputations: identity " << gxsid << " is banned because owner node ID " << owner_id << " is banned (found in proxy)." << std::endl; #endif - info.mOverallReputationLevel = RsReputations::REPUTATION_LOCALLY_NEGATIVE ; + info.mOverallReputationLevel = RsReputationLevel::LOCALLY_NEGATIVE; return true; } // 2 - now, our own opinion is neutral, which means we rely on what our friends tell if(info.mFriendsPositiveVotes >= info.mFriendsNegativeVotes + mMinVotesForRemotelyPositive) - info.mOverallReputationLevel = RsReputations::REPUTATION_REMOTELY_POSITIVE ; + info.mOverallReputationLevel = RsReputationLevel::REMOTELY_POSITIVE; else if(info.mFriendsPositiveVotes + mMinVotesForRemotelyNegative <= info.mFriendsNegativeVotes) - info.mOverallReputationLevel = RsReputations::REPUTATION_REMOTELY_NEGATIVE ; + info.mOverallReputationLevel = RsReputationLevel::REMOTELY_NEGATIVE; else - info.mOverallReputationLevel = RsReputations::REPUTATION_NEUTRAL ; + info.mOverallReputationLevel = RsReputationLevel::NEUTRAL; #ifdef DEBUG_REPUTATION2 std::cerr << " information present. OwnOp = " << info.mOwnOpinion << ", owner node=" << owner_id << ", overall score=" << info.mAssessment << std::endl; @@ -978,7 +988,7 @@ bool p3GxsReputation::isNodeBanned(const RsPgpId& id) bool p3GxsReputation::isIdentityBanned(const RsGxsId &id) { - RsReputations::ReputationInfo info ; + RsReputationInfo info; if(!getReputationInfo(id,RsPgpId(),info)) return false ; @@ -986,10 +996,11 @@ bool p3GxsReputation::isIdentityBanned(const RsGxsId &id) #ifdef DEBUG_REPUTATION std::cerr << "isIdentityBanned(): returning " << (info.mOverallReputationLevel == RsReputations::REPUTATION_LOCALLY_NEGATIVE) << " for GXS id " << id << std::endl; #endif - return info.mOverallReputationLevel == RsReputations::REPUTATION_LOCALLY_NEGATIVE ; + return info.mOverallReputationLevel == RsReputationLevel::LOCALLY_NEGATIVE; } -bool p3GxsReputation::getOwnOpinion(const RsGxsId& gxsid, RsReputations::Opinion& opinion) +bool p3GxsReputation::getOwnOpinion( + const RsGxsId& gxsid, RsOpinion& opinion ) { #ifdef DEBUG_REPUTATION std::cerr << "setOwnOpinion(): for GXS id " << gxsid << " to " << opinion << std::endl; @@ -1000,19 +1011,21 @@ bool p3GxsReputation::getOwnOpinion(const RsGxsId& gxsid, RsReputations::Opinion return false ; } - RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/ + RS_STACK_MUTEX(mReputationMtx); std::map::iterator rit = mReputations.find(gxsid); - if(rit != mReputations.end()) - opinion = RsReputations::Opinion(rit->second.mOwnOpinion) ; - else - opinion = RsReputations::OPINION_NEUTRAL ; + if(rit != mReputations.end()) + opinion = safe_convert_uint32t_to_opinion( + static_cast(rit->second.mOwnOpinion) ); + else + opinion = RsOpinion::NEUTRAL; return true; } -bool p3GxsReputation::setOwnOpinion(const RsGxsId& gxsid, const RsReputations::Opinion& opinion) +bool p3GxsReputation::setOwnOpinion( + const RsGxsId& gxsid, RsOpinion opinion ) { #ifdef DEBUG_REPUTATION std::cerr << "setOwnOpinion(): for GXS id " << gxsid << " to " << opinion << std::endl; @@ -1022,8 +1035,8 @@ bool p3GxsReputation::setOwnOpinion(const RsGxsId& gxsid, const RsReputations::O std::cerr << " ID " << gxsid << " is rejected. Look for a bug in calling method." << std::endl; return false ; } - - RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/ + + RS_STACK_MUTEX(mReputationMtx); std::map::iterator rit; @@ -1033,7 +1046,7 @@ bool p3GxsReputation::setOwnOpinion(const RsGxsId& gxsid, const RsReputations::O if (rit == mReputations.end()) { #warning csoler 2017-01-05: We should set the owner node id here. - mReputations[gxsid] = Reputation(gxsid); + mReputations[gxsid] = Reputation(); rit = mReputations.find(gxsid); } @@ -1041,7 +1054,7 @@ bool p3GxsReputation::setOwnOpinion(const RsGxsId& gxsid, const RsReputations::O Reputation &reputation = rit->second; if (reputation.mOwnOpinionTs != 0) { - if (reputation.mOwnOpinion == opinion) + if (reputation.mOwnOpinion == static_cast(opinion)) { // if opinion is accurate, don't update. return false; @@ -1060,8 +1073,8 @@ bool p3GxsReputation::setOwnOpinion(const RsGxsId& gxsid, const RsReputations::O } } - rstime_t now = time(NULL); - reputation.mOwnOpinion = opinion; + rstime_t now = time(nullptr); + reputation.mOwnOpinion = static_cast(opinion); reputation.mOwnOpinionTs = now; reputation.updateReputation(); @@ -1126,7 +1139,7 @@ bool p3GxsReputation::saveList(bool& cleanup, std::list &savelist) item->mOwnerNodeId = rit->second.mOwnerNode; item->mLastUsedTS = rit->second.mLastUsedTS; - std::map::iterator oit; + std::map::iterator oit; for(oit = rit->second.mOpinions.begin(); oit != rit->second.mOpinions.end(); ++oit) { // should be already limited. @@ -1492,15 +1505,16 @@ void Reputation::updateReputation() // accounts for all friends. Neutral opinions count for 1-1=0 // because the average is performed over only accessible peers (not the total number) we need to shift to 1 - for(std::map::const_iterator it(mOpinions.begin());it!=mOpinions.end();++it) + for( std::map::const_iterator it(mOpinions.begin()); + it != mOpinions.end(); ++it ) { - if( it->second == RsReputations::OPINION_NEGATIVE) + if( it->second == RsOpinion::NEGATIVE) ++mFriendsNegative ; - if( it->second == RsReputations::OPINION_POSITIVE) + if( it->second == RsOpinion::POSITIVE) ++mFriendsPositive ; - friend_total += it->second - 1 ; + friend_total += static_cast(it->second) - 1; } if(mOpinions.empty()) // includes the case of no friends! @@ -1554,11 +1568,10 @@ void Reputation::updateReputation() } // now compute a bias for PGP-signed ids. - - if(mOwnOpinion == RsReputations::OPINION_NEUTRAL) - mReputationScore = mFriendAverage ; - else - mReputationScore = (float)mOwnOpinion ; + + if(mOwnOpinion == static_cast(RsOpinion::NEUTRAL)) + mReputationScore = mFriendAverage; + else mReputationScore = static_cast(mOwnOpinion); } void p3GxsReputation::debug_print() @@ -1567,19 +1580,22 @@ void p3GxsReputation::debug_print() std::cerr << " GXS ID data: " << std::endl; std::cerr << std::dec ; -std::map rep_copy; + std::map rep_copy; -{ - RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/ - rep_copy = mReputations ; -} - rstime_t now = time(NULL) ; + { + RS_STACK_MUTEX(mReputationMtx); + rep_copy = mReputations; + } - for(std::map::const_iterator it(rep_copy.begin());it!=rep_copy.end();++it) + rstime_t now = time(nullptr); + + + for( std::map::const_iterator it(rep_copy.begin()); + it != rep_copy.end(); ++it ) { - RsReputations::ReputationInfo info ; - getReputationInfo(it->first,RsPgpId(),info,false) ; - uint32_t lev = info.mOverallReputationLevel; + RsReputationInfo info; + getReputationInfo(it->first, RsPgpId(), info, false); + uint32_t lev = static_cast(info.mOverallReputationLevel); std::cerr << " " << it->first << ": own: " << it->second.mOwnOpinion << ", PGP id=" << it->second.mOwnerNode @@ -1596,7 +1612,7 @@ std::map rep_copy; #endif } - RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/ + RS_STACK_MUTEX(mReputationMtx); std::cerr << " Banned RS nodes by ID: " << std::endl; for(std::map::const_iterator it(mBannedPgpIds.begin());it!=mBannedPgpIds.end();++it) diff --git a/libretroshare/src/services/p3gxsreputation.h b/libretroshare/src/services/p3gxsreputation.h index d27bb79cc..688ec9711 100644 --- a/libretroshare/src/services/p3gxsreputation.h +++ b/libretroshare/src/services/p3gxsreputation.h @@ -64,15 +64,17 @@ struct BannedNodeInfo class Reputation { public: - Reputation() - :mOwnOpinion(RsReputations::OPINION_NEUTRAL), mOwnOpinionTs(0),mFriendAverage(1.0f), mReputationScore(RsReputations::OPINION_NEUTRAL),mIdentityFlags(0){ } - - Reputation(const RsGxsId& /*about*/) - :mOwnOpinion(RsReputations::OPINION_NEUTRAL), mOwnOpinionTs(0),mFriendAverage(1.0f), mReputationScore(RsReputations::OPINION_NEUTRAL),mIdentityFlags(0){ } + Reputation() : + mOwnOpinion(static_cast(RsOpinion::NEUTRAL)), mOwnOpinionTs(0), + mFriendAverage(1.0f), + /* G10h4ck: TODO shouln't this be initialized with + * RsReputation::NEUTRAL or UNKOWN? */ + mReputationScore(static_cast(RsOpinion::NEUTRAL)), + mIdentityFlags(0) {} void updateReputation(); - std::map mOpinions; + std::map mOpinions; int32_t mOwnOpinion; rstime_t mOwnOpinionTs; @@ -103,14 +105,17 @@ public: virtual RsServiceInfo getServiceInfo(); /***** Interface for RsReputations *****/ - virtual bool setOwnOpinion(const RsGxsId& key_id, const Opinion& op) ; - virtual bool getOwnOpinion(const RsGxsId& key_id, Opinion& op) ; - virtual bool getReputationInfo(const RsGxsId& id, const RsPgpId &ownerNode, ReputationInfo& info,bool stamp=true) ; + virtual bool setOwnOpinion(const RsGxsId& key_id, RsOpinion op); + virtual bool getOwnOpinion(const RsGxsId& key_id, RsOpinion& op) ; + virtual bool getReputationInfo( + const RsGxsId& id, const RsPgpId& ownerNode, RsReputationInfo& info, + bool stamp = true ); virtual bool isIdentityBanned(const RsGxsId& id) ; virtual bool isNodeBanned(const RsPgpId& id); virtual void banNode(const RsPgpId& id,bool b) ; - virtual ReputationLevel overallReputationLevel(const RsGxsId& id,uint32_t *identity_flags=NULL); + virtual RsReputationLevel overallReputationLevel( + const RsGxsId& id, uint32_t* identity_flags = nullptr ); virtual void setNodeAutoPositiveOpinionForContacts(bool b) ; virtual bool nodeAutoPositiveOpinionForContacts() ; @@ -149,7 +154,8 @@ private: void updateBannedNodesProxy(); // internal update of data. Takes care of cleaning empty boxes. - void locked_updateOpinion(const RsPeerId &from, const RsGxsId &about, RsReputations::Opinion op); + void locked_updateOpinion( + const RsPeerId& from, const RsGxsId& about, RsOpinion op); bool loadReputationSet(RsGxsReputationSetItem *item, const std::set &peerSet); #ifdef TO_REMOVE bool loadReputationSet_deprecated3(RsGxsReputationSetItem_deprecated3 *item, const std::set &peerSet); diff --git a/libretroshare/src/services/p3idservice.cc b/libretroshare/src/services/p3idservice.cc index e4046210b..bd7ca905a 100644 --- a/libretroshare/src/services/p3idservice.cc +++ b/libretroshare/src/services/p3idservice.cc @@ -713,9 +713,10 @@ bool p3IdService::getIdDetails(const RsGxsId &id, RsIdentityDetails &details) if(is_a_contact && rsReputations->nodeAutoPositiveOpinionForContacts()) { - RsReputations::Opinion op ; - if(rsReputations->getOwnOpinion(id,op) && op == RsReputations::OPINION_NEUTRAL) - rsReputations->setOwnOpinion(id,RsReputations::OPINION_POSITIVE) ; + RsOpinion op; + if( rsReputations->getOwnOpinion(id,op) && + op == RsOpinion::NEUTRAL ) + rsReputations->setOwnOpinion(id, RsOpinion::POSITIVE); } std::map::const_iterator it = mKeysTS.find(id) ; @@ -1167,10 +1168,10 @@ bool p3IdService::requestKey(const RsGxsId &id, const std::list& peers std::cerr << "p3IdService::requesting key " << id <getReputationInfo(id,RsPgpId(),info) ; - if(info.mOverallReputationLevel == RsReputations::REPUTATION_LOCALLY_NEGATIVE) + if( info.mOverallReputationLevel == RsReputationLevel::LOCALLY_NEGATIVE ) { std::cerr << "(II) not requesting Key " << id << " because it has been banned." << std::endl; From a6e8a27fc0355235f7e0dcf20152faa4eda14195 Mon Sep 17 00:00:00 2001 From: Gioacchino Mazzurco Date: Sat, 16 Feb 2019 11:41:31 -0300 Subject: [PATCH 09/81] Add RsReputations JSON API --- libretroshare/src/retroshare/rsreputations.h | 164 +++++++++++++++--- libretroshare/src/services/p3gxsreputation.cc | 16 +- libretroshare/src/services/p3gxsreputation.h | 18 +- libretroshare/src/services/p3idservice.cc | 2 +- 4 files changed, 162 insertions(+), 38 deletions(-) diff --git a/libretroshare/src/retroshare/rsreputations.h b/libretroshare/src/retroshare/rsreputations.h index 68f49c058..8ea6ff213 100644 --- a/libretroshare/src/retroshare/rsreputations.h +++ b/libretroshare/src/retroshare/rsreputations.h @@ -3,7 +3,8 @@ * * * libretroshare: retroshare core library * * * - * Copyright 2015 by Cyril Soler * + * Copyright (C) 2015 Cyril Soler * + * Copyright (C) 2018 Gioacchino Mazzurco * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * @@ -23,6 +24,7 @@ #include "retroshare/rsids.h" #include "retroshare/rsgxsifacetypes.h" +#include "serialiser/rsserializable.h" class RsReputations; @@ -33,8 +35,7 @@ class RsReputations; extern RsReputations* rsReputations; -const float REPUTATION_THRESHOLD_DEFAULT = 1.0f; -const float REPUTATION_THRESHOLD_ANTI_SPAM = 1.4f; +constexpr float RS_REPUTATION_THRESHOLD_DEFAULT = 1.0f; enum struct RsOpinion : uint8_t { @@ -64,13 +65,14 @@ enum struct RsReputationLevel : uint8_t UNKNOWN = 0x05 }; -struct RsReputationInfo +struct RsReputationInfo : RsSerializable { RsReputationInfo() : mOwnOpinion(RsOpinion::NEUTRAL), mFriendsPositiveVotes(0), mFriendsNegativeVotes(0), - mFriendAverageScore(REPUTATION_THRESHOLD_DEFAULT), + mFriendAverageScore(RS_REPUTATION_THRESHOLD_DEFAULT), mOverallReputationLevel(RsReputationLevel::NEUTRAL) {} + virtual ~RsReputationInfo() {} RsOpinion mOwnOpinion; @@ -81,6 +83,17 @@ struct RsReputationInfo /// this should help clients in taking decisions RsReputationLevel mOverallReputationLevel; + + /// @see RsSerializable + void serial_process( RsGenericSerializer::SerializeJob j, + RsGenericSerializer::SerializeContext& ctx ) override + { + RS_SERIAL_PROCESS(mOwnOpinion); + RS_SERIAL_PROCESS(mFriendsPositiveVotes); + RS_SERIAL_PROCESS(mFriendsNegativeVotes); + RS_SERIAL_PROCESS(mFriendAverageScore); + RS_SERIAL_PROCESS(mOverallReputationLevel); + } }; @@ -89,34 +102,143 @@ class RsReputations public: virtual ~RsReputations() {} - virtual bool setOwnOpinion(const RsGxsId& key_id, RsOpinion op) = 0; - virtual bool getOwnOpinion(const RsGxsId& key_id, RsOpinion& op) = 0; + /** + * @brief Set own opinion about the given identity + * @jsonapi{development} + * @param[in] id Id of the identity + * @param[in] op Own opinion + * @return false on error, true otherwise + */ + virtual bool setOwnOpinion(const RsGxsId& id, RsOpinion op) = 0; + + /** + * @brief Get own opition about the given identity + * @jsonapi{development} + * @param[in] id Id of the identity + * @param[out] op Own opinion + * @return false on error, true otherwise + */ + virtual bool getOwnOpinion(const RsGxsId& id, RsOpinion& op) = 0; + + /** + * @brief Get reputation data of given identity + * @jsonapi{development} + * @param[in] id Id of the identity + * @param[in] ownerNode Optiona PGP id of the signed identity, accept a null + * (all zero/noninitialized) PGP id + * @param[out] info storage for the information + * @param[in] stamp if true, timestamo the information + * @return false on error, true otherwise + */ virtual bool getReputationInfo( const RsGxsId& id, const RsPgpId& ownerNode, RsReputationInfo& info, bool stamp = true ) = 0; - /** This returns the reputation level and also the flags of the identity - * service for that id. This is useful in order to get these flags without - * relying on the async method of p3Identity */ - RS_DEPRECATED - virtual RsReputationLevel overallReputationLevel( - const RsGxsId& id, uint32_t* identity_flags = nullptr) = 0; + /** + * @brief Get overall reputation level of given identity + * @jsonapi{development} + * @param[in] id Id of the identity + * @return the calculated reputation level based on available information + */ + virtual RsReputationLevel overallReputationLevel(const RsGxsId& id) = 0; - virtual void setNodeAutoPositiveOpinionForContacts(bool b) = 0; - virtual bool nodeAutoPositiveOpinionForContacts() = 0; + /** + * @brief Enable giving automatic positive opinion when flagging as contact + * @jsonapi{development} + * @param[in] b true to enable, false to disable + */ + virtual void setAutoPositiveOpinionForContacts(bool b) = 0; - virtual uint32_t thresholdForRemotelyNegativeReputation() = 0; - virtual uint32_t thresholdForRemotelyPositiveReputation() = 0; + /** + * @brief check if giving automatic positive opinion when flagging as + * contact is enbaled + * @jsonapi{development} + * @return true if enabled, false otherwise + */ + virtual bool autoPositiveOpinionForContacts() = 0; + + /** + * @brief Set threshold on remote reputation to consider it remotely + * negative + * @jsonapi{development} + * @param[in] thresh Threshold value + */ virtual void setThresholdForRemotelyNegativeReputation(uint32_t thresh) = 0; + + /** + * * @brief Get threshold on remote reputation to consider it remotely + * negative + * @jsonapi{development} + * @return Threshold value + */ + virtual uint32_t thresholdForRemotelyNegativeReputation() = 0; + + /** + * @brief Set threshold on remote reputation to consider it remotely + * positive + * @jsonapi{development} + * @param[in] thresh Threshold value + */ virtual void setThresholdForRemotelyPositiveReputation(uint32_t thresh) = 0; - virtual void setRememberDeletedNodesThreshold(uint32_t days) = 0; - virtual uint32_t rememberDeletedNodesThreshold() = 0; + /** + * @brief Get threshold on remote reputation to consider it remotely + * negative + * @jsonapi{development} + * @return Threshold value + */ + virtual uint32_t thresholdForRemotelyPositiveReputation() = 0; - /** This one is a proxy designed to allow fast checking of a GXS id. - * It basically returns true if assessment is not ASSESSMENT_OK */ + /** + * @brief Get number of days to wait before deleting a banned identity from + * local storage + * @jsonapi{development} + * @return number of days to wait, 0 means never delete + */ + virtual uint32_t rememberBannedIdThreshold() = 0; + + /** + * @brief Set number of days to wait before deleting a banned identity from + * local storage + * @jsonapi{development} + * @param[in] days number of days to wait, 0 means never delete + */ + virtual void setRememberBannedIdThreshold(uint32_t days) = 0; + + /** + * @brief This method allow fast checking if a GXS identity is banned. + * @jsonapi{development} + * @param[in] id Id of the identity to check + * @return true if identity is banned, false otherwise + */ virtual bool isIdentityBanned(const RsGxsId& id) = 0; + /** + * @brief Check if automatic banning of all identities signed by the given + * node is enabled + * @jsonapi{development} + * @param[in] id PGP id of the node + * @return true if enabled, false otherwise + */ virtual bool isNodeBanned(const RsPgpId& id) = 0; + + /** + * @brief Enable automatic banning of all identities signed by the given + * node + * @jsonapi{development} + * @param[in] id PGP id of the node + * @param[in] b true to enable, false to disable + */ virtual void banNode(const RsPgpId& id, bool b) = 0; + + + /** + * @deprecated + * This returns the reputation level and also the flags of the identity + * service for that id. This is useful in order to get these flags without + * relying on the async method of p3Identity + */ + RS_DEPRECATED + virtual RsReputationLevel overallReputationLevel( + const RsGxsId& id, uint32_t* identity_flags ) = 0; }; diff --git a/libretroshare/src/services/p3gxsreputation.cc b/libretroshare/src/services/p3gxsreputation.cc index e99c07b2e..a6fb352d2 100644 --- a/libretroshare/src/services/p3gxsreputation.cc +++ b/libretroshare/src/services/p3gxsreputation.cc @@ -236,7 +236,7 @@ int p3GxsReputation::tick() return 0; } -void p3GxsReputation::setNodeAutoPositiveOpinionForContacts(bool b) +void p3GxsReputation::setAutoPositiveOpinionForContacts(bool b) { RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/ @@ -249,13 +249,13 @@ void p3GxsReputation::setNodeAutoPositiveOpinionForContacts(bool b) IndicateConfigChanged() ; } } -bool p3GxsReputation::nodeAutoPositiveOpinionForContacts() +bool p3GxsReputation::autoPositiveOpinionForContacts() { RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/ return mAutoSetPositiveOptionToContacts ; } -void p3GxsReputation::setRememberDeletedNodesThreshold(uint32_t days) +void p3GxsReputation::setRememberBannedIdThreshold(uint32_t days) { RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/ @@ -265,7 +265,7 @@ void p3GxsReputation::setRememberDeletedNodesThreshold(uint32_t days) IndicateConfigChanged(); } } -uint32_t p3GxsReputation::rememberDeletedNodesThreshold() +uint32_t p3GxsReputation::rememberBannedIdThreshold() { RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/ @@ -831,7 +831,7 @@ bool p3GxsReputation::getReputationInfo( if(it == mReputations.end()) { info.mOwnOpinion = RsOpinion::NEUTRAL ; - info.mFriendAverageScore = REPUTATION_THRESHOLD_DEFAULT ; + info.mFriendAverageScore = RS_REPUTATION_THRESHOLD_DEFAULT ; info.mFriendsNegativeVotes = 0 ; info.mFriendsPositiveVotes = 0 ; @@ -979,9 +979,13 @@ void p3GxsReputation::banNode(const RsPgpId& id,bool b) } } } + +RsReputationLevel p3GxsReputation::overallReputationLevel(const RsGxsId& id) +{ return overallReputationLevel(id, nullptr); } + bool p3GxsReputation::isNodeBanned(const RsPgpId& id) { - RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/ + RsStackMutex stack(mReputationMtx); /****** LOCKED MUTEX *******/ return mBannedPgpIds.find(id) != mBannedPgpIds.end(); } diff --git a/libretroshare/src/services/p3gxsreputation.h b/libretroshare/src/services/p3gxsreputation.h index 688ec9711..e9a14d4e7 100644 --- a/libretroshare/src/services/p3gxsreputation.h +++ b/libretroshare/src/services/p3gxsreputation.h @@ -93,11 +93,6 @@ public: //!The p3GxsReputation service. - /** - * - * - */ - class p3GxsReputation: public p3Service, public p3Config, public RsGixsReputation, public RsReputations /* , public pqiMonitor */ { public: @@ -114,14 +109,17 @@ public: virtual bool isNodeBanned(const RsPgpId& id); virtual void banNode(const RsPgpId& id,bool b) ; + + RsReputationLevel overallReputationLevel(const RsGxsId& id) override; + virtual RsReputationLevel overallReputationLevel( - const RsGxsId& id, uint32_t* identity_flags = nullptr ); + const RsGxsId& id, uint32_t* identity_flags ); - virtual void setNodeAutoPositiveOpinionForContacts(bool b) ; - virtual bool nodeAutoPositiveOpinionForContacts() ; + virtual void setAutoPositiveOpinionForContacts(bool b) ; + virtual bool autoPositiveOpinionForContacts() ; - virtual void setRememberDeletedNodesThreshold(uint32_t days) ; - virtual uint32_t rememberDeletedNodesThreshold() ; + virtual void setRememberBannedIdThreshold(uint32_t days) ; + virtual uint32_t rememberBannedIdThreshold() ; uint32_t thresholdForRemotelyNegativeReputation(); uint32_t thresholdForRemotelyPositiveReputation(); diff --git a/libretroshare/src/services/p3idservice.cc b/libretroshare/src/services/p3idservice.cc index bd7ca905a..de9517843 100644 --- a/libretroshare/src/services/p3idservice.cc +++ b/libretroshare/src/services/p3idservice.cc @@ -711,7 +711,7 @@ bool p3IdService::getIdDetails(const RsGxsId &id, RsIdentityDetails &details) // This step is needed, because p3GxsReputation does not know all identities, and might not have any data for // the ones in the contact list. So we change them on demand. - if(is_a_contact && rsReputations->nodeAutoPositiveOpinionForContacts()) + if(is_a_contact && rsReputations->autoPositiveOpinionForContacts()) { RsOpinion op; if( rsReputations->getOwnOpinion(id,op) && From 5ff4ebbd12fa6049a5a1c98dce6d00fbabd25685 Mon Sep 17 00:00:00 2001 From: Gioacchino Mazzurco Date: Sat, 16 Feb 2019 11:42:22 -0300 Subject: [PATCH 10/81] Fix retroshare-gui compilation after RsReputations refactoring --- .../src/gui/Identity/IdDetailsDialog.cpp | 69 +++++++----- retroshare-gui/src/gui/Identity/IdDialog.cpp | 105 ++++++++++-------- .../src/gui/chat/ChatLobbyDialog.cpp | 25 +++-- retroshare-gui/src/gui/gxs/GxsIdDetails.cpp | 40 ++++--- retroshare-gui/src/gui/gxs/GxsIdDetails.h | 6 +- .../src/gui/gxs/GxsIdTreeWidgetItem.cpp | 46 ++++---- .../src/gui/gxs/GxsIdTreeWidgetItem.h | 2 +- .../src/gui/gxsforums/GxsForumModel.cpp | 14 ++- .../src/gui/gxsforums/GxsForumModel.h | 2 +- .../gui/gxsforums/GxsForumThreadWidget.cpp | 27 +++-- .../src/gui/settings/PeoplePage.cpp | 8 +- 11 files changed, 199 insertions(+), 145 deletions(-) diff --git a/retroshare-gui/src/gui/Identity/IdDetailsDialog.cpp b/retroshare-gui/src/gui/Identity/IdDetailsDialog.cpp index 98b8a0d91..58378a656 100644 --- a/retroshare-gui/src/gui/Identity/IdDetailsDialog.cpp +++ b/retroshare-gui/src/gui/Identity/IdDetailsDialog.cpp @@ -285,7 +285,7 @@ void IdDetailsDialog::insertIdDetails(uint32_t token) #endif - RsReputations::ReputationInfo info ; + RsReputationInfo info; rsReputations->getReputationInfo(RsGxsId(data.mMeta.mGroupId),data.mPgpId,info) ; #warning (csoler) Do we need to do this? This code is apparently not used. @@ -302,23 +302,34 @@ void IdDetailsDialog::insertIdDetails(uint32_t token) ui->label_positive->setText(QString::number(info.mFriendsPositiveVotes)); ui->label_negative->setText(QString::number(info.mFriendsNegativeVotes)); - switch(info.mOverallReputationLevel) - { - case RsReputations::REPUTATION_LOCALLY_POSITIVE: ui->overallOpinion_TF->setText(tr("Positive")) ; break ; - case RsReputations::REPUTATION_LOCALLY_NEGATIVE: ui->overallOpinion_TF->setText(tr("Negative (Banned by you)")) ; break ; - case RsReputations::REPUTATION_REMOTELY_POSITIVE: ui->overallOpinion_TF->setText(tr("Positive (according to your friends)")) ; break ; - case RsReputations::REPUTATION_REMOTELY_NEGATIVE: ui->overallOpinion_TF->setText(tr("Negative (according to your friends)")) ; break ; - default: - case RsReputations::REPUTATION_NEUTRAL: ui->overallOpinion_TF->setText(tr("Neutral")) ; break ; - } - - switch(info.mOwnOpinion) + switch(info.mOverallReputationLevel) { - case RsReputations::OPINION_NEGATIVE: ui->ownOpinion_CB->setCurrentIndex(0); break ; - case RsReputations::OPINION_NEUTRAL : ui->ownOpinion_CB->setCurrentIndex(1); break ; - case RsReputations::OPINION_POSITIVE: ui->ownOpinion_CB->setCurrentIndex(2); break ; - default: - std::cerr << "Unexpected value in own opinion: " << info.mOwnOpinion << std::endl; + case RsReputationLevel::LOCALLY_POSITIVE: + ui->overallOpinion_TF->setText(tr("Positive")); break; + case RsReputationLevel::LOCALLY_NEGATIVE: + ui->overallOpinion_TF->setText(tr("Negative (Banned by you)")); break; + case RsReputationLevel::REMOTELY_POSITIVE: + ui->overallOpinion_TF->setText( + tr("Positive (according to your friends)")); + break; + case RsReputationLevel::REMOTELY_NEGATIVE: + ui->overallOpinion_TF->setText( + tr("Negative (according to your friends)")); + break; + case RsReputationLevel::NEUTRAL: // fallthrough + default: + ui->overallOpinion_TF->setText(tr("Neutral")); break; + } + + switch(info.mOwnOpinion) + { + case RsOpinion::NEGATIVE: ui->ownOpinion_CB->setCurrentIndex(0); break; + case RsOpinion::NEUTRAL : ui->ownOpinion_CB->setCurrentIndex(1); break; + case RsOpinion::POSITIVE: ui->ownOpinion_CB->setCurrentIndex(2); break; + default: + std::cerr << "Unexpected value in own opinion: " + << static_cast(info.mOwnOpinion) << std::endl; + break; } } @@ -330,19 +341,19 @@ void IdDetailsDialog::modifyReputation() #endif RsGxsId id(ui->lineEdit_KeyId->text().toStdString()); - - RsReputations::Opinion op ; - switch(ui->ownOpinion_CB->currentIndex()) - { - case 0: op = RsReputations::OPINION_NEGATIVE ; break ; - case 1: op = RsReputations::OPINION_NEUTRAL ; break ; - case 2: op = RsReputations::OPINION_POSITIVE ; break ; - default: - std::cerr << "Wrong value from opinion combobox. Bug??" << std::endl; - - } - rsReputations->setOwnOpinion(id,op) ; + RsOpinion op; + + switch(ui->ownOpinion_CB->currentIndex()) + { + case 0: op = RsOpinion::NEGATIVE; break; + case 1: op = RsOpinion::NEUTRAL ; break; + case 2: op = RsOpinion::POSITIVE; break; + default: + std::cerr << "Wrong value from opinion combobox. Bug??" << std::endl; + break; + } + rsReputations->setOwnOpinion(id,op); #ifdef ID_DEBUG std::cerr << "IdDialog::modifyReputation() ID: " << id << " Mod: " << mod; diff --git a/retroshare-gui/src/gui/Identity/IdDialog.cpp b/retroshare-gui/src/gui/Identity/IdDialog.cpp index 0f6817067..703405bb0 100644 --- a/retroshare-gui/src/gui/Identity/IdDialog.cpp +++ b/retroshare-gui/src/gui/Identity/IdDialog.cpp @@ -344,7 +344,9 @@ IdDialog::IdDialog(QWidget *parent) : ui->idTreeWidget->setColumnWidth(RSID_COL_IDTYPE, 18 * fontWidth); ui->idTreeWidget->setColumnWidth(RSID_COL_VOTES, 2 * fontWidth); - ui->idTreeWidget->setItemDelegateForColumn(RSID_COL_VOTES,new ReputationItemDelegate(RsReputations::ReputationLevel(0xff))) ; + ui->idTreeWidget->setItemDelegateForColumn( + RSID_COL_VOTES, + new ReputationItemDelegate(RsReputationLevel(0xff))); /* Set header resize modes and initial section sizes */ QHeaderView * idheader = ui->idTreeWidget->header(); @@ -1444,8 +1446,9 @@ bool IdDialog::fillIdListItem(const RsGxsIdGroup& data, QTreeWidgetItem *&item, RsIdentityDetails idd ; rsIdentity->getIdDetails(RsGxsId(data.mMeta.mGroupId),idd) ; - bool isBanned = idd.mReputation.mOverallReputationLevel == RsReputations::REPUTATION_LOCALLY_NEGATIVE; - uint32_t item_flags = 0 ; + bool isBanned = idd.mReputation.mOverallReputationLevel == + RsReputationLevel::LOCALLY_NEGATIVE; + uint32_t item_flags = 0; /* do filtering */ bool ok = false; @@ -1514,8 +1517,12 @@ bool IdDialog::fillIdListItem(const RsGxsIdGroup& data, QTreeWidgetItem *&item, item->setData(RSID_COL_KEYID, Qt::UserRole,QVariant(item_flags)) ; item->setTextAlignment(RSID_COL_VOTES, Qt::AlignRight | Qt::AlignVCenter); - item->setData(RSID_COL_VOTES,Qt::DecorationRole, idd.mReputation.mOverallReputationLevel); - item->setData(RSID_COL_VOTES,SortRole, idd.mReputation.mOverallReputationLevel); + item->setData( + RSID_COL_VOTES,Qt::DecorationRole, + static_cast(idd.mReputation.mOverallReputationLevel)); + item->setData( + RSID_COL_VOTES,SortRole, + static_cast(idd.mReputation.mOverallReputationLevel)); if(isOwnId) { @@ -1910,7 +1917,7 @@ void IdDialog::insertIdDetails(uint32_t token) #endif - RsReputations::ReputationInfo info ; + RsReputationInfo info; rsReputations->getReputationInfo(RsGxsId(data.mMeta.mGroupId),data.mPgpId,info) ; QString frep_string ; @@ -1925,23 +1932,32 @@ void IdDialog::insertIdDetails(uint32_t token) ui->label_positive->setText(QString::number(info.mFriendsPositiveVotes)); ui->label_negative->setText(QString::number(info.mFriendsNegativeVotes)); - switch(info.mOverallReputationLevel) - { - case RsReputations::REPUTATION_LOCALLY_POSITIVE: ui->overallOpinion_TF->setText(tr("Positive")) ; break ; - case RsReputations::REPUTATION_LOCALLY_NEGATIVE: ui->overallOpinion_TF->setText(tr("Negative (Banned by you)")) ; break ; - case RsReputations::REPUTATION_REMOTELY_POSITIVE: ui->overallOpinion_TF->setText(tr("Positive (according to your friends)")) ; break ; - case RsReputations::REPUTATION_REMOTELY_NEGATIVE: ui->overallOpinion_TF->setText(tr("Negative (according to your friends)")) ; break ; - default: - case RsReputations::REPUTATION_NEUTRAL: ui->overallOpinion_TF->setText(tr("Neutral")) ; break ; - } - - switch(info.mOwnOpinion) + switch(info.mOverallReputationLevel) { - case RsReputations::OPINION_NEGATIVE: ui->ownOpinion_CB->setCurrentIndex(0); break ; - case RsReputations::OPINION_NEUTRAL : ui->ownOpinion_CB->setCurrentIndex(1); break ; - case RsReputations::OPINION_POSITIVE: ui->ownOpinion_CB->setCurrentIndex(2); break ; - default: - std::cerr << "Unexpected value in own opinion: " << info.mOwnOpinion << std::endl; + case RsReputationLevel::LOCALLY_POSITIVE: + ui->overallOpinion_TF->setText(tr("Positive")); break; + case RsReputationLevel::LOCALLY_NEGATIVE: + ui->overallOpinion_TF->setText(tr("Negative (Banned by you)")); break; + case RsReputationLevel::REMOTELY_POSITIVE: + ui->overallOpinion_TF->setText(tr("Positive (according to your friends)")); + break; + case RsReputationLevel::REMOTELY_NEGATIVE: + ui->overallOpinion_TF->setText(tr("Negative (according to your friends)")); + break; + case RsReputationLevel::NEUTRAL: // fallthrough + default: + ui->overallOpinion_TF->setText(tr("Neutral")) ; break ; + } + + switch(info.mOwnOpinion) + { + case RsOpinion::NEGATIVE: ui->ownOpinion_CB->setCurrentIndex(0); break; + case RsOpinion::NEUTRAL : ui->ownOpinion_CB->setCurrentIndex(1); break; + case RsOpinion::POSITIVE: ui->ownOpinion_CB->setCurrentIndex(2); break; + default: + std::cerr << "Unexpected value in own opinion: " + << static_cast(info.mOwnOpinion) << std::endl; + break; } // now fill in usage cases @@ -2060,19 +2076,19 @@ void IdDialog::modifyReputation() #endif RsGxsId id(ui->lineEdit_KeyId->text().toStdString()); - - RsReputations::Opinion op ; - switch(ui->ownOpinion_CB->currentIndex()) - { - case 0: op = RsReputations::OPINION_NEGATIVE ; break ; - case 1: op = RsReputations::OPINION_NEUTRAL ; break ; - case 2: op = RsReputations::OPINION_POSITIVE ; break ; - default: - std::cerr << "Wrong value from opinion combobox. Bug??" << std::endl; - - } - rsReputations->setOwnOpinion(id,op) ; + RsOpinion op; + + switch(ui->ownOpinion_CB->currentIndex()) + { + case 0: op = RsOpinion::NEGATIVE; break; + case 1: op = RsOpinion::NEUTRAL ; break; + case 2: op = RsOpinion::POSITIVE; break; + default: + std::cerr << "Wrong value from opinion combobox. Bug??" << std::endl; + break; + } + rsReputations->setOwnOpinion(id,op); #ifdef ID_DEBUG std::cerr << "IdDialog::modifyReputation() ID: " << id << " Mod: " << op; @@ -2386,17 +2402,12 @@ void IdDialog::IdListCustomPopupMenu( QPoint ) switch(det.mReputation.mOwnOpinion) { - case RsReputations::OPINION_NEGATIVE: ++n_negative_reputations ; - break ; - - case RsReputations::OPINION_POSITIVE: ++n_positive_reputations ; - break ; - - case RsReputations::OPINION_NEUTRAL: ++n_neutral_reputations ; - break ; + case RsOpinion::NEGATIVE: ++n_negative_reputations; break; + case RsOpinion::POSITIVE: ++n_positive_reputations; break; + case RsOpinion::NEUTRAL: ++n_neutral_reputations; break; } - ++n_selected_items ; + ++n_selected_items; if(rsIdentity->isARegularContact(keyId)) ++n_is_a_contact ; @@ -2674,7 +2685,7 @@ void IdDialog::negativePerson() std::string Id = item->text(RSID_COL_KEYID).toStdString(); - rsReputations->setOwnOpinion(RsGxsId(Id),RsReputations::OPINION_NEGATIVE) ; + rsReputations->setOwnOpinion(RsGxsId(Id), RsOpinion::NEGATIVE); } requestIdDetails(); @@ -2690,7 +2701,7 @@ void IdDialog::neutralPerson() std::string Id = item->text(RSID_COL_KEYID).toStdString(); - rsReputations->setOwnOpinion(RsGxsId(Id),RsReputations::OPINION_NEUTRAL) ; + rsReputations->setOwnOpinion(RsGxsId(Id), RsOpinion::NEUTRAL); } requestIdDetails(); @@ -2703,9 +2714,9 @@ void IdDialog::positivePerson() { QTreeWidgetItem *item = *it ; - std::string Id = item->text(RSID_COL_KEYID).toStdString(); + std::string Id = item->text(RSID_COL_KEYID).toStdString(); - rsReputations->setOwnOpinion(RsGxsId(Id),RsReputations::OPINION_POSITIVE) ; + rsReputations->setOwnOpinion(RsGxsId(Id), RsOpinion::POSITIVE); } requestIdDetails(); diff --git a/retroshare-gui/src/gui/chat/ChatLobbyDialog.cpp b/retroshare-gui/src/gui/chat/ChatLobbyDialog.cpp index f31f8c456..ec2994ced 100644 --- a/retroshare-gui/src/gui/chat/ChatLobbyDialog.cpp +++ b/retroshare-gui/src/gui/chat/ChatLobbyDialog.cpp @@ -300,9 +300,17 @@ void ChatLobbyDialog::initParticipantsContextMenu(QMenu *contextMnu, QListsetEnabled(true); sendMessageAct->setEnabled(true); - votePositiveAct->setEnabled(rsReputations->overallReputationLevel(gxsid) != RsReputations::REPUTATION_LOCALLY_POSITIVE); - voteNeutralAct->setEnabled((rsReputations->overallReputationLevel(gxsid) == RsReputations::REPUTATION_LOCALLY_POSITIVE) || (rsReputations->overallReputationLevel(gxsid) == RsReputations::REPUTATION_LOCALLY_NEGATIVE) ); - voteNegativeAct->setEnabled(rsReputations->overallReputationLevel(gxsid) != RsReputations::REPUTATION_LOCALLY_NEGATIVE); + votePositiveAct->setEnabled( + rsReputations->overallReputationLevel(gxsid) != + RsReputationLevel::LOCALLY_POSITIVE ); + voteNeutralAct->setEnabled( + ( rsReputations->overallReputationLevel(gxsid) == + RsReputationLevel::LOCALLY_POSITIVE ) || + ( rsReputations->overallReputationLevel(gxsid) == + RsReputationLevel::LOCALLY_NEGATIVE ) ); + voteNegativeAct->setEnabled( + rsReputations->overallReputationLevel(gxsid) != + RsReputationLevel::LOCALLY_NEGATIVE ); muteAct->setEnabled(true); muteAct->setChecked(isParticipantMuted(gxsid)); } @@ -319,16 +327,15 @@ void ChatLobbyDialog::voteParticipant() QList idList = act->data().value>(); - RsReputations::Opinion op = RsReputations::OPINION_NEUTRAL ; - if (act == votePositiveAct) - op = RsReputations::OPINION_POSITIVE; - if (act == voteNegativeAct) - op = RsReputations::OPINION_NEGATIVE; + RsOpinion op = RsOpinion::NEUTRAL; + if (act == votePositiveAct) op = RsOpinion::POSITIVE; + if (act == voteNegativeAct) op = RsOpinion::NEGATIVE; for (QList::iterator item = idList.begin(); item != idList.end(); ++item) { rsReputations->setOwnOpinion(*item, op); - std::cerr << "Giving opinion to GXS id " << *item << " to " << op << std::endl; + std::cerr << "Giving opinion to GXS id " << *item << " to " + << static_cast(op) << std::endl; } updateParticipantsList(); diff --git a/retroshare-gui/src/gui/gxs/GxsIdDetails.cpp b/retroshare-gui/src/gui/gxs/GxsIdDetails.cpp index 6168090eb..7c65e0d17 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdDetails.cpp +++ b/retroshare-gui/src/gui/gxs/GxsIdDetails.cpp @@ -84,7 +84,8 @@ void ReputationItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem if(icon_index > mMaxLevelToDisplay) return ; - QIcon icon = GxsIdDetails::getReputationIcon(RsReputations::ReputationLevel(icon_index),0xff); + QIcon icon = GxsIdDetails::getReputationIcon( + RsReputationLevel(icon_index), 0xff ); QPixmap pix = icon.pixmap(r.size()); @@ -937,8 +938,9 @@ bool GxsIdDetails::MakeIdDesc(const RsGxsId &id, bool doIcons, QString &str, QLi QString GxsIdDetails::getName(const RsIdentityDetails &details) { - if(details.mReputation.mOverallReputationLevel == RsReputations::REPUTATION_LOCALLY_NEGATIVE) - return tr("[Banned]") ; + if( details.mReputation.mOverallReputationLevel == + RsReputationLevel::LOCALLY_NEGATIVE ) + return tr("[Banned]"); QString name = QString::fromUtf8(details.mNickname.c_str()).left(RSID_MAXIMUM_NICKNAME_SIZE); @@ -956,7 +958,8 @@ QString GxsIdDetails::getComment(const RsIdentityDetails &details) QString comment; QString nickname ; - bool banned = (details.mReputation.mOverallReputationLevel == RsReputations::REPUTATION_LOCALLY_NEGATIVE); + bool banned = ( details.mReputation.mOverallReputationLevel == + RsReputationLevel::LOCALLY_NEGATIVE ); if(details.mNickname.empty()) nickname = tr("[Unknown]") ; @@ -997,19 +1000,27 @@ QString nickname ; return comment; } -QIcon GxsIdDetails::getReputationIcon(RsReputations::ReputationLevel icon_index,uint32_t min_reputation) +QIcon GxsIdDetails::getReputationIcon( + RsReputationLevel icon_index, uint32_t min_reputation ) { - if( icon_index >= min_reputation ) return QIcon(REPUTATION_VOID) ; + if( static_cast(icon_index) >= min_reputation ) + return QIcon(REPUTATION_VOID); switch(icon_index) { - case RsReputations::REPUTATION_LOCALLY_NEGATIVE: return QIcon(REPUTATION_LOCALLY_NEGATIVE_ICON) ; break ; - case RsReputations::REPUTATION_LOCALLY_POSITIVE: return QIcon(REPUTATION_LOCALLY_POSITIVE_ICON) ; break ; - case RsReputations::REPUTATION_REMOTELY_POSITIVE: return QIcon(REPUTATION_REMOTELY_POSITIVE_ICON) ; break ; - case RsReputations::REPUTATION_REMOTELY_NEGATIVE: return QIcon(REPUTATION_REMOTELY_NEGATIVE_ICON) ; break ; - case RsReputations::REPUTATION_NEUTRAL: return QIcon(REPUTATION_NEUTRAL_ICON) ; break ; - default: - std::cerr << "Asked for unidentified icon index " << icon_index << std::endl; + case RsReputationLevel::LOCALLY_NEGATIVE: + return QIcon(REPUTATION_LOCALLY_NEGATIVE_ICON); + case RsReputationLevel::LOCALLY_POSITIVE: + return QIcon(REPUTATION_LOCALLY_POSITIVE_ICON); + case RsReputationLevel::REMOTELY_POSITIVE: + return QIcon(REPUTATION_REMOTELY_POSITIVE_ICON); + case RsReputationLevel::REMOTELY_NEGATIVE: + return QIcon(REPUTATION_REMOTELY_NEGATIVE_ICON); + case RsReputationLevel::NEUTRAL: + return QIcon(REPUTATION_NEUTRAL_ICON); + default: + std::cerr << "Asked for unidentified icon index " + << static_cast(icon_index) << std::endl; return QIcon(); // dont draw anything } } @@ -1018,7 +1029,8 @@ void GxsIdDetails::getIcons(const RsIdentityDetails &details, QList &icon { QPixmap pix ; - if(details.mReputation.mOverallReputationLevel == RsReputations::REPUTATION_LOCALLY_NEGATIVE) + if( details.mReputation.mOverallReputationLevel == + RsReputationLevel::LOCALLY_NEGATIVE ) { icons.clear() ; icons.push_back(QIcon(IMAGE_BANNED)) ; diff --git a/retroshare-gui/src/gui/gxs/GxsIdDetails.h b/retroshare-gui/src/gui/gxs/GxsIdDetails.h index 8c6c8edac..29e876e55 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdDetails.h +++ b/retroshare-gui/src/gui/gxs/GxsIdDetails.h @@ -49,7 +49,8 @@ typedef void (*GxsIdDetailsCallbackFunction)(GxsIdDetailsType type, const RsIden class ReputationItemDelegate: public QStyledItemDelegate { public: - ReputationItemDelegate(RsReputations::ReputationLevel max_level_to_display) : mMaxLevelToDisplay(max_level_to_display) {} + ReputationItemDelegate(RsReputationLevel max_level_to_display) : + mMaxLevelToDisplay(static_cast(max_level_to_display)) {} virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; @@ -96,7 +97,8 @@ public: static QString getNameForType(GxsIdDetailsType type, const RsIdentityDetails &details); static QIcon getLoadingIcon(const RsGxsId &id); - static QIcon getReputationIcon(RsReputations::ReputationLevel icon_index, uint32_t min_reputation); + static QIcon getReputationIcon( + RsReputationLevel icon_index, uint32_t min_reputation ); static void GenerateCombinedPixmap(QPixmap &pixmap, const QList &icons, int iconSize); diff --git a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.cpp b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.cpp index d01135577..bfe8cf052 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.cpp +++ b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.cpp @@ -149,30 +149,34 @@ void GxsIdRSTreeWidgetItem::setAvatar(const RsGxsImage &avatar) QVariant GxsIdRSTreeWidgetItem::data(int column, int role) const { - if (column == idColumn()) - { - if (role == Qt::ToolTipRole) - { - QString t = RSTreeWidgetItem::data(column, role).toString(); - QImage pix; + if (column == idColumn()) + { + if (role == Qt::ToolTipRole) + { + QString t = RSTreeWidgetItem::data(column, role).toString(); + QImage pix; - if(mId.isNull()) - return RSTreeWidgetItem::data(column, role); - else if(rsReputations->overallReputationLevel(mId) == RsReputations::REPUTATION_LOCALLY_NEGATIVE) - pix = QImage(BANNED_IMAGE) ; - else if (mAvatar.mSize == 0 || !pix.loadFromData(mAvatar.mData, mAvatar.mSize, "PNG")) - pix = GxsIdDetails::makeDefaultIcon(mId); + if(mId.isNull()) return RSTreeWidgetItem::data(column, role); + else if( rsReputations->overallReputationLevel(mId) == + RsReputationLevel::LOCALLY_NEGATIVE ) + pix = QImage(BANNED_IMAGE); + else if ( mAvatar.mSize == 0 || + !pix.loadFromData(mAvatar.mData, mAvatar.mSize, "PNG") ) + pix = GxsIdDetails::makeDefaultIcon(mId); - int S = QFontMetricsF(font(column)).height(); + int S = QFontMetricsF(font(column)).height(); - QString embeddedImage; - if (RsHtml::makeEmbeddedImage(pix.scaled(QSize(4*S,4*S), Qt::KeepAspectRatio, Qt::SmoothTransformation), embeddedImage, 8*S * 8*S)) { - t = "
" + embeddedImage + "" + t + "
"; - } + QString embeddedImage; + if ( RsHtml::makeEmbeddedImage( + pix.scaled(QSize(4*S,4*S), Qt::KeepAspectRatio, + Qt::SmoothTransformation ), + embeddedImage, 8*S * 8*S ) ) + t = "
" + embeddedImage + "" + t + + "
"; - return t; - } - } + return t; + } + } - return RSTreeWidgetItem::data(column, role); + return RSTreeWidgetItem::data(column, role); } diff --git a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h index edb8515e4..72e8fad11 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h +++ b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h @@ -64,7 +64,7 @@ private: bool mIdFound; bool mBannedState ; bool mRetryWhenFailed; - RsReputations::ReputationLevel mReputationLevel ; + RsReputationLevel mReputationLevel; uint32_t mIconTypeMask; RsGxsImage mAvatar; }; diff --git a/retroshare-gui/src/gui/gxsforums/GxsForumModel.cpp b/retroshare-gui/src/gui/gxsforums/GxsForumModel.cpp index c13c80a3f..c9fc624c1 100644 --- a/retroshare-gui/src/gui/gxsforums/GxsForumModel.cpp +++ b/retroshare-gui/src/gui/gxsforums/GxsForumModel.cpp @@ -824,19 +824,20 @@ void RsGxsForumModel::convertMsgToPostEntry(const RsGxsForumGroup& mForumGroup,c void RsGxsForumModel::computeReputationLevel(uint32_t forum_sign_flags,ForumModelPostEntry& fentry) { uint32_t idflags =0; - RsReputations::ReputationLevel reputation_level = rsReputations->overallReputationLevel(fentry.mAuthorId,&idflags) ; + RsReputationLevel reputation_level = + rsReputations->overallReputationLevel(fentry.mAuthorId, &idflags); bool redacted = false; - if(reputation_level == RsReputations::REPUTATION_LOCALLY_NEGATIVE) + if(reputation_level == RsReputationLevel::LOCALLY_NEGATIVE) fentry.mPostFlags |= ForumModelPostEntry::FLAG_POST_IS_REDACTED; else fentry.mPostFlags &= ~ForumModelPostEntry::FLAG_POST_IS_REDACTED; // We use a specific item model for forums in order to handle the post pinning. - if(reputation_level == RsReputations::REPUTATION_UNKNOWN) + if(reputation_level == RsReputationLevel::UNKNOWN) fentry.mReputationWarningLevel = 3 ; - else if(reputation_level == RsReputations::REPUTATION_LOCALLY_NEGATIVE) + else if(reputation_level == RsReputationLevel::LOCALLY_NEGATIVE) fentry.mReputationWarningLevel = 2 ; else if(reputation_level < rsGxsForums->minReputationForForwardingMessages(forum_sign_flags,idflags)) fentry.mReputationWarningLevel = 1 ; @@ -1301,7 +1302,7 @@ void RsGxsForumModel::debug_dump() } #endif -void RsGxsForumModel::setAuthorOpinion(const QModelIndex& indx,RsReputations::Opinion op) +void RsGxsForumModel::setAuthorOpinion(const QModelIndex& indx, RsOpinion op) { if(!indx.isValid()) return ; @@ -1312,7 +1313,8 @@ void RsGxsForumModel::setAuthorOpinion(const QModelIndex& indx,RsReputations::Op if(!convertRefPointerToTabEntry(ref,entry) || entry >= mPosts.size()) return ; - std::cerr << "Setting own opinion for author " << mPosts[entry].mAuthorId << " to " << op << std::endl; + std::cerr << "Setting own opinion for author " << mPosts[entry].mAuthorId + << " to " << static_cast(op) << std::endl; RsGxsId author_id = mPosts[entry].mAuthorId; rsReputations->setOwnOpinion(author_id,op) ; diff --git a/retroshare-gui/src/gui/gxsforums/GxsForumModel.h b/retroshare-gui/src/gui/gxsforums/GxsForumModel.h index 85714ffa2..cdbed3b0b 100644 --- a/retroshare-gui/src/gui/gxsforums/GxsForumModel.h +++ b/retroshare-gui/src/gui/gxsforums/GxsForumModel.h @@ -119,7 +119,7 @@ public: void setMsgReadStatus(const QModelIndex &i, bool read_status, bool with_children); void setFilter(int column, const QStringList &strings, uint32_t &count) ; - void setAuthorOpinion(const QModelIndex& indx,RsReputations::Opinion op); + void setAuthorOpinion(const QModelIndex& indx,RsOpinion op); int rowCount(const QModelIndex& parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; diff --git a/retroshare-gui/src/gui/gxsforums/GxsForumThreadWidget.cpp b/retroshare-gui/src/gui/gxsforums/GxsForumThreadWidget.cpp index f388564c1..952d9e818 100644 --- a/retroshare-gui/src/gui/gxsforums/GxsForumThreadWidget.cpp +++ b/retroshare-gui/src/gui/gxsforums/GxsForumThreadWidget.cpp @@ -770,17 +770,17 @@ void GxsForumThreadWidget::threadListCustomPopupMenu(QPoint /*point*/) QAction *flagaspositiveAct = new QAction(QIcon(IMAGE_POSITIVE_OPINION), tr("Give positive opinion"), &contextMnu); flagaspositiveAct->setToolTip(tr("This will block/hide messages from this person, and notify friend nodes.")) ; - flagaspositiveAct->setData(RsReputations::OPINION_POSITIVE) ; + flagaspositiveAct->setData(static_cast(RsOpinion::POSITIVE)); connect(flagaspositiveAct, SIGNAL(triggered()), this, SLOT(flagperson())); QAction *flagasneutralAct = new QAction(QIcon(IMAGE_NEUTRAL_OPINION), tr("Give neutral opinion"), &contextMnu); flagasneutralAct->setToolTip(tr("Doing this, you trust your friends to decide to forward this message or not.")) ; - flagasneutralAct->setData(RsReputations::OPINION_NEUTRAL) ; + flagasneutralAct->setData(static_cast(RsOpinion::NEUTRAL)); connect(flagasneutralAct, SIGNAL(triggered()), this, SLOT(flagperson())); QAction *flagasnegativeAct = new QAction(QIcon(IMAGE_NEGATIVE_OPINION), tr("Give negative opinion"), &contextMnu); flagasnegativeAct->setToolTip(tr("This will block/hide messages from this person, and notify friend nodes.")) ; - flagasnegativeAct->setData(RsReputations::OPINION_NEGATIVE) ; + flagasnegativeAct->setData(static_cast(RsOpinion::NEGATIVE)); connect(flagasnegativeAct, SIGNAL(triggered()), this, SLOT(flagperson())); QAction *newthreadAct = new QAction(QIcon(IMAGE_MESSAGE), tr("Start New Thread"), &contextMnu); @@ -876,19 +876,19 @@ void GxsForumThreadWidget::threadListCustomPopupMenu(QPoint /*point*/) #endif contextMnu.addSeparator(); - RsReputations::Opinion op ; + RsOpinion op; if(!rsIdentity->isOwnId(current_post.mAuthorId) && rsReputations->getOwnOpinion(current_post.mAuthorId,op)) { QMenu *submenu1 = contextMnu.addMenu(tr("Author's reputation")) ; - if(op != RsReputations::OPINION_POSITIVE) + if(op != RsOpinion::POSITIVE) submenu1->addAction(flagaspositiveAct); - if(op != RsReputations::OPINION_NEUTRAL) + if(op != RsOpinion::NEUTRAL) submenu1->addAction(flagasneutralAct); - if(op != RsReputations::OPINION_NEGATIVE) + if(op != RsOpinion::NEGATIVE) submenu1->addAction(flagasnegativeAct); } @@ -1294,8 +1294,10 @@ void GxsForumThreadWidget::insertMessageData(const RsGxsForumMsg &msg) return; } - uint32_t overall_reputation = rsReputations->overallReputationLevel(msg.mMeta.mAuthorId) ; - bool redacted = (overall_reputation == RsReputations::REPUTATION_LOCALLY_NEGATIVE) ; + RsReputationLevel overall_reputation = + rsReputations->overallReputationLevel(msg.mMeta.mAuthorId); + bool redacted = + (overall_reputation == RsReputationLevel::LOCALLY_NEGATIVE); #ifdef TO_REMOVE bool setToReadOnActive = Settings->getForumMsgSetToReadOnActivate(); @@ -1621,9 +1623,12 @@ void GxsForumThreadWidget::flagperson() return; } - RsReputations::Opinion opinion = static_cast(qobject_cast(sender())->data().toUInt()); + RsOpinion opinion = + static_cast( + qobject_cast(sender())->data().toUInt() ); - mThreadModel->setAuthorOpinion(mThreadProxyModel->mapToSource(getCurrentIndex()),opinion); + mThreadModel->setAuthorOpinion( + mThreadProxyModel->mapToSource(getCurrentIndex()), opinion ); } void GxsForumThreadWidget::replytoforummessage() { async_msg_action( &GxsForumThreadWidget::replyForumMessageData ); } diff --git a/retroshare-gui/src/gui/settings/PeoplePage.cpp b/retroshare-gui/src/gui/settings/PeoplePage.cpp index 3124c1b6b..c528db090 100644 --- a/retroshare-gui/src/gui/settings/PeoplePage.cpp +++ b/retroshare-gui/src/gui/settings/PeoplePage.cpp @@ -38,12 +38,12 @@ PeoplePage::PeoplePage(QWidget * parent, Qt::WindowFlags flags) connect(ui.autoAddFriendIdsAsContact_CB,SIGNAL(toggled(bool)),this,SLOT(updateAutoAddFriendIdsAsContact())); } -void PeoplePage::updateAutoPositiveOpinion() { rsReputations->setNodeAutoPositiveOpinionForContacts(ui.autoPositiveOpinion_CB->isChecked()) ; } +void PeoplePage::updateAutoPositiveOpinion() { rsReputations->setAutoPositiveOpinionForContacts(ui.autoPositiveOpinion_CB->isChecked()) ; } void PeoplePage::updateThresholdForRemotelyPositiveReputation() { rsReputations->setThresholdForRemotelyPositiveReputation(ui.thresholdForPositive_SB->value()); } void PeoplePage::updateThresholdForRemotelyNegativeReputation() { rsReputations->setThresholdForRemotelyNegativeReputation(ui.thresholdForNegative_SB->value()); } -void PeoplePage::updateRememberDeletedNodes() { rsReputations->setRememberDeletedNodesThreshold(ui.preventReloadingBannedIdentitiesFor_SB->value()); } +void PeoplePage::updateRememberDeletedNodes() { rsReputations->setRememberBannedIdThreshold(ui.preventReloadingBannedIdentitiesFor_SB->value()); } void PeoplePage::updateDeleteBannedNodesThreshold() { rsIdentity->setDeleteBannedNodesThreshold(ui.deleteBannedIdentitiesAfter_SB->value());} void PeoplePage::updateAutoAddFriendIdsAsContact() { rsIdentity->setAutoAddFriendIdsAsContact(ui.autoAddFriendIdsAsContact_CB->isChecked()) ; } @@ -54,7 +54,7 @@ PeoplePage::~PeoplePage() /** Loads the settings for this page */ void PeoplePage::load() { - bool auto_positive_contacts = rsReputations->nodeAutoPositiveOpinionForContacts() ; + bool auto_positive_contacts = rsReputations->autoPositiveOpinionForContacts() ; uint32_t threshold_for_positive = rsReputations->thresholdForRemotelyPositiveReputation(); uint32_t threshold_for_negative = rsReputations->thresholdForRemotelyNegativeReputation(); bool auto_add_friend_ids_as_contact = rsIdentity->autoAddFriendIdsAsContact(); @@ -64,5 +64,5 @@ void PeoplePage::load() whileBlocking(ui.thresholdForPositive_SB )->setValue(threshold_for_positive); whileBlocking(ui.thresholdForNegative_SB )->setValue(threshold_for_negative); whileBlocking(ui.deleteBannedIdentitiesAfter_SB )->setValue(rsIdentity->deleteBannedNodesThreshold()); - whileBlocking(ui.preventReloadingBannedIdentitiesFor_SB)->setValue(rsReputations->rememberDeletedNodesThreshold()); + whileBlocking(ui.preventReloadingBannedIdentitiesFor_SB)->setValue(rsReputations->rememberBannedIdThreshold()); } From 9e70aa0a98edb189fab2eaf17b658aa4c64e2502 Mon Sep 17 00:00:00 2001 From: Gioacchino Mazzurco Date: Sat, 16 Feb 2019 17:09:35 -0300 Subject: [PATCH 11/81] Fix compile error on OSX --- libretroshare/src/services/p3idservice.cc | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/libretroshare/src/services/p3idservice.cc b/libretroshare/src/services/p3idservice.cc index de9517843..e6f820b89 100644 --- a/libretroshare/src/services/p3idservice.cc +++ b/libretroshare/src/services/p3idservice.cc @@ -212,9 +212,12 @@ bool p3IdService::getIdentitiesInfo( const std::set& ids, std::vector& idsInfo ) { uint32_t token; + RsTokReqOptions opts; opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA; - std::list idsList(ids.begin(), ids.end()); + + std::list idsList; + for (auto&& id : ids) idsList.push_back(RsGxsGroupId(id)); if( !requestGroupInfo(token, opts, idsList) || waitToken(token) != RsTokenService::COMPLETE ) return false; From bdf8d68c341a18aad832cfc8212af1b8849a6e46 Mon Sep 17 00:00:00 2001 From: defnax Date: Mon, 25 Feb 2019 20:23:47 +0100 Subject: [PATCH 12/81] Added more actions to People V2 Thumbed View Added action for send invite Added action for add to contacts Added action for person details view Added menu for circles Added to display votes on Identity widget --- .../src/gui/People/IdentityWidget.cpp | 35 ++- .../src/gui/People/IdentityWidget.h | 2 + .../src/gui/People/IdentityWidget.ui | 249 ++++++++++++------ .../src/gui/People/PeopleDialog.cpp | 59 ++++- retroshare-gui/src/gui/People/PeopleDialog.h | 9 +- 5 files changed, 257 insertions(+), 97 deletions(-) diff --git a/retroshare-gui/src/gui/People/IdentityWidget.cpp b/retroshare-gui/src/gui/People/IdentityWidget.cpp index 77d08c038..15eed8852 100644 --- a/retroshare-gui/src/gui/People/IdentityWidget.cpp +++ b/retroshare-gui/src/gui/People/IdentityWidget.cpp @@ -51,6 +51,11 @@ IdentityWidget::IdentityWidget(QString name/*=QString()*/, QWidget *parent/*=0*/ ui->labelGXSId->setText(_keyId); ui->labelGXSId->setToolTip(_keyId); ui->labelGXSId->setVisible(false); + + ui->labelPositive->setVisible(false); + ui->labelNegative->setVisible(false); + ui->label_PosIcon_2->setVisible(false); + ui->label_NegIcon_2->setVisible(false); ui->pbAdd->setVisible(false); QObject::connect(ui->pbAdd, SIGNAL(clicked()), this, SLOT(pbAdd_clicked())); @@ -80,19 +85,19 @@ void IdentityWidget::updateData(const RsGxsIdGroup &gxs_group_info) _group_info = gxs_group_info; _haveGXSId = true; + RsReputations::ReputationInfo info ; + rsReputations->getReputationInfo(RsGxsId(_group_info.mMeta.mGroupId),_group_info.mPgpId,info) ; + m_myName = QString::fromUtf8(_group_info.mMeta.mGroupName.c_str()); + //ui->labelName->setId(RsGxsId(_group_info.mMeta.mGroupId)); ui->labelName->setText(m_myName); - if (_havePGPDetail) { - ui->labelName->setToolTip(tr("GXS name:").append(" "+m_myName).append("\n") - .append(tr("PGP name:").append(" "+_nickname))); - } else {//if (m_myName != _nickname) - ui->labelName->setToolTip(tr("GXS name:").append(" "+m_myName)); - }//else (m_myName != _nickname) - _gxsId = QString::fromStdString(_group_info.mMeta.mGroupId.toStdString()); + ui->labelGXSId->setId(RsGxsId(_group_info.mMeta.mGroupId)); ui->labelGXSId->setText(_gxsId); - ui->labelGXSId->setToolTip(tr("GXS id:").append(" "+_gxsId)); + + ui->labelPositive->setText(QString::number(info.mFriendsPositiveVotes)); + ui->labelNegative->setText(QString::number(info.mFriendsNegativeVotes)); if (!_havePGPDetail) { QFont font = ui->labelName->font(); @@ -100,8 +105,8 @@ void IdentityWidget::updateData(const RsGxsIdGroup &gxs_group_info) ui->labelName->setFont(font); _keyId=QString::fromStdString(_group_info.mMeta.mGroupId.toStdString()); + ui->labelKeyId->setId(RsGxsId(_group_info.mMeta.mGroupId)); ui->labelKeyId->setText(_keyId); - ui->labelKeyId->setToolTip(tr("GXS id:").append(" "+_keyId)); ui->labelKeyId->setVisible(false); /// (TODO) Get real ident icon @@ -133,10 +138,10 @@ void IdentityWidget::updateData(const RsPeerDetails &pgp_details) if (!_haveGXSId) m_myName = _nickname; ui->labelName->setText(m_myName); if (_haveGXSId) { - ui->labelName->setToolTip(tr("GXS name:").append(" "+m_myName).append("\n") - .append(tr("PGP name:").append(" "+_nickname))); + ui->labelName->setToolTip(tr("GXS name:") + (" "+m_myName) + ("\n") + +(tr("PGP name:")+(" "+_nickname))); } else {//if (m_myName != _nickname) - ui->labelName->setToolTip(tr("PGP name:").append(" "+_nickname)); + ui->labelName->setToolTip(tr("PGP name:")+(" "+_nickname)); }//else (m_myName != _nickname) QFont font = ui->labelName->font(); @@ -145,7 +150,7 @@ void IdentityWidget::updateData(const RsPeerDetails &pgp_details) _keyId = QString::fromStdString(_details.gpg_id.toStdString()); ui->labelKeyId->setText(_keyId); - ui->labelKeyId->setToolTip(tr("PGP id:").append(" "+_keyId)); + ui->labelKeyId->setToolTip(tr("PGP id:")+(" "+_keyId)); if (!_haveGXSId) { QPixmap avatar; @@ -217,6 +222,10 @@ void IdentityWidget::setIsCurrent(bool value) m_isCurrent=value; ui->labelKeyId->setVisible(value); ui->labelGXSId->setVisible(value && (_haveGXSId && _havePGPDetail)); + ui->labelPositive->setVisible(value); + ui->labelNegative->setVisible(value); + ui->label_PosIcon_2->setVisible(value); + ui->label_NegIcon_2->setVisible(value); ui->pbAdd->setVisible(value); } /* diff --git a/retroshare-gui/src/gui/People/IdentityWidget.h b/retroshare-gui/src/gui/People/IdentityWidget.h index a5e7b7771..03f980683 100644 --- a/retroshare-gui/src/gui/People/IdentityWidget.h +++ b/retroshare-gui/src/gui/People/IdentityWidget.h @@ -82,6 +82,8 @@ private: QString _idtype; QString _nickname; QString _gxsId; + QString _postiveVotes; + QString _negativeVotes; Ui::IdentityWidget *ui; }; diff --git a/retroshare-gui/src/gui/People/IdentityWidget.ui b/retroshare-gui/src/gui/People/IdentityWidget.ui index 9a9ed0e90..adf4668d5 100644 --- a/retroshare-gui/src/gui/People/IdentityWidget.ui +++ b/retroshare-gui/src/gui/People/IdentityWidget.ui @@ -6,18 +6,96 @@ 0 0 - 102 - 170 + 101 + 272 - - + + 0 - - 1 + + 0 - + + 0 + + + 0 + + + 0 + + + + + + 0 + 15 + + + + + 100 + 16777215 + + + + Name + + + true + + + Qt::AlignCenter + + + + + + + + 0 + 15 + + + + + 100 + 16777215 + + + + KeyId + + + Qt::AlignCenter + + + + + + + + 0 + 15 + + + + + 100 + 16777215 + + + + GXSId + + + Qt::AlignCenter + + + + @@ -53,76 +131,89 @@ - - - - - 0 - 15 - + + + + 6 - - - 100 - 16777215 - - - - Name - - - true - - - Qt::AlignCenter - - + + + + + 24 + 24 + + + + + + + :/icons/png/thumbs-up.png + + + true + + + + + + + + 16 + + + + Positive votes + + + 0 + + + + + + + Qt::Vertical + + + + + + + + 24 + 24 + + + + + + + :/icons/png/thumbs-down.png + + + true + + + + + + + + 16 + + + + Negative votes + + + 0 + + + + - - - - - 0 - 15 - - - - - 100 - 16777215 - - - - KeyId - - - Qt::AlignCenter - - - - - - - - 0 - 15 - - - - - 100 - 16777215 - - - - GXSId - - - Qt::AlignCenter - - - - + Add @@ -135,12 +226,18 @@ ElidedLabel QLabel -
gui/common/ElidedLabel.h
+
gui/common/ElidedLabel.h
1
+ + GxsIdLabel + QLabel +
gui/gxs/GxsIdLabel.h
+
+ diff --git a/retroshare-gui/src/gui/People/PeopleDialog.cpp b/retroshare-gui/src/gui/People/PeopleDialog.cpp index 5944d5c34..e97ad3c98 100644 --- a/retroshare-gui/src/gui/People/PeopleDialog.cpp +++ b/retroshare-gui/src/gui/People/PeopleDialog.cpp @@ -23,9 +23,12 @@ #include "gui/common/FlowLayout.h" #include "gui/settings/rsharesettings.h" #include "gui/msgs/MessageComposer.h" +#include "gui/RetroShareLink.h" #include "gui/gxs/GxsIdDetails.h" #include "gui/gxs/RsGxsUpdateBroadcastBase.h" #include "gui/Identity/IdDetailsDialog.h" +#include "gui/Identity/IdDialog.h" +#include "gui/MainWindow.h" #include "retroshare/rspeers.h" #include "retroshare/rsidentity.h" @@ -63,6 +66,8 @@ PeopleDialog::PeopleDialog(QWidget *parent) tabWidget->removeTab(1); + //hide circle flow widget not functional yet + pictureFlowWidgetExternal->hide(); //need erase QtCreator Layout first(for Win) delete idExternal->layout(); @@ -423,6 +428,8 @@ void PeopleDialog::iw_AddButtonClickedExt() qobject_cast(QObject::sender()); if (dest) { QMenu contextMnu( this ); + + QMenu *mnu = contextMnu.addMenu(QIcon(":/icons/png/circles.png"),tr("Invite to Circle")) ; std::map::iterator itCurs; for( itCurs =_ext_circles_widgets.begin(); @@ -432,7 +439,7 @@ void PeopleDialog::iw_AddButtonClickedExt() QIcon icon = QIcon(curs->getImage()); QString name = curs->getName(); - QAction *action = contextMnu.addAction(icon, name, this, SLOT(addToCircleExt())); + QAction *action = mnu->addAction(icon, name, this, SLOT(addToCircleExt())); action->setData(QString::fromStdString(curs->groupInfo().mGroupId.toStdString()) + ";" + QString::fromStdString(dest->groupInfo().mMeta.mGroupId.toStdString())); }//for( itCurs =_ext_circles_widgets.begin(); @@ -468,9 +475,17 @@ void PeopleDialog::iw_AddButtonClickedExt() } } - QAction *actionsendmsg = contextMnu.addAction(QIcon(":/images/mail_new.png"), tr("Send message to this person"), this, SLOT(sendMessage())); + QAction *actionsendmsg = contextMnu.addAction(QIcon(":/images/mail_new.png"), tr("Send message"), this, SLOT(sendMessage())); actionsendmsg->setData( QString::fromStdString(dest->groupInfo().mMeta.mGroupId.toStdString())); + QAction *actionsendinvite = contextMnu.addAction(QIcon(":/images/mail_new.png"), tr("Send invite"), this, SLOT(sendInvite())); + actionsendinvite->setData( QString::fromStdString(dest->groupInfo().mMeta.mGroupId.toStdString())); + + contextMnu.addSeparator(); + + QAction *actionaddcontact = contextMnu.addAction(QIcon(":/images/mail_new.png"), tr("Add to Contacts"), this, SLOT(addtoContacts())); + actionaddcontact->setData( QString::fromStdString(dest->groupInfo().mMeta.mGroupId.toStdString())); + contextMnu.addSeparator(); QAction *actionDetails = contextMnu.addAction(QIcon(":/images/info16.png"), tr("Person details"), this, SLOT(personDetails())); @@ -607,6 +622,36 @@ void PeopleDialog::sendMessage() } +void PeopleDialog::sendInvite() +{ + QAction *action = + qobject_cast(QObject::sender()); + if (action) { + QString data = action->data().toString(); + + RsGxsId gxs_id = RsGxsId(data.toStdString());; + + MessageComposer::sendInvite(gxs_id,false); + + } + + +} + +void PeopleDialog::addtoContacts() +{ + QAction *action = + qobject_cast(QObject::sender()); + if (action) { + QString data = action->data().toString(); + + RsGxsId gxs_id = RsGxsId(data.toStdString());; + + rsIdentity->setAsRegularContact(RsGxsId(gxs_id),true); + } + +} + void PeopleDialog::personDetails() { QAction *action = @@ -620,10 +665,14 @@ void PeopleDialog::personDetails() return; } - IdDetailsDialog *dialog = new IdDetailsDialog(RsGxsGroupId(gxs_id)); - dialog->show(); + /* window will destroy itself! */ + IdDialog *idDialog = dynamic_cast(MainWindow::getPage(MainWindow::People)); - /* Dialog will destroy itself */ + if (!idDialog) + return ; + + MainWindow::showWindow(MainWindow::People); + idDialog->navigate(RsGxsId(gxs_id)); } diff --git a/retroshare-gui/src/gui/People/PeopleDialog.h b/retroshare-gui/src/gui/People/PeopleDialog.h index 0a29dec6d..bf8e7b1ea 100644 --- a/retroshare-gui/src/gui/People/PeopleDialog.h +++ b/retroshare-gui/src/gui/People/PeopleDialog.h @@ -31,7 +31,7 @@ #include "ui_PeopleDialog.h" -#define IMAGE_IDENTITY ":/icons/friends_128.png" +#define IMAGE_IDENTITY ":/icons/png/people.png" class PeopleDialog : public RsGxsUpdateBroadcastPage, public Ui::PeopleDialog, public TokenResponse { @@ -84,8 +84,11 @@ private slots: void pf_dropEventOccursInt(QDropEvent *event); void chatIdentity(); - void sendMessage(); - void personDetails(); + void sendMessage(); + void personDetails(); + void sendInvite(); + void addtoContacts(); + private: void reloadAll(); From 16cae622e3c4acc2f3f6d4e22f03d9223b25e7a5 Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 26 Feb 2019 10:46:32 +0100 Subject: [PATCH 13/81] fixed icons in attachment and read columns --- libretroshare/src/retroshare/rsmsgs.h | 6 +- retroshare-gui/src/gui/MessagesDialog.cpp | 201 ++++++------------- retroshare-gui/src/gui/msgs/MessageModel.cpp | 164 +++++++++++++-- retroshare-gui/src/gui/msgs/MessageModel.h | 44 +--- 4 files changed, 223 insertions(+), 192 deletions(-) diff --git a/libretroshare/src/retroshare/rsmsgs.h b/libretroshare/src/retroshare/rsmsgs.h index ad189e03f..4893bb6c6 100644 --- a/libretroshare/src/retroshare/rsmsgs.h +++ b/libretroshare/src/retroshare/rsmsgs.h @@ -93,8 +93,8 @@ const ChatLobbyFlags RS_CHAT_LOBBY_FLAGS_PGP_SIGNED ( 0x00000010 ) ; // requi typedef uint64_t ChatLobbyId ; typedef uint64_t ChatLobbyMsgId ; typedef std::string ChatLobbyNickName ; - -typedef uint64_t MessageId ; +typedef std::string RsMailMessageId; // should be uint32_t !! +typedef uint64_t MessageId ; namespace Rs @@ -237,7 +237,7 @@ struct MsgInfoSummary : RsSerializable MsgInfoSummary() : msgflags(0), count(0), ts(0) {} virtual ~MsgInfoSummary() = default; - std::string msgId; + RsMailMessageId msgId; RsPeerId srcId; uint32_t msgflags; diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 684c08de9..32159c946 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -66,20 +66,14 @@ #define COLUMN_SUBJECT 2 #define COLUMN_UNREAD 3 #define COLUMN_FROM 4 -#define COLUMN_SIGNATURE 5 -#define COLUMN_DATE 6 -#define COLUMN_CONTENT 7 -#define COLUMN_TAGS 8 -#define COLUMN_COUNT 9 +//#define COLUMN_SIGNATURE 5 +#define COLUMN_DATE 5 +#define COLUMN_CONTENT 6 +#define COLUMN_TAGS 7 +#define COLUMN_COUNT 8 #define COLUMN_DATA 0 // column for storing the userdata like msgid and srcid -#define ROLE_SORT Qt::UserRole -#define ROLE_MSGID Qt::UserRole + 1 -#define ROLE_SRCID Qt::UserRole + 2 -#define ROLE_UNREAD Qt::UserRole + 3 -#define ROLE_MSGFLAGS Qt::UserRole + 4 - #define ROLE_QUICKVIEW_TYPE Qt::UserRole #define ROLE_QUICKVIEW_ID Qt::UserRole + 1 #define ROLE_QUICKVIEW_TEXT Qt::UserRole + 2 @@ -195,7 +189,7 @@ MessagesDialog::MessagesDialog(QWidget *parent) mMessageProxyModel->setSortRole(RsMessageModel::SortRole); ui.messageTreeWidget->setModel(mMessageProxyModel); - mMessageModel->updateMessages(); + changeBox(RsMessageModel::BOX_INBOX); mMessageProxyModel->setFilterRole(RsMessageModel::FilterRole); mMessageProxyModel->setFilterRegExp(QRegExp(QString(RsMessageModel::FilterString))) ; @@ -235,13 +229,13 @@ MessagesDialog::MessagesDialog(QWidget *parent) #endif mMessageCompareRole = new RSTreeWidgetItemCompareRole; - mMessageCompareRole->setRole(COLUMN_SUBJECT, ROLE_SORT); - mMessageCompareRole->setRole(COLUMN_UNREAD, ROLE_SORT); - mMessageCompareRole->setRole(COLUMN_FROM, ROLE_SORT); - mMessageCompareRole->setRole(COLUMN_DATE, ROLE_SORT); - mMessageCompareRole->setRole(COLUMN_TAGS, ROLE_SORT); - mMessageCompareRole->setRole(COLUMN_ATTACHEMENTS, ROLE_SORT); - mMessageCompareRole->setRole(COLUMN_STAR, ROLE_SORT); + mMessageCompareRole->setRole(COLUMN_SUBJECT, RsMessageModel::ROLE_SORT); + mMessageCompareRole->setRole(COLUMN_UNREAD, RsMessageModel::ROLE_SORT); + mMessageCompareRole->setRole(COLUMN_FROM, RsMessageModel::ROLE_SORT); + mMessageCompareRole->setRole(COLUMN_DATE, RsMessageModel::ROLE_SORT); + mMessageCompareRole->setRole(COLUMN_TAGS, RsMessageModel::ROLE_SORT); + mMessageCompareRole->setRole(COLUMN_ATTACHEMENTS, RsMessageModel::ROLE_SORT); + mMessageCompareRole->setRole(COLUMN_STAR, RsMessageModel::ROLE_SORT); RSElidedItemDelegate *itemDelegate = new RSElidedItemDelegate(this); itemDelegate->setSpacing(QSize(0, 2)); @@ -256,12 +250,14 @@ MessagesDialog::MessagesDialog(QWidget *parent) Shortcut = new QShortcut(QKeySequence (Qt::SHIFT | Qt::Key_Delete), ui.messageTreeWidget, 0, 0, Qt::WidgetShortcut); connect(Shortcut, SIGNAL(activated()), this, SLOT( removemessage ())); + QFontMetricsF fm(font()); + /* Set initial section sizes */ QHeaderView * msgwheader = ui.messageTreeWidget->header () ; - msgwheader->resizeSection (COLUMN_ATTACHEMENTS, 24); + msgwheader->resizeSection (COLUMN_ATTACHEMENTS, fm.width('0')); msgwheader->resizeSection (COLUMN_SUBJECT, 250); msgwheader->resizeSection (COLUMN_FROM, 140); - msgwheader->resizeSection (COLUMN_SIGNATURE, 24); + //msgwheader->resizeSection (COLUMN_SIGNATURE, 24); msgwheader->resizeSection (COLUMN_DATE, 140); QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_STAR, QHeaderView::Fixed); @@ -306,9 +302,9 @@ MessagesDialog::MessagesDialog(QWidget *parent) QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_ATTACHEMENTS, QHeaderView::Fixed); QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_DATE, QHeaderView::Interactive); QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_UNREAD, QHeaderView::Fixed); - QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_SIGNATURE, QHeaderView::Fixed); + //QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_SIGNATURE, QHeaderView::Fixed); msgwheader->resizeSection (COLUMN_UNREAD, 24); - msgwheader->resizeSection (COLUMN_SIGNATURE, 24); + //msgwheader->resizeSection (COLUMN_SIGNATURE, 24); msgwheader->resizeSection (COLUMN_STAR, 24); QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_STAR, QHeaderView::Fixed); msgwheader->setStretchLastSection(false); @@ -543,7 +539,7 @@ int MessagesDialog::getSelectedMessages(QList& mid) QModelIndexList qmil = ui.messageTreeWidget->selectionModel()->selectedRows(); foreach(const QModelIndex& m, qmil) - mid.push_back(m.sibling(m.row(),COLUMN_DATA).data(ROLE_MSGID).toString()) ; + mid.push_back(m.sibling(m.row(),COLUMN_DATA).data(RsMessageModel::ROLE_MSGID).toString()) ; return mid.size(); } @@ -590,7 +586,7 @@ bool MessagesDialog::isMessageRead(QTreeWidgetItem *item) return true; } - return !item->data(COLUMN_DATA, ROLE_UNREAD).toBool(); + return !item->data(COLUMN_DATA, RsMessageModel::ROLE_UNREAD).toBool(); } bool MessagesDialog::hasMessageStar(QTreeWidgetItem *item) @@ -599,7 +595,7 @@ bool MessagesDialog::hasMessageStar(QTreeWidgetItem *item) return false; } - return item->data(COLUMN_DATA, ROLE_MSGFLAGS).toInt() & RS_MSG_STAR; + return item->data(COLUMN_DATA, RsMessageModel::ROLE_MSGFLAGS).toInt() & RS_MSG_STAR; } void MessagesDialog::messageTreeWidgetCustomPopupMenu(QPoint /*point*/) @@ -609,7 +605,10 @@ void MessagesDialog::messageTreeWidgetCustomPopupMenu(QPoint /*point*/) MessageInfo msgInfo; if (!getCurrentMsg(cid, mid)) + { + std::cerr << "No current message!" << std::endl; return ; + } if(!rsMail->getMessage(mid, msgInfo)) return ; @@ -895,68 +894,6 @@ void MessagesDialog::messagesTagsChanged() static void InitIconAndFont(QTreeWidgetItem *item) { - int msgFlags = item->data(COLUMN_DATA, ROLE_MSGFLAGS).toInt(); - - // show the real "New" state - if (msgFlags & RS_MSG_NEW) { - item->setIcon(COLUMN_SUBJECT, QIcon(":/images/message-state-new.png")); - } else { - if (msgFlags & RS_MSG_USER_REQUEST) { - item->setIcon(COLUMN_SUBJECT, QIcon(":/images/user/user_request16.png")); - } else if (msgFlags & RS_MSG_FRIEND_RECOMMENDATION) { - item->setIcon(COLUMN_SUBJECT, QIcon(":/images/user/friend_suggestion16.png")); - } else if (msgFlags & RS_MSG_PUBLISH_KEY) { - item->setIcon(COLUMN_SUBJECT, QIcon(":/images/share-icon-16.png")); - } else if (msgFlags & RS_MSG_UNREAD_BY_USER) { - if ((msgFlags & (RS_MSG_REPLIED | RS_MSG_FORWARDED)) == RS_MSG_REPLIED) { - item->setIcon(COLUMN_SUBJECT, QIcon(":/images/message-mail-replied.png")); - } else if ((msgFlags & (RS_MSG_REPLIED | RS_MSG_FORWARDED)) == RS_MSG_FORWARDED) { - item->setIcon(COLUMN_SUBJECT, QIcon(":/images/message-mail-forwarded.png")); - } else if ((msgFlags & (RS_MSG_REPLIED | RS_MSG_FORWARDED)) == (RS_MSG_REPLIED | RS_MSG_FORWARDED)) { - item->setIcon(COLUMN_SUBJECT, QIcon(":/images/message-mail-replied-forw.png")); - } else { - item->setIcon(COLUMN_SUBJECT, QIcon(":/images/message-mail.png")); - } - } else { - if ((msgFlags & (RS_MSG_REPLIED | RS_MSG_FORWARDED)) == RS_MSG_REPLIED) { - item->setIcon(COLUMN_SUBJECT, QIcon(":/images/message-mail-replied-read.png")); - } else if ((msgFlags & (RS_MSG_REPLIED | RS_MSG_FORWARDED)) == RS_MSG_FORWARDED) { - item->setIcon(COLUMN_SUBJECT, QIcon(":/images/message-mail-forwarded-read.png")); - } else if ((msgFlags & (RS_MSG_REPLIED | RS_MSG_FORWARDED)) == (RS_MSG_REPLIED | RS_MSG_FORWARDED)) { - item->setIcon(COLUMN_SUBJECT, QIcon(":/images/message-mail-replied-forw-read.png")); - } else { - item->setIcon(COLUMN_SUBJECT, QIcon(":/images/message-mail-read.png")); - } - } - } - - if (msgFlags & RS_MSG_STAR) { - item->setIcon(COLUMN_STAR, QIcon(IMAGE_STAR_ON)); - item->setData(COLUMN_STAR, ROLE_SORT, 1); - } else { - item->setIcon(COLUMN_STAR, QIcon(IMAGE_STAR_OFF)); - item->setData(COLUMN_STAR, ROLE_SORT, 0); - } - - bool isNew = msgFlags & (RS_MSG_NEW | RS_MSG_UNREAD_BY_USER); - - // set icon - if (isNew) { - item->setIcon(COLUMN_UNREAD, QIcon(":/images/message-state-unread.png")); - item->setData(COLUMN_UNREAD, ROLE_SORT, 1); - } else { - item->setIcon(COLUMN_UNREAD, QIcon(":/images/message-state-read.png")); - item->setData(COLUMN_UNREAD, ROLE_SORT, 0); - } - - // set font - for (int i = 0; i < COLUMN_COUNT; ++i) { - QFont qf = item->font(i); - qf.setBold(isNew); - item->setFont(i, qf); - } - - item->setData(COLUMN_DATA, ROLE_UNREAD, isNew); } #ifdef TO_REMOVE @@ -1519,10 +1456,10 @@ void MessagesDialog::setMsgAsReadUnread(const QList &items, bo LockUpdate Lock (this, false); foreach (QTreeWidgetItem *item, items) { - std::string mid = item->data(COLUMN_DATA, ROLE_MSGID).toString().toStdString(); + std::string mid = item->data(COLUMN_DATA, RsMessageModel::ROLE_MSGID).toString().toStdString(); if (rsMail->MessageRead(mid, !read)) { - int msgFlag = item->data(COLUMN_DATA, ROLE_MSGFLAGS).toInt(); + int msgFlag = item->data(COLUMN_DATA, RsMessageModel::ROLE_MSGFLAGS).toInt(); msgFlag &= ~RS_MSG_NEW; if (read) { @@ -1531,7 +1468,7 @@ void MessagesDialog::setMsgAsReadUnread(const QList &items, bo msgFlag |= RS_MSG_UNREAD_BY_USER; } - item->setData(COLUMN_DATA, ROLE_MSGFLAGS, msgFlag); + item->setData(COLUMN_DATA, RsMessageModel::ROLE_MSGFLAGS, msgFlag); InitIconAndFont(item); } @@ -1571,10 +1508,10 @@ void MessagesDialog::setMsgStar(const QList &items, bool star) LockUpdate Lock (this, false); foreach (QTreeWidgetItem *item, items) { - std::string mid = item->data(COLUMN_DATA, ROLE_MSGID).toString().toStdString(); + std::string mid = item->data(COLUMN_DATA, RsMessageModel::ROLE_MSGID).toString().toStdString(); if (rsMail->MessageStar(mid, star)) { - int msgFlag = item->data(COLUMN_DATA, ROLE_MSGFLAGS).toInt(); + int msgFlag = item->data(COLUMN_DATA, RsMessageModel::ROLE_MSGFLAGS).toInt(); msgFlag &= ~RS_MSG_STAR; if (star) { @@ -1583,7 +1520,7 @@ void MessagesDialog::setMsgStar(const QList &items, bool star) msgFlag &= ~RS_MSG_STAR; } - item->setData(COLUMN_DATA, ROLE_MSGFLAGS, msgFlag); + item->setData(COLUMN_DATA, RsMessageModel::ROLE_MSGFLAGS, msgFlag); InitIconAndFont(item); @@ -1606,7 +1543,7 @@ void MessagesDialog::insertMsgTxtAndFiles(QTreeWidgetItem *item, bool bSetToRead updateInterface(); return; } - mid = item->data(COLUMN_DATA, ROLE_MSGID).toString().toStdString(); + mid = item->data(COLUMN_DATA, RsMessageModel::ROLE_MSGID).toString().toStdString(); int nCount = getSelectedMsgCount (NULL, NULL, NULL, NULL); if (nCount == 1) { @@ -1682,8 +1619,8 @@ bool MessagesDialog::getCurrentMsg(std::string &cid, std::string &mid) if(!indx.isValid()) return false ; - cid = indx.sibling(indx.row(),COLUMN_DATA).data(ROLE_SRCID).toString().toStdString(); - mid = indx.sibling(indx.row(),COLUMN_DATA).data(ROLE_MSGID).toString().toStdString(); + cid = indx.sibling(indx.row(),COLUMN_DATA).data(RsMessageModel::ROLE_SRCID).toString().toStdString(); + mid = indx.sibling(indx.row(),COLUMN_DATA).data(RsMessageModel::ROLE_MSGID).toString().toStdString(); return true; } @@ -1720,12 +1657,11 @@ void MessagesDialog::undeletemessage() { LockUpdate Lock (this, true); - QList items; - getSelectedMsgCount (&items, NULL, NULL, NULL); - foreach (QTreeWidgetItem *item, items) { - QString mid = item->data(COLUMN_DATA, ROLE_MSGID).toString(); - rsMail->MessageToTrash(mid.toStdString(), false); - } + QList msgids; + getSelectedMessages(msgids); + + foreach (const QString& s, msgids) + rsMail->MessageToTrash(s.toStdString(), false); // LockUpdate -> insertMessages(); } @@ -1990,14 +1926,11 @@ void MessagesDialog::tagAboutToShow() // activate actions from the first selected row MsgTagInfo tagInfo; - QList items; - getSelectedMsgCount (&items, NULL, NULL, NULL); + QList msgids; + getSelectedMessages(msgids); - if (items.size()) { - std::string msgId = items.front()->data(COLUMN_DATA, ROLE_MSGID).toString().toStdString(); - - rsMail->getMessageTag(msgId, tagInfo); - } + if(!msgids.empty()) + rsMail->getMessageTag(msgids.front().toStdString(), tagInfo); menu->activateActions(tagInfo.tagIds); } @@ -2006,12 +1939,12 @@ void MessagesDialog::tagRemoveAll() { LockUpdate Lock (this, false); - QList items; - getSelectedMsgCount (&items, NULL, NULL, NULL); - foreach (QTreeWidgetItem *item, items) { - std::string msgId = item->data(COLUMN_DATA, ROLE_MSGID).toString().toStdString(); + QList msgids; + getSelectedMessages(msgids); - rsMail->setMessageTag(msgId, 0, false); + foreach(const QString& s, msgids) + { + rsMail->setMessageTag(s.toStdString(), 0, false); Lock.setUpdate(true); } @@ -2026,32 +1959,23 @@ void MessagesDialog::tagSet(int tagId, bool set) LockUpdate Lock (this, false); - QList items; - getSelectedMsgCount (&items, NULL, NULL, NULL); - foreach (QTreeWidgetItem *item, items) { - std::string msgId = item->data(COLUMN_DATA, ROLE_MSGID).toString().toStdString(); + QList msgids; + getSelectedMessages(msgids); - if (rsMail->setMessageTag(msgId, tagId, set)) { + foreach (const QString& s, msgids) + if (rsMail->setMessageTag(s.toStdString(), tagId, set)) Lock.setUpdate(true); - } - } - - // LockUpdate -> insertMessages(); } void MessagesDialog::emptyTrash() { LockUpdate Lock (this, true); - std::list msgList; - rsMail->getMessageSummaries(msgList); + std::list msgs ; + mMessageModel->getMessageSummaries(RsMessageModel::BOX_TRASH,msgs); - std::list::const_iterator it; - for (it = msgList.begin(); it != msgList.end(); ++it) { - if (it->msgflags & RS_MSG_TRASH) { - rsMail->MessageDelete(it->msgId); - } - } + for(auto it(msgs.begin());it!=msgs.end();++it) + rsMail->MessageDelete(it->msgId); // LockUpdate -> insertMessages(); } @@ -2142,13 +2066,16 @@ void MessagesDialog::updateInterface() int tab = ui.tabWidget->currentIndex(); - if (tab == 0) { - count = getSelectedMsgCount(NULL, NULL, NULL, NULL); - } else { + if (tab == 0) + { + QList msgs; + count = getSelectedMessages(msgs); + } + else + { MessageWidget *msg = dynamic_cast(ui.tabWidget->widget(tab)); - if (msg && msg->msgId().empty() == false) { + if (msg && msg->msgId().empty() == false) count = 1; - } } ui.replymessageButton->setEnabled(count == 1); diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index 47430fab3..55fb89e42 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -26,17 +26,20 @@ #include #include +#include "gui/common/TagDefs.h" #include "util/HandleRichText.h" #include "util/DateTime.h" #include "gui/gxs/GxsIdDetails.h" #include "MessageModel.h" #include "retroshare/rsexpr.h" +#include "retroshare/rsmsgs.h" //#define DEBUG_MESSAGE_MODEL -#define IS_MESSAGE_UNREAD(flags) (flags & RS_MSG_UNREAD_BY_USER) +#define IS_MESSAGE_UNREAD(flags) (flags & (RS_MSG_NEW | RS_MSG_UNREAD_BY_USER)) #define IMAGE_STAR_ON ":/images/star-on-16.png" +#define IMAGE_STAR_OFF ":/images/star-off-16.png" std::ostream& operator<<(std::ostream& o, const QModelIndex& i);// defined elsewhere @@ -46,6 +49,7 @@ RsMessageModel::RsMessageModel(QObject *parent) : QAbstractItemModel(parent) { mFilteringEnabled=false; + mCurrentBox = BOX_NONE; } void RsMessageModel::preMods() @@ -174,11 +178,25 @@ QVariant RsMessageModel::headerData(int section, Qt::Orientation orientation, in switch(section) { case COLUMN_THREAD_STAR: return QIcon(IMAGE_STAR_ON); - case COLUMN_THREAD_READ: return QIcon(":/images/message-state-read.png"); + case COLUMN_THREAD_READ: return QIcon(":/images/message-state-header.png"); + case COLUMN_THREAD_ATTACHMENT: return QIcon(":/images/attachment.png"); default: return QVariant(); } + if(role == Qt::ToolTipRole) + switch(section) + { + case COLUMN_THREAD_ATTACHMENT: return tr("Click to sort by attachments"); + case COLUMN_THREAD_SUBJECT: return tr("Click to sort by subject"); + case COLUMN_THREAD_READ: return tr("Click to sort by read"); + case COLUMN_THREAD_AUTHOR: return tr("Click to sort by from"); + case COLUMN_THREAD_DATE: return tr("Click to sort by date"); + case COLUMN_THREAD_TAGS: return tr("Click to sort by tags"); + case COLUMN_THREAD_STAR: return tr("Click to sort by star"); + default: + return QVariant(); + } return QVariant(); } @@ -226,7 +244,8 @@ QVariant RsMessageModel::data(const QModelIndex &index, int role) const if(role == Qt::FontRole) { QFont font ; -// font.setBold( (fmpe.mPostFlags & (ForumModelPostEntry::FLAG_POST_HAS_UNREAD_CHILDREN | ForumModelPostEntry::FLAG_POST_IS_PINNED)) || IS_MSG_UNREAD(fmpe.mMsgStatus)); + font.setBold(fmpe.msgflags & (RS_MSG_NEW | RS_MSG_UNREAD_BY_USER)); + return QVariant(font); } @@ -356,6 +375,14 @@ QVariant RsMessageModel::authorRole(const Rs::Msgs::MsgInfoSummary& fmpe,int col return QVariant(); } +// QVariant RsMessageModel::unreadRole(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const +// { +// if(column == COLUMN_THREAD_UNREAD) +// return QVariant(); +// lconst Rs::Msgs::MsgInfoSummary& fmpe,int column) const +// +// } + QVariant RsMessageModel::sortRole(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const { switch(column) @@ -371,6 +398,8 @@ QVariant RsMessageModel::sortRole(const Rs::Msgs::MsgInfoSummary& fmpe,int colum return QVariant(str); } + case COLUMN_THREAD_STAR: return QVariant((fmpe.msgflags & RS_MSG_STAR)? 1:0); + default: return displayRole(fmpe,column); } @@ -380,21 +409,48 @@ QVariant RsMessageModel::displayRole(const Rs::Msgs::MsgInfoSummary& fmpe,int co { switch(col) { - case COLUMN_THREAD_SUBJECT: return QVariant(QString::fromUtf8(fmpe.title.c_str())); + case COLUMN_THREAD_SUBJECT: return QVariant(QString::fromUtf8(fmpe.title.c_str())); + case COLUMN_THREAD_ATTACHMENT:return QVariant(QString::number(fmpe.count)); - case COLUMN_THREAD_READ:return QVariant(); - case COLUMN_THREAD_DATE:{ - QDateTime qtime; - qtime.setTime_t(fmpe.ts); + case COLUMN_THREAD_READ:return QVariant(); + case COLUMN_THREAD_DATE:{ + QDateTime qtime; + qtime.setTime_t(fmpe.ts); - return QVariant(DateTime::formatDateTime(qtime)); - } + return QVariant(DateTime::formatDateTime(qtime)); + } - case COLUMN_THREAD_AUTHOR: return QVariant(); + case COLUMN_THREAD_TAGS:{ + // Tags + Rs::Msgs::MsgTagInfo tagInfo; + rsMsgs->getMessageTag(fmpe.msgId, tagInfo); - default: - return QVariant("[ TODO ]"); - } + Rs::Msgs::MsgTagType Tags; + rsMsgs->getMessageTagTypes(Tags); + + QString text; + + // build tag names + std::map >::iterator Tag; + for (auto tagit = tagInfo.tagIds.begin(); tagit != tagInfo.tagIds.end(); ++tagit) + { + if (!text.isNull()) + text += ","; + + auto Tag = Tags.types.find(*tagit); + + if (Tag != Tags.types.end()) + text += TagDefs::name(Tag->first, Tag->second.first); + else + std::cerr << "(WW) unknown tag " << (int)Tag->first << " in message " << fmpe.msgId << std::endl; + } + return text; + } + case COLUMN_THREAD_AUTHOR: return QVariant(); + + default: + return QVariant("[ TODO ]"); + } return QVariant("[ERROR]"); @@ -413,10 +469,43 @@ QVariant RsMessageModel::userRole(const Rs::Msgs::MsgInfoSummary& fmpe,int col) QVariant RsMessageModel::decorationRole(const Rs::Msgs::MsgInfoSummary& fmpe,int col) const { + if(col == COLUMN_THREAD_READ) + if(fmpe.msgflags & (RS_MSG_NEW | RS_MSG_UNREAD_BY_USER)) + return QIcon(":/images/message-state-unread.png"); + else + return QIcon(":/images/message-state-read.png"); + + if(col == COLUMN_THREAD_SUBJECT) + { + if(fmpe.msgflags & RS_MSG_NEW ) return QIcon(":/images/message-state-new.png"); + if(fmpe.msgflags & RS_MSG_USER_REQUEST) return QIcon(":/images/user/user_request16.png"); + if(fmpe.msgflags & RS_MSG_FRIEND_RECOMMENDATION) return QIcon(":/images/user/friend_suggestion16.png"); + if(fmpe.msgflags & RS_MSG_PUBLISH_KEY) return QIcon(":/images/share-icon-16.png"); + + if(fmpe.msgflags & RS_MSG_UNREAD_BY_USER) + { + if((fmpe.msgflags & (RS_MSG_REPLIED | RS_MSG_FORWARDED)) == RS_MSG_REPLIED) return QIcon(":/images/message-mail-replied.png"); + if((fmpe.msgflags & (RS_MSG_REPLIED | RS_MSG_FORWARDED)) == RS_MSG_FORWARDED) return QIcon(":/images/message-mail-forwarded.png"); + if((fmpe.msgflags & (RS_MSG_REPLIED | RS_MSG_FORWARDED)) == (RS_MSG_REPLIED | RS_MSG_FORWARDED)) return QIcon(":/images/message-mail-replied-forw.png"); + + return QIcon(":/images/message-mail.png"); + } + if((fmpe.msgflags & (RS_MSG_REPLIED | RS_MSG_FORWARDED)) == RS_MSG_REPLIED) return QIcon(":/images/message-mail-replied-read.png"); + if((fmpe.msgflags & (RS_MSG_REPLIED | RS_MSG_FORWARDED)) == RS_MSG_FORWARDED) return QIcon(":/images/message-mail-forwarded-read.png"); + if((fmpe.msgflags & (RS_MSG_REPLIED | RS_MSG_FORWARDED)) == (RS_MSG_REPLIED | RS_MSG_FORWARDED)) return QIcon(":/images/message-mail-replied-forw-read.png"); + + return QIcon(":/images/message-mail-read.png"); + } + + if(col == COLUMN_THREAD_STAR) + return QIcon((fmpe.msgflags & RS_MSG_STAR) ? (IMAGE_STAR_ON ): (IMAGE_STAR_OFF)); + + bool isNew = fmpe.msgflags & (RS_MSG_NEW | RS_MSG_UNREAD_BY_USER); + if(col == COLUMN_THREAD_READ) - return QVariant(IS_MESSAGE_UNREAD(fmpe.msgflags)); - else - return QVariant(); + return QIcon(isNew ? ":/images/message-state-unread.png": ":/images/message-state-read.png"); + + return QVariant(); } void RsMessageModel::clear() @@ -455,11 +544,48 @@ void RsMessageModel::setMessages(const std::list& msgs emit messagesLoaded(); } +void RsMessageModel::setCurrentBox(BoxName bn) +{ + if(mCurrentBox != bn) + { + mCurrentBox = bn; + updateMessages(); + } +} + +void RsMessageModel::getMessageSummaries(BoxName box,std::list& msgs) +{ + rsMsgs->getMessageSummaries(msgs); + + // filter out messages that are not in the right box. + + for(auto it(msgs.begin());it!=msgs.end();) + { + bool ok = false; + + switch(box) + { + case BOX_INBOX : ok = (it->msgflags & RS_MSG_BOXMASK) == RS_MSG_INBOX ; break ; + case BOX_SENT : ok = (it->msgflags & RS_MSG_BOXMASK) == RS_MSG_SENTBOX; break ; + case BOX_OUTBOX : ok = (it->msgflags & RS_MSG_BOXMASK) == RS_MSG_OUTBOX ; break ; + case BOX_DRAFTS : ok = (it->msgflags & RS_MSG_BOXMASK) == RS_MSG_DRAFTBOX ; break ; + case BOX_TRASH : ok = (it->msgflags & RS_MSG_TRASH) ; break ; + default: + continue; + } + + if(ok) + ++it; + else + it = msgs.erase(it) ; + } +} + void RsMessageModel::updateMessages() { - std::list msgs ; + std::list msgs; - rsMsgs->getMessageSummaries(msgs); + getMessageSummaries(mCurrentBox,msgs); setMessages(msgs); } diff --git a/retroshare-gui/src/gui/msgs/MessageModel.h b/retroshare-gui/src/gui/msgs/MessageModel.h index 438a3aa5f..db777612a 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.h +++ b/retroshare-gui/src/gui/msgs/MessageModel.h @@ -33,34 +33,6 @@ typedef uint32_t ForumModelIndex; -struct ForumModelPostEntry -{ - ForumModelPostEntry() : mPublishTs(0),mMostRecentTsInThread(0),mPostFlags(0),mReputationWarningLevel(0),mMsgStatus(0),prow(0) {} - - enum { // flags for display of posts. To be used in mPostFlags - FLAG_POST_IS_PINNED = 0x0001, - FLAG_POST_IS_MISSING = 0x0002, - FLAG_POST_IS_REDACTED = 0x0004, - FLAG_POST_HAS_UNREAD_CHILDREN = 0x0008, - FLAG_POST_HAS_READ_CHILDREN = 0x0010, - FLAG_POST_PASSES_FILTER = 0x0020, - FLAG_POST_CHILDREN_PASSES_FILTER = 0x0040, - }; - - std::string mTitle ; - RsGxsId mAuthorId ; - RsGxsMessageId mMsgId; - uint32_t mPublishTs; - uint32_t mMostRecentTsInThread; - uint32_t mPostFlags; - int mReputationWarningLevel; - int mMsgStatus; - - std::vector mChildren; - ForumModelIndex mParent; - int prow ; // parent row -}; - // This class is the item model used by Qt to display the information class RsMessageModel : public QAbstractItemModel @@ -71,6 +43,14 @@ public: explicit RsMessageModel(QObject *parent = NULL); ~RsMessageModel(){} + enum Role { + ROLE_SORT = Qt::UserRole, + ROLE_MSGID = Qt::UserRole + 1, + ROLE_SRCID = Qt::UserRole + 2, + ROLE_UNREAD = Qt::UserRole + 3, + ROLE_MSGFLAGS = Qt::UserRole + 4 + }; + enum BoxName { BOX_NONE = 0x00, BOX_INBOX = 0x01, @@ -102,10 +82,11 @@ public: QModelIndex getIndexOfMessage(const std::string &mid) const; static const QString FilterString ; + static void getMessageSummaries(BoxName box,std::list& msgs); // This method will asynchroneously update the data - void setCurrentBox(BoxName bn) {} + void setCurrentBox(BoxName bn) ; void updateMessages(); const RsMessageId& currentMessageId() const; @@ -162,13 +143,9 @@ private: static bool convertMsgIndexToInternalId(uint32_t entry,quintptr& ref); static bool convertInternalIdToMsgIndex(quintptr ref,uint32_t& index); - static void computeReputationLevel(uint32_t forum_sign_flags, ForumModelPostEntry& entry); uint32_t updateFilterStatus(ForumModelIndex i,int column,const QStringList& strings); - static void generateMissingItem(const RsGxsMessageId &msgId,ForumModelPostEntry& entry); - static ForumModelIndex addEntry(std::vector& posts,const ForumModelPostEntry& entry,ForumModelIndex parent); - void setMessages(const std::list& msgs); QColor mTextColorRead ; @@ -177,5 +154,6 @@ private: QColor mTextColorNotSubscribed ; QColor mTextColorMissing ; + BoxName mCurrentBox ; std::vector mMessages; }; From 40832734cc0173e16b860aeb04541a861cc64836 Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 26 Feb 2019 11:29:10 +0100 Subject: [PATCH 14/81] fixed double definitions of roles --- retroshare-gui/src/gui/MessagesDialog.cpp | 42 ++++++++++---------- retroshare-gui/src/gui/msgs/MessageModel.cpp | 4 ++ retroshare-gui/src/gui/msgs/MessageModel.h | 11 ++--- 3 files changed, 28 insertions(+), 29 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 32159c946..4c49b36b7 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -151,7 +151,7 @@ MessagesDialog::MessagesDialog(QWidget *parent) connect(NotifyQt::getInstance(), SIGNAL(messagesChanged()), this, SLOT(insertMessages())); connect(NotifyQt::getInstance(), SIGNAL(messagesTagsChanged()), this, SLOT(messagesTagsChanged())); - connect(ui.messageTreeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(messageTreeWidgetCustomPopupMenu(QPoint))); + connect(ui.messageTreeWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(messageTreeWidgetCustomPopupMenu(const QPoint&))); connect(ui.listWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(folderlistWidgetCustomPopupMenu(QPoint))); connect(ui.messageTreeWidget, SIGNAL(itemClicked(QTreeWidgetItem*,int)) , this, SLOT(clicked(QTreeWidgetItem*,int))); connect(ui.messageTreeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)) , this, SLOT(doubleClicked(QTreeWidgetItem*,int))); @@ -229,13 +229,13 @@ MessagesDialog::MessagesDialog(QWidget *parent) #endif mMessageCompareRole = new RSTreeWidgetItemCompareRole; - mMessageCompareRole->setRole(COLUMN_SUBJECT, RsMessageModel::ROLE_SORT); - mMessageCompareRole->setRole(COLUMN_UNREAD, RsMessageModel::ROLE_SORT); - mMessageCompareRole->setRole(COLUMN_FROM, RsMessageModel::ROLE_SORT); - mMessageCompareRole->setRole(COLUMN_DATE, RsMessageModel::ROLE_SORT); - mMessageCompareRole->setRole(COLUMN_TAGS, RsMessageModel::ROLE_SORT); - mMessageCompareRole->setRole(COLUMN_ATTACHEMENTS, RsMessageModel::ROLE_SORT); - mMessageCompareRole->setRole(COLUMN_STAR, RsMessageModel::ROLE_SORT); + mMessageCompareRole->setRole(COLUMN_SUBJECT, RsMessageModel::SortRole); + mMessageCompareRole->setRole(COLUMN_UNREAD, RsMessageModel::SortRole); + mMessageCompareRole->setRole(COLUMN_FROM, RsMessageModel::SortRole); + mMessageCompareRole->setRole(COLUMN_DATE, RsMessageModel::SortRole); + mMessageCompareRole->setRole(COLUMN_TAGS, RsMessageModel::SortRole); + mMessageCompareRole->setRole(COLUMN_ATTACHEMENTS, RsMessageModel::SortRole); + mMessageCompareRole->setRole(COLUMN_STAR, RsMessageModel::SortRole); RSElidedItemDelegate *itemDelegate = new RSElidedItemDelegate(this); itemDelegate->setSpacing(QSize(0, 2)); @@ -254,7 +254,7 @@ MessagesDialog::MessagesDialog(QWidget *parent) /* Set initial section sizes */ QHeaderView * msgwheader = ui.messageTreeWidget->header () ; - msgwheader->resizeSection (COLUMN_ATTACHEMENTS, fm.width('0')); + msgwheader->resizeSection (COLUMN_ATTACHEMENTS, fm.width('0')*1.2f); msgwheader->resizeSection (COLUMN_SUBJECT, 250); msgwheader->resizeSection (COLUMN_FROM, 140); //msgwheader->resizeSection (COLUMN_SIGNATURE, 24); @@ -539,7 +539,7 @@ int MessagesDialog::getSelectedMessages(QList& mid) QModelIndexList qmil = ui.messageTreeWidget->selectionModel()->selectedRows(); foreach(const QModelIndex& m, qmil) - mid.push_back(m.sibling(m.row(),COLUMN_DATA).data(RsMessageModel::ROLE_MSGID).toString()) ; + mid.push_back(m.sibling(m.row(),COLUMN_DATA).data(RsMessageModel::MsgIdRole).toString()) ; return mid.size(); } @@ -586,7 +586,7 @@ bool MessagesDialog::isMessageRead(QTreeWidgetItem *item) return true; } - return !item->data(COLUMN_DATA, RsMessageModel::ROLE_UNREAD).toBool(); + return !item->data(COLUMN_DATA, RsMessageModel::UnreadRole).toBool(); } bool MessagesDialog::hasMessageStar(QTreeWidgetItem *item) @@ -595,7 +595,7 @@ bool MessagesDialog::hasMessageStar(QTreeWidgetItem *item) return false; } - return item->data(COLUMN_DATA, RsMessageModel::ROLE_MSGFLAGS).toInt() & RS_MSG_STAR; + return item->data(COLUMN_DATA, RsMessageModel::MsgFlagsRole).toInt() & RS_MSG_STAR; } void MessagesDialog::messageTreeWidgetCustomPopupMenu(QPoint /*point*/) @@ -1456,10 +1456,10 @@ void MessagesDialog::setMsgAsReadUnread(const QList &items, bo LockUpdate Lock (this, false); foreach (QTreeWidgetItem *item, items) { - std::string mid = item->data(COLUMN_DATA, RsMessageModel::ROLE_MSGID).toString().toStdString(); + std::string mid = item->data(COLUMN_DATA, RsMessageModel::MsgIdRole).toString().toStdString(); if (rsMail->MessageRead(mid, !read)) { - int msgFlag = item->data(COLUMN_DATA, RsMessageModel::ROLE_MSGFLAGS).toInt(); + int msgFlag = item->data(COLUMN_DATA, RsMessageModel::MsgFlagsRole).toInt(); msgFlag &= ~RS_MSG_NEW; if (read) { @@ -1468,7 +1468,7 @@ void MessagesDialog::setMsgAsReadUnread(const QList &items, bo msgFlag |= RS_MSG_UNREAD_BY_USER; } - item->setData(COLUMN_DATA, RsMessageModel::ROLE_MSGFLAGS, msgFlag); + item->setData(COLUMN_DATA, RsMessageModel::MsgFlagsRole, msgFlag); InitIconAndFont(item); } @@ -1508,10 +1508,10 @@ void MessagesDialog::setMsgStar(const QList &items, bool star) LockUpdate Lock (this, false); foreach (QTreeWidgetItem *item, items) { - std::string mid = item->data(COLUMN_DATA, RsMessageModel::ROLE_MSGID).toString().toStdString(); + std::string mid = item->data(COLUMN_DATA, RsMessageModel::MsgIdRole).toString().toStdString(); if (rsMail->MessageStar(mid, star)) { - int msgFlag = item->data(COLUMN_DATA, RsMessageModel::ROLE_MSGFLAGS).toInt(); + int msgFlag = item->data(COLUMN_DATA, RsMessageModel::MsgFlagsRole).toInt(); msgFlag &= ~RS_MSG_STAR; if (star) { @@ -1520,7 +1520,7 @@ void MessagesDialog::setMsgStar(const QList &items, bool star) msgFlag &= ~RS_MSG_STAR; } - item->setData(COLUMN_DATA, RsMessageModel::ROLE_MSGFLAGS, msgFlag); + item->setData(COLUMN_DATA, RsMessageModel::MsgFlagsRole, msgFlag); InitIconAndFont(item); @@ -1543,7 +1543,7 @@ void MessagesDialog::insertMsgTxtAndFiles(QTreeWidgetItem *item, bool bSetToRead updateInterface(); return; } - mid = item->data(COLUMN_DATA, RsMessageModel::ROLE_MSGID).toString().toStdString(); + mid = item->data(COLUMN_DATA, RsMessageModel::MsgIdRole).toString().toStdString(); int nCount = getSelectedMsgCount (NULL, NULL, NULL, NULL); if (nCount == 1) { @@ -1619,8 +1619,8 @@ bool MessagesDialog::getCurrentMsg(std::string &cid, std::string &mid) if(!indx.isValid()) return false ; - cid = indx.sibling(indx.row(),COLUMN_DATA).data(RsMessageModel::ROLE_SRCID).toString().toStdString(); - mid = indx.sibling(indx.row(),COLUMN_DATA).data(RsMessageModel::ROLE_MSGID).toString().toStdString(); + cid = indx.sibling(indx.row(),COLUMN_DATA).data(RsMessageModel::SrcIdRole).toString().toStdString(); + mid = indx.sibling(indx.row(),COLUMN_DATA).data(RsMessageModel::MsgIdRole).toString().toStdString(); return true; } diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index 55fb89e42..b5c60012d 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -265,6 +265,10 @@ QVariant RsMessageModel::data(const QModelIndex &index, int role) const case FilterRole: return filterRole (fmpe,index.column()) ; case StatusRole: return statusRole (fmpe,index.column()) ; case SortRole: return sortRole (fmpe,index.column()) ; + case MsgFlagsRole: return fmpe.msgflags ; + case UnreadRole: return fmpe.msgflags & (RS_MSG_NEW | RS_MSG_UNREAD_BY_USER); + case MsgIdRole: return QString::fromStdString(fmpe.msgId) ; + case SrcIdRole: return QString::fromStdString(fmpe.srcId.toStdString()) ; default: return QVariant(); } diff --git a/retroshare-gui/src/gui/msgs/MessageModel.h b/retroshare-gui/src/gui/msgs/MessageModel.h index db777612a..479ffd7dd 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.h +++ b/retroshare-gui/src/gui/msgs/MessageModel.h @@ -43,14 +43,6 @@ public: explicit RsMessageModel(QObject *parent = NULL); ~RsMessageModel(){} - enum Role { - ROLE_SORT = Qt::UserRole, - ROLE_MSGID = Qt::UserRole + 1, - ROLE_SRCID = Qt::UserRole + 2, - ROLE_UNREAD = Qt::UserRole + 3, - ROLE_MSGFLAGS = Qt::UserRole + 4 - }; - enum BoxName { BOX_NONE = 0x00, BOX_INBOX = 0x01, @@ -76,6 +68,9 @@ public: StatusRole = Qt::UserRole+2, UnreadRole = Qt::UserRole+3, FilterRole = Qt::UserRole+4, + MsgIdRole = Qt::UserRole+5, + MsgFlagsRole = Qt::UserRole+6, + SrcIdRole = Qt::UserRole+7, }; QModelIndex root() const{ return createIndex(0,0,(void*)NULL) ;} From 875d0a15da66d266116f8c3fca6bf8fffde8adbd Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 26 Feb 2019 14:09:49 +0100 Subject: [PATCH 15/81] fixed display of selected msg --- retroshare-gui/src/gui/MessagesDialog.cpp | 160 ++++++++++------------ retroshare-gui/src/gui/MessagesDialog.h | 6 +- 2 files changed, 77 insertions(+), 89 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 4c49b36b7..e85b0d399 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -153,8 +153,8 @@ MessagesDialog::MessagesDialog(QWidget *parent) connect(NotifyQt::getInstance(), SIGNAL(messagesTagsChanged()), this, SLOT(messagesTagsChanged())); connect(ui.messageTreeWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(messageTreeWidgetCustomPopupMenu(const QPoint&))); connect(ui.listWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(folderlistWidgetCustomPopupMenu(QPoint))); - connect(ui.messageTreeWidget, SIGNAL(itemClicked(QTreeWidgetItem*,int)) , this, SLOT(clicked(QTreeWidgetItem*,int))); - connect(ui.messageTreeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)) , this, SLOT(doubleClicked(QTreeWidgetItem*,int))); + connect(ui.messageTreeWidget, SIGNAL(clicked(const QModelIndex&)) , this, SLOT(clicked(const QModelIndex&))); + connect(ui.messageTreeWidget, SIGNAL(doubleClicked(const QModelIndex&)) , this, SLOT(doubleClicked(const QModelIndex&))); connect(ui.messageTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), this, SLOT(currentItemChanged(QTreeWidgetItem*))); connect(ui.messageTreeWidget->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(currentChanged(const QModelIndex&))); connect(ui.listWidget, SIGNAL(currentRowChanged(int)), this, SLOT(changeBox(int))); @@ -181,8 +181,6 @@ MessagesDialog::MessagesDialog(QWidget *parent) listMode = LIST_NOTHING; - mCurrMsgId = ""; - mMessageModel = new RsMessageModel(this); mMessageProxyModel = new MessageSortFilterProxyModel(ui.messageTreeWidget->header(),this); mMessageProxyModel->setSourceModel(mMessageModel); @@ -229,13 +227,13 @@ MessagesDialog::MessagesDialog(QWidget *parent) #endif mMessageCompareRole = new RSTreeWidgetItemCompareRole; - mMessageCompareRole->setRole(COLUMN_SUBJECT, RsMessageModel::SortRole); - mMessageCompareRole->setRole(COLUMN_UNREAD, RsMessageModel::SortRole); - mMessageCompareRole->setRole(COLUMN_FROM, RsMessageModel::SortRole); - mMessageCompareRole->setRole(COLUMN_DATE, RsMessageModel::SortRole); - mMessageCompareRole->setRole(COLUMN_TAGS, RsMessageModel::SortRole); + mMessageCompareRole->setRole(COLUMN_SUBJECT, RsMessageModel::SortRole); + mMessageCompareRole->setRole(COLUMN_UNREAD, RsMessageModel::SortRole); + mMessageCompareRole->setRole(COLUMN_FROM, RsMessageModel::SortRole); + mMessageCompareRole->setRole(COLUMN_DATE, RsMessageModel::SortRole); + mMessageCompareRole->setRole(COLUMN_TAGS, RsMessageModel::SortRole); mMessageCompareRole->setRole(COLUMN_ATTACHEMENTS, RsMessageModel::SortRole); - mMessageCompareRole->setRole(COLUMN_STAR, RsMessageModel::SortRole); + mMessageCompareRole->setRole(COLUMN_STAR, RsMessageModel::SortRole); RSElidedItemDelegate *itemDelegate = new RSElidedItemDelegate(this); itemDelegate->setSpacing(QSize(0, 2)); @@ -257,7 +255,6 @@ MessagesDialog::MessagesDialog(QWidget *parent) msgwheader->resizeSection (COLUMN_ATTACHEMENTS, fm.width('0')*1.2f); msgwheader->resizeSection (COLUMN_SUBJECT, 250); msgwheader->resizeSection (COLUMN_FROM, 140); - //msgwheader->resizeSection (COLUMN_SIGNATURE, 24); msgwheader->resizeSection (COLUMN_DATE, 140); QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_STAR, QHeaderView::Fixed); @@ -1376,44 +1373,44 @@ void MessagesDialog::currentItemChanged(QTreeWidgetItem *item) } // click in messageTreeWidget -void MessagesDialog::clicked(QTreeWidgetItem *item, int column) +void MessagesDialog::clicked(const QModelIndex& index) { - if (!item) { + if(!index.isValid()) return; - } - switch (column) { - case COLUMN_UNREAD: - { - QList items; - items.append(item); - setMsgAsReadUnread(items, !isMessageRead(item)); - insertMsgTxtAndFiles(item, false); - updateMessageSummaryList(); - return; - } - case COLUMN_STAR: - { - QList items; - items.append(item); - setMsgStar(items, !hasMessageStar(item)); - return; - } - } +// switch (index.column()) +// { +// case COLUMN_UNREAD: +// { +// QList items; +// items.append(item); +// setMsgAsReadUnread(items, !isMessageRead(item)); +// insertMsgTxtAndFiles(item, false); +// updateMessageSummaryList(); +// return; +// } +// case COLUMN_STAR: +// { +// QList items; +// items.append(item); +// setMsgStar(items, !hasMessageStar(item)); +// return; +// } +// } #ifdef TODO timer->stop(); timerIndex = ui.messageTreeWidget->indexOfTopLevelItem(item); #endif // show current message directly - updateCurrentMessage(); + insertMsgTxtAndFiles(index); } // double click in messageTreeWidget -void MessagesDialog::doubleClicked(QTreeWidgetItem *item, int column) +void MessagesDialog::doubleClicked(const QModelIndex& index) { /* activate row */ - clicked (item, column); + clicked(index); std::string cid; std::string mid; @@ -1445,10 +1442,6 @@ void MessagesDialog::doubleClicked(QTreeWidgetItem *item, int column) // show current message directly void MessagesDialog::updateCurrentMessage() { -#ifdef TODO - timer->stop(); - insertMsgTxtAndFiles(ui.messageTreeWidget->topLevelItem(timerIndex)); -#endif } void MessagesDialog::setMsgAsReadUnread(const QList &items, bool read) @@ -1531,70 +1524,65 @@ void MessagesDialog::setMsgStar(const QList &items, bool star) // LockUpdate } -void MessagesDialog::insertMsgTxtAndFiles(QTreeWidgetItem *item, bool bSetToRead) +void MessagesDialog::insertMsgTxtAndFiles(const QModelIndex& index) { /* get its Ids */ std::string cid; std::string mid; - if (item == NULL) { - mCurrMsgId.clear(); - msgWidget->fill(mCurrMsgId); - updateInterface(); - return; - } - mid = item->data(COLUMN_DATA, RsMessageModel::MsgIdRole).toString().toStdString(); + if(!index.isValid()) + { + mCurrMsgId.clear(); + msgWidget->fill(mCurrMsgId); + updateInterface(); + return; + } + mid = index.data(RsMessageModel::MsgIdRole).toString().toStdString(); - int nCount = getSelectedMsgCount (NULL, NULL, NULL, NULL); - if (nCount == 1) { - ui.actionSaveAs->setEnabled(true); - ui.actionPrintPreview->setEnabled(true); - ui.actionPrint->setEnabled(true); - } else { - ui.actionSaveAs->setDisabled(true); - ui.actionPrintPreview->setDisabled(true); - ui.actionPrint->setDisabled(true); - } - - if (mCurrMsgId == mid) { - // message doesn't changed - return; - } +// int nCount = getSelectedMsgCount (NULL, NULL, NULL, NULL); +// +// if (nCount == 1) { +// ui.actionSaveAs->setEnabled(true); +// ui.actionPrintPreview->setEnabled(true); +// ui.actionPrint->setEnabled(true); +// } else { +// ui.actionSaveAs->setDisabled(true); +// ui.actionPrintPreview->setDisabled(true); +// ui.actionPrint->setDisabled(true); +// } /* Save the Data.... for later */ - mCurrMsgId = mid; - MessageInfo msgInfo; if (!rsMail -> getMessage(mid, msgInfo)) { std::cerr << "MessagesDialog::insertMsgTxtAndFiles() Couldn't find Msg" << std::endl; return; } - QList items; - items.append(item); - - bool bSetToReadOnActive = Settings->getMsgSetToReadOnActivate(); - - if (msgInfo.msgflags & RS_MSG_NEW) { - // set always to read or unread - if (bSetToReadOnActive == false || bSetToRead == false) { - // set locally to unread - setMsgAsReadUnread(items, false); - } else { - setMsgAsReadUnread(items, true); - } - updateMessageSummaryList(); - } else { - if ((msgInfo.msgflags & RS_MSG_UNREAD_BY_USER) && bSetToRead && bSetToReadOnActive) { - // set to read - setMsgAsReadUnread(items, true); - updateMessageSummaryList(); - } - } +// QList items; +// items.append(item); +// +// bool bSetToReadOnActive = Settings->getMsgSetToReadOnActivate(); +// +// if (msgInfo.msgflags & RS_MSG_NEW) { +// // set always to read or unread +// if (bSetToReadOnActive == false || bSetToRead == false) { +// // set locally to unread +// setMsgAsReadUnread(items, false); +// } else { +// setMsgAsReadUnread(items, true); +// } +// updateMessageSummaryList(); +// } else { +// if ((msgInfo.msgflags & RS_MSG_UNREAD_BY_USER) && bSetToRead && bSetToReadOnActive) { +// // set to read +// setMsgAsReadUnread(items, true); +// updateMessageSummaryList(); +// } +// } updateInterface(); - msgWidget->fill(mCurrMsgId); + msgWidget->fill(mid); } bool MessagesDialog::getCurrentMsg(std::string &cid, std::string &mid) diff --git a/retroshare-gui/src/gui/MessagesDialog.h b/retroshare-gui/src/gui/MessagesDialog.h index 8b3a96dcd..45b810a4c 100644 --- a/retroshare-gui/src/gui/MessagesDialog.h +++ b/retroshare-gui/src/gui/MessagesDialog.h @@ -77,8 +77,8 @@ private slots: void changeQuickView(int newrow); void updateCurrentMessage(); void currentItemChanged(QTreeWidgetItem *item); - void clicked(QTreeWidgetItem *item, int column); - void doubleClicked(QTreeWidgetItem *item, int column); + void clicked(const QModelIndex&); + void doubleClicked(const QModelIndex&); void newmessage(); void openAsWindow(); @@ -125,7 +125,7 @@ private: void connectActions(); void updateMessageSummaryList(); - void insertMsgTxtAndFiles(QTreeWidgetItem *item = NULL, bool bSetToRead = true); + void insertMsgTxtAndFiles(const QModelIndex& index = QModelIndex()); bool getCurrentMsg(std::string &cid, std::string &mid); void setMsgAsReadUnread(const QList &items, bool read); From 5cbff98e4054a6aa93072a6f3e40f036956f2d6b Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 26 Feb 2019 14:45:48 +0100 Subject: [PATCH 16/81] fixed toggling read/unread and star status --- retroshare-gui/src/gui/MessagesDialog.cpp | 80 ++++++-------------- retroshare-gui/src/gui/MessagesDialog.h | 5 +- retroshare-gui/src/gui/msgs/MessageModel.cpp | 18 ++--- retroshare-gui/src/gui/msgs/MessageModel.h | 5 +- 4 files changed, 39 insertions(+), 69 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index e85b0d399..3c4c6644f 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -577,22 +577,20 @@ int MessagesDialog::getSelectedMsgCount (QList *items, QListdata(COLUMN_DATA, RsMessageModel::UnreadRole).toBool(); + return !index.data(RsMessageModel::UnreadRole).toBool(); } -bool MessagesDialog::hasMessageStar(QTreeWidgetItem *item) +bool MessagesDialog::hasMessageStar(const QModelIndex& index) { - if (!item) { + if (!index.isValid()) return false; - } - return item->data(COLUMN_DATA, RsMessageModel::MsgFlagsRole).toInt() & RS_MSG_STAR; + return index.data(RsMessageModel::MsgFlagsRole).toInt() & RS_MSG_STAR; } void MessagesDialog::messageTreeWidgetCustomPopupMenu(QPoint /*point*/) @@ -1378,25 +1376,21 @@ void MessagesDialog::clicked(const QModelIndex& index) if(!index.isValid()) return; -// switch (index.column()) -// { -// case COLUMN_UNREAD: -// { -// QList items; -// items.append(item); -// setMsgAsReadUnread(items, !isMessageRead(item)); -// insertMsgTxtAndFiles(item, false); -// updateMessageSummaryList(); -// return; -// } -// case COLUMN_STAR: -// { -// QList items; -// items.append(item); -// setMsgStar(items, !hasMessageStar(item)); -// return; -// } -// } + switch (index.column()) + { + case COLUMN_UNREAD: + { + mMessageModel->setMsgReadStatus(index, !isMessageRead(index)); + insertMsgTxtAndFiles(index); + updateMessageSummaryList(); + return; + } + case COLUMN_STAR: + { + mMessageModel->setMsgStar(index, !hasMessageStar(index)); + return; + } + } #ifdef TODO timer->stop(); timerIndex = ui.messageTreeWidget->indexOfTopLevelItem(item); @@ -1490,39 +1484,13 @@ void MessagesDialog::markAsUnread() void MessagesDialog::markWithStar(bool checked) { - QList items; - getSelectedMsgCount (&items, NULL, NULL, NULL); + QModelIndexList lst = ui.messageTreeWidget->selectionModel()->selectedRows(); - setMsgStar(items, checked); + foreach(const QModelIndex& index,lst) + mMessageModel->setMsgStar(index, checked); } -void MessagesDialog::setMsgStar(const QList &items, bool star) -{ - LockUpdate Lock (this, false); - foreach (QTreeWidgetItem *item, items) { - std::string mid = item->data(COLUMN_DATA, RsMessageModel::MsgIdRole).toString().toStdString(); - - if (rsMail->MessageStar(mid, star)) { - int msgFlag = item->data(COLUMN_DATA, RsMessageModel::MsgFlagsRole).toInt(); - msgFlag &= ~RS_MSG_STAR; - - if (star) { - msgFlag |= RS_MSG_STAR; - } else { - msgFlag &= ~RS_MSG_STAR; - } - - item->setData(COLUMN_DATA, RsMessageModel::MsgFlagsRole, msgFlag); - - InitIconAndFont(item); - - Lock.setUpdate(true); - } - } - - // LockUpdate -} void MessagesDialog::insertMsgTxtAndFiles(const QModelIndex& index) { diff --git a/retroshare-gui/src/gui/MessagesDialog.h b/retroshare-gui/src/gui/MessagesDialog.h index 45b810a4c..d178f77c1 100644 --- a/retroshare-gui/src/gui/MessagesDialog.h +++ b/retroshare-gui/src/gui/MessagesDialog.h @@ -129,11 +129,10 @@ private: bool getCurrentMsg(std::string &cid, std::string &mid); void setMsgAsReadUnread(const QList &items, bool read); - void setMsgStar(const QList &items, bool mark); int getSelectedMsgCount (QList *items, QList *itemsRead, QList *itemsUnread, QList *itemsStar); - bool isMessageRead(QTreeWidgetItem *item); - bool hasMessageStar(QTreeWidgetItem *item); + bool isMessageRead(const QModelIndex &index); + bool hasMessageStar(const QModelIndex &index); void processSettings(bool load); diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index b5c60012d..f85503dbc 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -58,7 +58,7 @@ void RsMessageModel::preMods() } void RsMessageModel::postMods() { - emit dataChanged(createIndex(0,0,(void*)NULL), createIndex(0,COLUMN_THREAD_NB_COLUMNS-1,(void*)NULL)); + emit dataChanged(createIndex(0,0,(void*)NULL), createIndex(mMessages.size()-1,COLUMN_THREAD_NB_COLUMNS-1,(void*)NULL)); } // void RsGxsForumModel::setSortMode(SortMode mode) @@ -651,15 +651,14 @@ void RsMessageModel::setMsgReadStatus(const QModelIndex& i,bool read_status) return ; preMods(); + rsMsgs->MessageRead(i.data(MsgIdRole).toString().toStdString(),!read_status); + postMods(); +} - quintptr ref = i.internalId(); - uint32_t index = 0; - - if(!convertInternalIdToMsgIndex(ref,index) || index >= mMessages.size()) - return ; - - rsMsgs->MessageRead(mMessages[index].msgId,!read_status); - +void RsMessageModel::setMsgStar(const QModelIndex& i,bool star) +{ + preMods(); + rsMsgs->MessageStar(i.data(MsgIdRole).toString().toStdString(),star); postMods(); } @@ -685,3 +684,4 @@ void RsMessageModel::debug_dump() const std::cerr << "Id: " << it->msgId << ": from " << it->srcId << ": flags=" << it->msgflags << ": title=\"" << it->title << "\"" << std::endl; } + diff --git a/retroshare-gui/src/gui/msgs/MessageModel.h b/retroshare-gui/src/gui/msgs/MessageModel.h index 479ffd7dd..baf2c45ba 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.h +++ b/retroshare-gui/src/gui/msgs/MessageModel.h @@ -85,7 +85,6 @@ public: void updateMessages(); const RsMessageId& currentMessageId() const; - void setMsgReadStatus(const QModelIndex& i, bool read_status); void setFilter(int column, const QStringList& strings, uint32_t &count) ; int rowCount(const QModelIndex& parent = QModelIndex()) const override; @@ -122,6 +121,10 @@ public: */ void debug_dump() const; + // control over message flags and so on. This is handled by the model because it will allow it to update accordingly + void setMsgReadStatus(const QModelIndex& i, bool read_status); + void setMsgStar(const QModelIndex& index,bool star) ; + signals: void messagesLoaded(); // emitted after the messages have been set. Can be used to updated the UI. From 0570c3fa3864d1e8447bbac68fd608fef6abe236 Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 26 Feb 2019 15:05:00 +0100 Subject: [PATCH 17/81] fixed context menu --- retroshare-gui/src/gui/MessagesDialog.cpp | 106 +++++++++---------- retroshare-gui/src/gui/MessagesDialog.h | 2 +- retroshare-gui/src/gui/msgs/MessageModel.cpp | 6 +- 3 files changed, 56 insertions(+), 58 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 3c4c6644f..211c9faa2 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -541,40 +541,31 @@ int MessagesDialog::getSelectedMessages(QList& mid) return mid.size(); } -int MessagesDialog::getSelectedMsgCount (QList *items, QList *itemsRead, QList *itemsUnread, QList *itemsStar) +int MessagesDialog::getSelectedMsgCount (QList *items, QList *itemsRead, QList *itemsUnread, QList *itemsStar) { -#ifdef TODO + QModelIndexList qmil = ui.messageTreeWidget->selectionModel()->selectedRows(); + if (items) items->clear(); if (itemsRead) itemsRead->clear(); if (itemsUnread) itemsUnread->clear(); if (itemsStar) itemsStar->clear(); - //To check if the selection has more than one row. - QList selectedMessages; - getSelectedMessages(selectedMessages); - - foreach (const QString&, selectedMessages) + foreach(const QModelIndex& m, qmil) { - if (items || itemsRead || itemsUnread || itemsStar) { - if (items) items->append(item); + if (items) + items->append(m); - if (item->data(COLUMN_DATA, ROLE_UNREAD).toBool()) { - if (itemsUnread) itemsUnread->append(item); - } else { - if (itemsRead) itemsRead->append(item); - } + if (m.data(RsMessageModel::UnreadRole).toBool()) + if (itemsUnread) + itemsUnread->append(m); + else if(itemsRead) + itemsRead->append(m); - if (itemsStar) { - if (item->data(COLUMN_DATA, ROLE_MSGFLAGS).toInt() & RS_MSG_STAR) { - itemsStar->append(item); - } - } - } + if (itemsStar && m.data(RsMessageModel::MsgFlagsRole).toInt() & RS_MSG_STAR) + itemsStar->append(m); } - return selectedItems.size(); -#endif - return 0; + return qmil.size(); } bool MessagesDialog::isMessageRead(const QModelIndex& index) @@ -608,9 +599,10 @@ void MessagesDialog::messageTreeWidgetCustomPopupMenu(QPoint /*point*/) if(!rsMail->getMessage(mid, msgInfo)) return ; - QList itemsRead; - QList itemsUnread; - QList itemsStar; + QList itemsRead; + QList itemsUnread; + QList itemsStar; + int nCount = getSelectedMsgCount (NULL, &itemsRead, &itemsUnread, &itemsStar); /** Defines the actions for the context menu */ @@ -1438,47 +1430,51 @@ void MessagesDialog::updateCurrentMessage() { } -void MessagesDialog::setMsgAsReadUnread(const QList &items, bool read) -{ - LockUpdate Lock (this, false); - - foreach (QTreeWidgetItem *item, items) { - std::string mid = item->data(COLUMN_DATA, RsMessageModel::MsgIdRole).toString().toStdString(); - - if (rsMail->MessageRead(mid, !read)) { - int msgFlag = item->data(COLUMN_DATA, RsMessageModel::MsgFlagsRole).toInt(); - msgFlag &= ~RS_MSG_NEW; - - if (read) { - msgFlag &= ~RS_MSG_UNREAD_BY_USER; - } else { - msgFlag |= RS_MSG_UNREAD_BY_USER; - } - - item->setData(COLUMN_DATA, RsMessageModel::MsgFlagsRole, msgFlag); - - InitIconAndFont(item); - } - } - - // LockUpdate -} +// void MessagesDialog::setMsgAsReadUnread(const QList &items, bool read) +// { +// LockUpdate Lock (this, false); +// +// foreach (QTreeWidgetItem *item, items) { +// std::string mid = item->data(COLUMN_DATA, RsMessageModel::MsgIdRole).toString().toStdString(); +// +// if (rsMail->MessageRead(mid, !read)) { +// int msgFlag = item->data(COLUMN_DATA, RsMessageModel::MsgFlagsRole).toInt(); +// msgFlag &= ~RS_MSG_NEW; +// +// if (read) { +// msgFlag &= ~RS_MSG_UNREAD_BY_USER; +// } else { +// msgFlag |= RS_MSG_UNREAD_BY_USER; +// } +// +// item->setData(COLUMN_DATA, RsMessageModel::MsgFlagsRole, msgFlag); +// +// InitIconAndFont(item); +// } +// } +// +// // LockUpdate +// } void MessagesDialog::markAsRead() { - QList itemsUnread; + QList itemsUnread; getSelectedMsgCount (NULL, NULL, &itemsUnread, NULL); - setMsgAsReadUnread (itemsUnread, true); + foreach(const QModelIndex& index,itemsUnread) + mMessageModel->setMsgReadStatus(index,true); + updateMessageSummaryList(); } void MessagesDialog::markAsUnread() { - QList itemsRead; + QList itemsRead; getSelectedMsgCount (NULL, &itemsRead, NULL, NULL); - setMsgAsReadUnread (itemsRead, false); + foreach(const QModelIndex& index,itemsRead) + mMessageModel->setMsgReadStatus(index,false); + updateMessageSummaryList(); } diff --git a/retroshare-gui/src/gui/MessagesDialog.h b/retroshare-gui/src/gui/MessagesDialog.h index d178f77c1..1926c23dc 100644 --- a/retroshare-gui/src/gui/MessagesDialog.h +++ b/retroshare-gui/src/gui/MessagesDialog.h @@ -130,7 +130,7 @@ private: bool getCurrentMsg(std::string &cid, std::string &mid); void setMsgAsReadUnread(const QList &items, bool read); - int getSelectedMsgCount (QList *items, QList *itemsRead, QList *itemsUnread, QList *itemsStar); + int getSelectedMsgCount (QList *items, QList *itemsRead, QList *itemsUnread, QList *itemsStar); bool isMessageRead(const QModelIndex &index); bool hasMessageStar(const QModelIndex &index); diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index f85503dbc..cd32dd05a 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -652,14 +652,16 @@ void RsMessageModel::setMsgReadStatus(const QModelIndex& i,bool read_status) preMods(); rsMsgs->MessageRead(i.data(MsgIdRole).toString().toStdString(),!read_status); - postMods(); + + emit dataChanged(i.sibling(i.row(),0),i.sibling(i.row(),COLUMN_THREAD_NB_COLUMNS-1)); } void RsMessageModel::setMsgStar(const QModelIndex& i,bool star) { preMods(); rsMsgs->MessageStar(i.data(MsgIdRole).toString().toStdString(),star); - postMods(); + + emit dataChanged(i.sibling(i.row(),0),i.sibling(i.row(),COLUMN_THREAD_NB_COLUMNS-1)); } QModelIndex RsMessageModel::getIndexOfMessage(const std::string& mid) const From 26792a7471c0b20d22f74ceaeea83abea65599aa Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 3 Mar 2019 21:49:09 +0100 Subject: [PATCH 18/81] removed some timer calls --- retroshare-gui/src/gui/MessagesDialog.cpp | 86 +++++++---------------- retroshare-gui/src/gui/MessagesDialog.h | 2 - 2 files changed, 26 insertions(+), 62 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 211c9faa2..8c218626d 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -321,15 +321,7 @@ MessagesDialog::MessagesDialog(QWidget *parent) // fill quick view fillQuickView(); - // create timer for navigation - timer = new RsProtectedTimer(this); -#ifdef TODO - timer->setInterval(300); - timer->setSingleShot(true); - connect(timer, SIGNAL(timeout()), this, SLOT(updateCurrentMessage())); -#endif - - ui.messageTreeWidget->installEventFilter(this); + //ui.messageTreeWidget->installEventFilter(this); // remove close button of the the first tab ui.tabWidget->hideCloseButton(0); @@ -351,10 +343,6 @@ MessagesDialog::MessagesDialog(QWidget *parent) MessagesDialog::~MessagesDialog() { - // stop and delete timer - timer->stop(); - delete(timer); - // save settings processSettings(false); } @@ -418,36 +406,35 @@ void MessagesDialog::processSettings(bool load) bool MessagesDialog::eventFilter(QObject *obj, QEvent *event) { -#ifdef TODO - if (obj == ui.messageTreeWidget) { - if (event->type() == QEvent::KeyPress) { - QKeyEvent *keyEvent = static_cast(event); - if (keyEvent && keyEvent->key() == Qt::Key_Space) { - // Space pressed - clicked(ui.messageTreeWidget->currentItem(), COLUMN_UNREAD); - return true; // eat event - } - } - } -#endif + if (obj == ui.messageTreeWidget && event->type() == QEvent::KeyPress) + { + QKeyEvent *keyEvent = static_cast(event); + + if (keyEvent && keyEvent->key() == Qt::Key_Space) + { + // Space pressed + clicked(ui.messageTreeWidget->currentIndex()); + return true; // eat event + } + } + // pass the event on to the parent class return MainPage::eventFilter(obj, event); } -void MessagesDialog::changeEvent(QEvent *e) -{ -#ifdef TODO - QWidget::changeEvent(e); - switch (e->type()) { - case QEvent::StyleChange: - insertMessages(); - break; - default: - // remove compiler warnings - break; - } -#endif -} +// void MessagesDialog::changeEvent(QEvent *e) +// { +// QWidget::changeEvent(e); +// +// switch (e->type()) { +// case QEvent::StyleChange: +// insertMessages(); +// break; +// default: +// // remove compiler warnings +// break; +// } +// } void MessagesDialog::fillQuickView() { @@ -1345,23 +1332,6 @@ void MessagesDialog::insertMessages() } #endif -// current row in messageTreeWidget has changed -void MessagesDialog::currentItemChanged(QTreeWidgetItem *item) -{ -#ifdef TODO - timer->stop(); - - if (item) { - timerIndex = ui.messageTreeWidget->indexOfTopLevelItem(item); - timer->start(); - } else { - timerIndex = -1; - } - - updateInterface(); -#endif -} - // click in messageTreeWidget void MessagesDialog::clicked(const QModelIndex& index) { @@ -1383,10 +1353,6 @@ void MessagesDialog::clicked(const QModelIndex& index) return; } } -#ifdef TODO - timer->stop(); - timerIndex = ui.messageTreeWidget->indexOfTopLevelItem(item); -#endif // show current message directly insertMsgTxtAndFiles(index); diff --git a/retroshare-gui/src/gui/MessagesDialog.h b/retroshare-gui/src/gui/MessagesDialog.h index 1926c23dc..084ba70de 100644 --- a/retroshare-gui/src/gui/MessagesDialog.h +++ b/retroshare-gui/src/gui/MessagesDialog.h @@ -60,7 +60,6 @@ public: protected: bool eventFilter(QObject *obj, QEvent *ev); - void changeEvent(QEvent *e); int getSelectedMessages(QList& mid); public slots: @@ -76,7 +75,6 @@ private slots: void changeBox(int newrow); void changeQuickView(int newrow); void updateCurrentMessage(); - void currentItemChanged(QTreeWidgetItem *item); void clicked(const QModelIndex&); void doubleClicked(const QModelIndex&); From 294d711cc37d339d095d950667b4665f7286083d Mon Sep 17 00:00:00 2001 From: hunbernd Date: Sat, 9 Mar 2019 20:38:33 +0100 Subject: [PATCH 19/81] Fixed restbed compilation on Windows --- libretroshare/src/libretroshare.pro | 36 ++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 22d2d1235..cdfadde1d 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -862,17 +862,31 @@ rs_jsonapi { no_rs_cross_compiling { restbed.target = $$clean_path($${RESTBED_BUILD_PATH}/library/librestbed.a) - restbed.commands = \ - cd $${RS_SRC_PATH};\ - git submodule update --init --recommend-shallow supportlibs/restbed;\ - cd $${RESTBED_SRC_PATH};\ - git submodule update --init --recommend-shallow dependency/asio;\ - git submodule update --init --recommend-shallow dependency/catch;\ - git submodule update --init --recommend-shallow dependency/kashmir;\ - mkdir -p $${RESTBED_BUILD_PATH}; cd $${RESTBED_BUILD_PATH};\ - cmake -DCMAKE_CXX_COMPILER=$$QMAKE_CXX -DBUILD_SSL=OFF \ - -DCMAKE_INSTALL_PREFIX=. -B. -H$$shell_path($${RESTBED_SRC_PATH});\ - make; make install + win32-g++ { + restbed.commands = \ + cd $${RS_SRC_PATH} && \ + git submodule update --init --recommend-shallow supportlibs/restbed && \ + cd $${RESTBED_SRC_PATH} && \ + git submodule update --init --recommend-shallow dependency/asio && \ + git submodule update --init --recommend-shallow dependency/catch && \ + git submodule update --init --recommend-shallow dependency/kashmir && \ + mkdir -p $${RESTBED_BUILD_PATH}; cd $${RESTBED_BUILD_PATH} && \ + cmake -DCMAKE_CXX_COMPILER=$$QMAKE_CXX -G \"MSYS Makefiles\" -DBUILD_SSL=OFF \ + -DCMAKE_INSTALL_PREFIX=. -B. -H$$shell_path($${RESTBED_SRC_PATH}) && \ + make && make install + } else { + restbed.commands = \ + cd $${RS_SRC_PATH};\ + git submodule update --init --recommend-shallow supportlibs/restbed;\ + cd $${RESTBED_SRC_PATH};\ + git submodule update --init --recommend-shallow dependency/asio;\ + git submodule update --init --recommend-shallow dependency/catch;\ + git submodule update --init --recommend-shallow dependency/kashmir;\ + mkdir -p $${RESTBED_BUILD_PATH}; cd $${RESTBED_BUILD_PATH};\ + cmake -DCMAKE_CXX_COMPILER=$$QMAKE_CXX -DBUILD_SSL=OFF \ + -DCMAKE_INSTALL_PREFIX=. -B. -H$$shell_path($${RESTBED_SRC_PATH});\ + make; make install + } QMAKE_EXTRA_TARGETS += restbed libretroshare.depends += restbed PRE_TARGETDEPS *= $${restbed.target} From bbb15fd9601c80eaacfdebe2f6cce61af06008fc Mon Sep 17 00:00:00 2001 From: hunbernd Date: Sat, 9 Mar 2019 20:49:54 +0100 Subject: [PATCH 20/81] Fixed jsonapi generator: - Doxygen failed, because it got Unix like paths on Windows - Josnapi generator created empty output files, because multiple _ in input file names --- jsonapi-generator/src/jsonapi-generator.cpp | 2 +- libretroshare/src/libretroshare.pro | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/jsonapi-generator/src/jsonapi-generator.cpp b/jsonapi-generator/src/jsonapi-generator.cpp index aa20eda01..90d44cbd9 100644 --- a/jsonapi-generator/src/jsonapi-generator.cpp +++ b/jsonapi-generator/src/jsonapi-generator.cpp @@ -140,7 +140,7 @@ int main(int argc, char *argv[]) QString refid(member.attributes().namedItem("refid").nodeValue()); QString methodName(member.firstChildElement("name").toElement().text()); bool requiresAuth = true; - QString defFilePath(doxPrefix + refid.split('_')[0] + ".xml"); + QString defFilePath(doxPrefix + refid.left(refid.lastIndexOf('_')) + ".xml"); qDebug() << "Looking for" << typeName << methodName << "into" << typeFilePath; diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index cdfadde1d..4012f798f 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -900,8 +900,8 @@ rs_jsonapi { jsonwrappersincl.commands = \ mkdir -p $${JSONAPI_GENERATOR_OUT} && \ cp $${DOXIGEN_CONFIG_SRC} $${DOXIGEN_CONFIG_OUT} && \ - echo OUTPUT_DIRECTORY=$$shell_path($${JSONAPI_GENERATOR_OUT}) >> $${DOXIGEN_CONFIG_OUT} && \ - echo INPUT=$$shell_path($${DOXIGEN_INPUT_DIRECTORY}) >> $${DOXIGEN_CONFIG_OUT} && \ + echo OUTPUT_DIRECTORY=$${JSONAPI_GENERATOR_OUT} >> $${DOXIGEN_CONFIG_OUT} && \ + echo INPUT=$${DOXIGEN_INPUT_DIRECTORY} >> $${DOXIGEN_CONFIG_OUT} && \ doxygen $${DOXIGEN_CONFIG_OUT} && \ $${JSONAPI_GENERATOR_EXE} $${JSONAPI_GENERATOR_SRC} $${JSONAPI_GENERATOR_OUT}; QMAKE_EXTRA_TARGETS += jsonwrappersincl From 5df54d76300fc9e8ee29f7199643852d134fc9a7 Mon Sep 17 00:00:00 2001 From: hunbernd Date: Sun, 10 Mar 2019 01:49:47 +0100 Subject: [PATCH 21/81] Converted extra targets into an extra compiler: - Multi core compilation works correctly - The jsonapi header files are regenerated when there are changes in libretroshare interface files --- RetroShare.pro | 4 ++-- libretroshare/src/libretroshare.pro | 23 +++++++++-------------- 2 files changed, 11 insertions(+), 16 deletions(-) diff --git a/RetroShare.pro b/RetroShare.pro index 69f9710e0..c04c62ed2 100644 --- a/RetroShare.pro +++ b/RetroShare.pro @@ -31,7 +31,7 @@ rs_jsonapi:isEmpty(JSONAPI_GENERATOR_EXE) { SUBDIRS += libbitdht libbitdht.file = libbitdht/src/libbitdht.pro -libretroshare.depends = openpgpsdk libbitdht +libretroshare.depends += openpgpsdk libbitdht SUBDIRS += libretroshare libretroshare.file = libretroshare/src/libretroshare.pro @@ -39,7 +39,7 @@ libretroshare.file = libretroshare/src/libretroshare.pro libresapi { SUBDIRS += libresapi libresapi.file = libresapi/src/libresapi.pro - libresapi.depends = libretroshare + libresapi.depends += libretroshare } retroshare_gui { diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 4012f798f..528d15497 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -892,28 +892,23 @@ rs_jsonapi { PRE_TARGETDEPS *= $${restbed.target} } - PRE_TARGETDEPS *= $${JSONAPI_GENERATOR_EXE} INCLUDEPATH *= $${JSONAPI_GENERATOR_OUT} - GENERATED_HEADERS += $${WRAPPERS_INCL_FILE} + apiheaders = $$files($${RS_SRC_PATH}/libretroshare/src/retroshare/*.h) - jsonwrappersincl.target = $${WRAPPERS_INCL_FILE} - jsonwrappersincl.commands = \ + genjsonapi.name = Generating jsonapi headers. + genjsonapi.input = apiheaders + genjsonapi.output = $${WRAPPERS_INCL_FILE} $${WRAPPERS_INCL_FILE} + genjsonapi.clean = $${WRAPPERS_INCL_FILE} $${WRAPPERS_INCL_FILE} + genjsonapi.CONFIG += target_predeps combine no_link + genjsonapi.variable_out = HEADERS + genjsonapi.commands = \ mkdir -p $${JSONAPI_GENERATOR_OUT} && \ cp $${DOXIGEN_CONFIG_SRC} $${DOXIGEN_CONFIG_OUT} && \ echo OUTPUT_DIRECTORY=$${JSONAPI_GENERATOR_OUT} >> $${DOXIGEN_CONFIG_OUT} && \ echo INPUT=$${DOXIGEN_INPUT_DIRECTORY} >> $${DOXIGEN_CONFIG_OUT} && \ doxygen $${DOXIGEN_CONFIG_OUT} && \ $${JSONAPI_GENERATOR_EXE} $${JSONAPI_GENERATOR_SRC} $${JSONAPI_GENERATOR_OUT}; - QMAKE_EXTRA_TARGETS += jsonwrappersincl - libretroshare.depends += jsonwrappersincl - PRE_TARGETDEPS *= $${WRAPPERS_INCL_FILE} - - jsonwrappersreg.target = $${WRAPPERS_REG_FILE} - jsonwrappersreg.commands = touch $${WRAPPERS_REG_FILE} - jsonwrappersreg.depends = jsonwrappersincl - QMAKE_EXTRA_TARGETS += jsonwrappersreg - libretroshare.depends += jsonwrappersreg - PRE_TARGETDEPS *= $${WRAPPERS_REG_FILE} + QMAKE_EXTRA_COMPILERS += genjsonapi # Force recalculation of libretroshare dependencies see https://stackoverflow.com/a/47884045 QMAKE_EXTRA_TARGETS += libretroshare From b5b2c430c5f8c1ac8ab77493dccdbc1319fe7817 Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 12 Mar 2019 14:17:42 +0100 Subject: [PATCH 22/81] fixed QuickView filtering system --- libretroshare/src/retroshare/rsmsgs.h | 2 + libretroshare/src/services/p3msgservice.cc | 14 +- libretroshare/src/services/p3msgservice.h | 3 +- retroshare-gui/src/gui/MessagesDialog.cpp | 143 ++++++------------ retroshare-gui/src/gui/MessagesDialog.h | 13 -- .../src/gui/msgs/MessageComposer.cpp | 3 +- retroshare-gui/src/gui/msgs/MessageModel.cpp | 48 ++++-- retroshare-gui/src/gui/msgs/MessageModel.h | 47 ++++-- 8 files changed, 132 insertions(+), 141 deletions(-) diff --git a/libretroshare/src/retroshare/rsmsgs.h b/libretroshare/src/retroshare/rsmsgs.h index 4893bb6c6..6658a53bc 100644 --- a/libretroshare/src/retroshare/rsmsgs.h +++ b/libretroshare/src/retroshare/rsmsgs.h @@ -241,6 +241,7 @@ struct MsgInfoSummary : RsSerializable RsPeerId srcId; uint32_t msgflags; + std::list msgtags; // that leaves 25 bits for user-defined tags. std::string title; int count; /* file count */ @@ -253,6 +254,7 @@ struct MsgInfoSummary : RsSerializable RS_SERIAL_PROCESS(srcId); RS_SERIAL_PROCESS(msgflags); + RS_SERIAL_PROCESS(msgtags); RS_SERIAL_PROCESS(title); RS_SERIAL_PROCESS(count); diff --git a/libretroshare/src/services/p3msgservice.cc b/libretroshare/src/services/p3msgservice.cc index 3e51558d8..3e2f9902c 100644 --- a/libretroshare/src/services/p3msgservice.cc +++ b/libretroshare/src/services/p3msgservice.cc @@ -1290,6 +1290,12 @@ bool p3MsgService::MessageToDraft(MessageInfo &info, const std::string &msgParen return false; } +bool p3MsgService::getMessageTag(const std::string &msgId, Rs::Msgs::MsgTagInfo& info) +{ + RsStackMutex stack(mMsgMtx); /********** STACK LOCKED MTX ******/ + return locked_getMessageTag(msgId,info); +} + bool p3MsgService::getMessageTagTypes(MsgTagType& tags) { RsStackMutex stack(mMsgMtx); /********** STACK LOCKED MTX ******/ @@ -1413,10 +1419,8 @@ bool p3MsgService::removeMessageTagType(uint32_t tagId) return true; } -bool p3MsgService::getMessageTag(const std::string &msgId, MsgTagInfo& info) +bool p3MsgService::locked_getMessageTag(const std::string &msgId, MsgTagInfo& info) { - RsStackMutex stack(mMsgMtx); /********** STACK LOCKED MTX ******/ - uint32_t mid = atoi(msgId.c_str()); if (mid == 0) { std::cerr << "p3MsgService::MessageGetMsgTag: Unknown msgId " << msgId << std::endl; @@ -1740,6 +1744,10 @@ void p3MsgService::initRsMIS(RsMsgItem *msg, MsgInfoSummary &mis) mis.title = msg->subject; mis.count = msg->attachment.items.size(); mis.ts = msg->sendTime; + + MsgTagInfo taginfo; + locked_getMessageTag(mis.msgId,taginfo); + mis.msgtags = taginfo.tagIds ; } void p3MsgService::initMIRsMsg(RsMsgItem *msg,const MessageInfo& info) diff --git a/libretroshare/src/services/p3msgservice.h b/libretroshare/src/services/p3msgservice.h index 658425c4f..d94df85ba 100644 --- a/libretroshare/src/services/p3msgservice.h +++ b/libretroshare/src/services/p3msgservice.h @@ -77,11 +77,11 @@ public: bool MessageToDraft(Rs::Msgs::MessageInfo &info, const std::string &msgParentId); bool MessageToTrash(const std::string &mid, bool bTrash); + bool getMessageTag(const std::string &msgId, Rs::Msgs::MsgTagInfo& info); bool getMessageTagTypes(Rs::Msgs::MsgTagType& tags); bool setMessageTagType(uint32_t tagId, std::string& text, uint32_t rgb_color); bool removeMessageTagType(uint32_t tagId); - bool getMessageTag(const std::string &msgId, Rs::Msgs::MsgTagInfo& info); /* set == false && tagId == 0 --> remove all */ bool setMessageTag(const std::string &msgId, uint32_t tagId, bool set); @@ -142,6 +142,7 @@ public: private: void sendDistantMsgItem(RsMsgItem *msgitem); + bool locked_getMessageTag(const std::string &msgId, Rs::Msgs::MsgTagInfo& info); /** This contains the ongoing tunnel handling contacts. * The map is indexed by the hash */ diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 8c218626d..5218e49b9 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -92,33 +92,6 @@ #define ROW_TRASHBOX 4 -MessagesDialog::LockUpdate::LockUpdate (MessagesDialog *pDialog, bool bUpdate) -{ -#ifdef TODO - m_pDialog = pDialog; - m_bUpdate = bUpdate; - - ++m_pDialog->lockUpdate; -#endif -} - -MessagesDialog::LockUpdate::~LockUpdate () -{ -#ifdef TODO - if(--m_pDialog->lockUpdate < 0) - m_pDialog->lockUpdate = 0; - - if (m_bUpdate && m_pDialog->lockUpdate == 0) { - m_pDialog->insertMessages(); - } -#endif -} - -void MessagesDialog::LockUpdate::setUpdate(bool bUpdate) -{ - m_bUpdate = bUpdate; -} - class MessageSortFilterProxyModel: public QSortFilterProxyModel { public: @@ -149,24 +122,6 @@ MessagesDialog::MessagesDialog(QWidget *parent) inChange = false; lockUpdate = 0; - connect(NotifyQt::getInstance(), SIGNAL(messagesChanged()), this, SLOT(insertMessages())); - connect(NotifyQt::getInstance(), SIGNAL(messagesTagsChanged()), this, SLOT(messagesTagsChanged())); - connect(ui.messageTreeWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(messageTreeWidgetCustomPopupMenu(const QPoint&))); - connect(ui.listWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(folderlistWidgetCustomPopupMenu(QPoint))); - connect(ui.messageTreeWidget, SIGNAL(clicked(const QModelIndex&)) , this, SLOT(clicked(const QModelIndex&))); - connect(ui.messageTreeWidget, SIGNAL(doubleClicked(const QModelIndex&)) , this, SLOT(doubleClicked(const QModelIndex&))); - connect(ui.messageTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), this, SLOT(currentItemChanged(QTreeWidgetItem*))); - connect(ui.messageTreeWidget->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(currentChanged(const QModelIndex&))); - connect(ui.listWidget, SIGNAL(currentRowChanged(int)), this, SLOT(changeBox(int))); - connect(ui.quickViewWidget, SIGNAL(currentRowChanged(int)), this, SLOT(changeQuickView(int))); - connect(ui.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int))); - connect(ui.tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(tabCloseRequested(int))); - connect(ui.newmessageButton, SIGNAL(clicked()), this, SLOT(newmessage())); - - connect(ui.actionTextBesideIcon, SIGNAL(triggered()), this, SLOT(buttonStyle())); - connect(ui.actionIconOnly, SIGNAL(triggered()), this, SLOT(buttonStyle())); - connect(ui.actionTextUnderIcon, SIGNAL(triggered()), this, SLOT(buttonStyle())); - ui.actionTextBesideIcon->setData(Qt::ToolButtonTextBesideIcon); ui.actionIconOnly->setData(Qt::ToolButtonIconOnly); ui.actionTextUnderIcon->setData(Qt::ToolButtonTextUnderIcon); @@ -339,6 +294,26 @@ MessagesDialog::MessagesDialog(QWidget *parent) ").arg(QString::number(2*S)).arg(QString::number(S)) ; registerHelpButton(ui.helpButton,help_str,"MessagesDialog") ; + + connect(NotifyQt::getInstance(), SIGNAL(messagesChanged()), mMessageModel, SLOT(updateMessages())); + connect(NotifyQt::getInstance(), SIGNAL(messagesTagsChanged()), this, SLOT(messagesTagsChanged())); + connect(ui.messageTreeWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(messageTreeWidgetCustomPopupMenu(const QPoint&))); + connect(ui.listWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(folderlistWidgetCustomPopupMenu(QPoint))); + connect(ui.messageTreeWidget, SIGNAL(clicked(const QModelIndex&)) , this, SLOT(clicked(const QModelIndex&))); + connect(ui.messageTreeWidget, SIGNAL(doubleClicked(const QModelIndex&)) , this, SLOT(doubleClicked(const QModelIndex&))); + connect(ui.messageTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), this, SLOT(currentItemChanged(QTreeWidgetItem*))); + connect(ui.messageTreeWidget->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(currentChanged(const QModelIndex&))); + connect(ui.listWidget, SIGNAL(currentRowChanged(int)), this, SLOT(changeBox(int))); + connect(ui.quickViewWidget, SIGNAL(currentRowChanged(int)), this, SLOT(changeQuickView(int))); + connect(ui.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int))); + connect(ui.tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(tabCloseRequested(int))); + connect(ui.newmessageButton, SIGNAL(clicked()), this, SLOT(newmessage())); + + connect(ui.actionTextBesideIcon, SIGNAL(triggered()), this, SLOT(buttonStyle())); + connect(ui.actionIconOnly, SIGNAL(triggered()), this, SLOT(buttonStyle())); + connect(ui.actionTextUnderIcon, SIGNAL(triggered()), this, SLOT(buttonStyle())); + + } MessagesDialog::~MessagesDialog() @@ -830,40 +805,34 @@ void MessagesDialog::changeBox(int box_row) void MessagesDialog::changeQuickView(int newrow) { -#warning Missing code here! -#ifdef TODO Q_UNUSED(newrow); - if (inChange) { - // already in change method - return; - } - - inChange = true; - - ui.messageTreeWidget->clear(); - ui.listWidget->setCurrentItem(NULL); listMode = LIST_QUICKVIEW; - insertMessages(); - insertMsgTxtAndFiles(ui.messageTreeWidget->currentItem()); + RsMessageModel::QuickViewFilter f = RsMessageModel::QUICK_VIEW_ALL ; - inChange = false; -#endif + if(newrow >= 0) // -1 means that nothing is selected + switch(newrow) + { + case 0x00: f = RsMessageModel::QUICK_VIEW_STARRED ; break; + case 0x01: f = RsMessageModel::QUICK_VIEW_SYSTEM ; break; + case 0x02: f = RsMessageModel::QUICK_VIEW_IMPORTANT; break; + case 0x03: f = RsMessageModel::QUICK_VIEW_WORK ; break; + case 0x04: f = RsMessageModel::QUICK_VIEW_PERSONAL ; break; + case 0x05: f = RsMessageModel::QUICK_VIEW_TODO ; break; + case 0x06: f = RsMessageModel::QUICK_VIEW_LATER ; break; + default: + f = RsMessageModel::QuickViewFilter( (int)RsMessageModel::QUICK_VIEW_USER + newrow - 0x06); + } + mMessageModel->setQuickViewFilter(f); + insertMsgTxtAndFiles(ui.messageTreeWidget->currentIndex()); } void MessagesDialog::messagesTagsChanged() { -#ifdef TODO - if (lockUpdate) { - return; - } - fillQuickView(); - insertMessages(); -#endif -#warning Missing code here! + mMessageModel->updateMessages(); } static void InitIconAndFont(QTreeWidgetItem *item) @@ -1545,8 +1514,6 @@ bool MessagesDialog::getCurrentMsg(std::string &cid, std::string &mid) void MessagesDialog::removemessage() { - LockUpdate Lock (this, true); - QList selectedMessages ; getSelectedMessages(selectedMessages); @@ -1567,21 +1534,15 @@ void MessagesDialog::removemessage() rsMail->MessageToTrash(m.toStdString(), true); } } - - // LockUpdate -> insertMessages(); } void MessagesDialog::undeletemessage() { - LockUpdate Lock (this, true); - QList msgids; getSelectedMessages(msgids); foreach (const QString& s, msgids) rsMail->MessageToTrash(s.toStdString(), false); - - // LockUpdate -> insertMessages(); } void MessagesDialog::setToolbarButtonStyle(Qt::ToolButtonStyle style) @@ -1638,21 +1599,19 @@ void MessagesDialog::updateMessageSummaryList() unsigned int systemCount = 0; /* calculating the new messages */ -// rsMail->getMessageCount (&inboxCount, &newInboxCount, &newOutboxCount, &newDraftCount, &newSentboxCount); std::list msgList; - std::list::const_iterator it; - rsMail->getMessageSummaries(msgList); QMap tagCount; /* calculating the new messages */ - for (it = msgList.begin(); it != msgList.end(); ++it) { + for (auto it = msgList.begin(); it != msgList.end(); ++it) + { /* calcluate tag count */ - MsgTagInfo tagInfo; - rsMail->getMessageTag(it->msgId, tagInfo); - for (std::list::iterator tagId = tagInfo.tagIds.begin(); tagId != tagInfo.tagIds.end(); ++tagId) { + + for (auto tagId = (*it).msgtags.begin(); tagId != (*it).msgtags.end(); ++tagId) + { int nCount = tagCount [*tagId]; ++nCount; tagCount [*tagId] = nCount; @@ -1836,6 +1795,7 @@ void MessagesDialog::updateMessageSummaryList() void MessagesDialog::tagAboutToShow() { +#ifdef TODO TagsMenu *menu = dynamic_cast(ui.tagButton->menu()); if (menu == NULL) { return; @@ -1851,22 +1811,16 @@ void MessagesDialog::tagAboutToShow() rsMail->getMessageTag(msgids.front().toStdString(), tagInfo); menu->activateActions(tagInfo.tagIds); +#endif } void MessagesDialog::tagRemoveAll() { - LockUpdate Lock (this, false); - QList msgids; getSelectedMessages(msgids); foreach(const QString& s, msgids) - { rsMail->setMessageTag(s.toStdString(), 0, false); - Lock.setUpdate(true); - } - - // LockUpdate -> insertMessages(); } void MessagesDialog::tagSet(int tagId, bool set) @@ -1875,27 +1829,20 @@ void MessagesDialog::tagSet(int tagId, bool set) return; } - LockUpdate Lock (this, false); - QList msgids; getSelectedMessages(msgids); foreach (const QString& s, msgids) - if (rsMail->setMessageTag(s.toStdString(), tagId, set)) - Lock.setUpdate(true); + rsMail->setMessageTag(s.toStdString(), tagId, set); } void MessagesDialog::emptyTrash() { - LockUpdate Lock (this, true); - std::list msgs ; mMessageModel->getMessageSummaries(RsMessageModel::BOX_TRASH,msgs); for(auto it(msgs.begin());it!=msgs.end();++it) rsMail->MessageDelete(it->msgId); - - // LockUpdate -> insertMessages(); } void MessagesDialog::tabChanged(int /*tab*/) diff --git a/retroshare-gui/src/gui/MessagesDialog.h b/retroshare-gui/src/gui/MessagesDialog.h index 084ba70de..ba56f0224 100644 --- a/retroshare-gui/src/gui/MessagesDialog.h +++ b/retroshare-gui/src/gui/MessagesDialog.h @@ -105,19 +105,6 @@ private slots: void tabCloseRequested(int tab); private: - class LockUpdate - { - public: - LockUpdate (MessagesDialog *pDialog, bool bUpdate); - ~LockUpdate (); - - void setUpdate(bool bUpdate); - - private: - MessagesDialog *m_pDialog; - bool m_bUpdate; - }; - void updateInterface(); void connectActions(); diff --git a/retroshare-gui/src/gui/msgs/MessageComposer.cpp b/retroshare-gui/src/gui/msgs/MessageComposer.cpp index 7c2db10eb..8f485b410 100644 --- a/retroshare-gui/src/gui/msgs/MessageComposer.cpp +++ b/retroshare-gui/src/gui/msgs/MessageComposer.cpp @@ -976,7 +976,8 @@ MessageComposer *MessageComposer::newMsg(const std::string &msgId /* = ""*/) msgComposer->addEmptyRecipient(); - if (msgId.empty() == false) { + if (!msgId.empty()) + { // fill existing message MessageInfo msgInfo; if (!rsMail->getMessage(msgId, msgInfo)) { diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index cd32dd05a..eccff958b 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -50,6 +50,7 @@ RsMessageModel::RsMessageModel(QObject *parent) { mFilteringEnabled=false; mCurrentBox = BOX_NONE; + mQuickViewFilter = QUICK_VIEW_ALL; } void RsMessageModel::preMods() @@ -295,9 +296,29 @@ QVariant RsMessageModel::statusRole(const Rs::Msgs::MsgInfoSummary& fmpe,int col return QVariant();//fmpe.mMsgStatus); } +bool RsMessageModel::passesFilter(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const +{ + QString s = displayRole(fmpe,mFilterColumn).toString(); + bool passes_strings = true ; + + if(!mFilterStrings.empty()) + for(auto iter(mFilterStrings.begin()); iter != mFilterStrings.end(); ++iter) + passes_strings = passes_strings && s.contains(*iter,Qt::CaseInsensitive); + else + passes_strings = true; + + bool passes_quick_view = + (mQuickViewFilter==QUICK_VIEW_ALL) + || (std::find(fmpe.msgtags.begin(),fmpe.msgtags.end(),mQuickViewFilter) != fmpe.msgtags.end()) + || (mQuickViewFilter==QUICK_VIEW_STARRED && (fmpe.msgflags & RS_MSG_STAR)) + || (mQuickViewFilter==QUICK_VIEW_SYSTEM && (fmpe.msgflags & RS_MSG_SYSTEM)); + + return passes_quick_view && passes_strings; +} + QVariant RsMessageModel::filterRole(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const { - if(!mFilteringEnabled) + if(passesFilter(fmpe,column)) return QVariant(FilterString); return QVariant(QString()); @@ -312,20 +333,12 @@ uint32_t RsMessageModel::updateFilterStatus(ForumModelIndex i,int column,const Q } -void RsMessageModel::setFilter(int column,const QStringList& strings,uint32_t& count) +void RsMessageModel::setFilter(int column,const QStringList& strings) { preMods(); - if(!strings.empty()) - { - count = updateFilterStatus(ForumModelIndex(0),column,strings); - mFilteringEnabled = true; - } - else - { - count=0; - mFilteringEnabled = false; - } + mFilterColumn = column; + mFilterStrings = strings; postMods(); } @@ -557,6 +570,16 @@ void RsMessageModel::setCurrentBox(BoxName bn) } } +void RsMessageModel::setQuickViewFilter(QuickViewFilter fn) +{ + if(fn != mQuickViewFilter) + { + preMods(); + mQuickViewFilter = fn ; + postMods(); + } +} + void RsMessageModel::getMessageSummaries(BoxName box,std::list& msgs) { rsMsgs->getMessageSummaries(msgs); @@ -575,6 +598,7 @@ void RsMessageModel::getMessageSummaries(BoxName box,std::listmsgflags & RS_MSG_BOXMASK) == RS_MSG_DRAFTBOX ; break ; case BOX_TRASH : ok = (it->msgflags & RS_MSG_TRASH) ; break ; default: + ++it; continue; } diff --git a/retroshare-gui/src/gui/msgs/MessageModel.h b/retroshare-gui/src/gui/msgs/MessageModel.h index baf2c45ba..5e7f78d9f 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.h +++ b/retroshare-gui/src/gui/msgs/MessageModel.h @@ -53,17 +53,29 @@ public: }; enum Columns { - COLUMN_THREAD_STAR =0x00, - COLUMN_THREAD_ATTACHMENT =0x01, - COLUMN_THREAD_SUBJECT =0x02, - COLUMN_THREAD_READ =0x03, - COLUMN_THREAD_AUTHOR =0x04, - COLUMN_THREAD_DATE =0x05, - COLUMN_THREAD_TAGS =0x06, - COLUMN_THREAD_MSGID =0x07, - COLUMN_THREAD_NB_COLUMNS =0x08, + COLUMN_THREAD_STAR = 0x00, + COLUMN_THREAD_ATTACHMENT = 0x01, + COLUMN_THREAD_SUBJECT = 0x02, + COLUMN_THREAD_READ = 0x03, + COLUMN_THREAD_AUTHOR = 0x04, + COLUMN_THREAD_DATE = 0x05, + COLUMN_THREAD_TAGS = 0x06, + COLUMN_THREAD_MSGID = 0x07, + COLUMN_THREAD_NB_COLUMNS = 0x08, }; + enum QuickViewFilter { + QUICK_VIEW_ALL = 0x00, + QUICK_VIEW_IMPORTANT = 0x01, // These numbers have been carefuly chosen to match the ones in rsmsgs.h + QUICK_VIEW_WORK = 0x02, + QUICK_VIEW_PERSONAL = 0x03, + QUICK_VIEW_TODO = 0x04, + QUICK_VIEW_LATER = 0x05, + QUICK_VIEW_STARRED = 0x06, + QUICK_VIEW_SYSTEM = 0x07, + QUICK_VIEW_USER = 100 + }; + enum Roles{ SortRole = Qt::UserRole+1, StatusRole = Qt::UserRole+2, UnreadRole = Qt::UserRole+3, @@ -77,15 +89,16 @@ public: QModelIndex getIndexOfMessage(const std::string &mid) const; static const QString FilterString ; - static void getMessageSummaries(BoxName box,std::list& msgs); + static void getMessageSummaries(BoxName box, std::list& msgs); // This method will asynchroneously update the data void setCurrentBox(BoxName bn) ; - void updateMessages(); + void setQuickViewFilter(QuickViewFilter fn) ; + const RsMessageId& currentMessageId() const; - void setFilter(int column, const QStringList& strings, uint32_t &count) ; + void setFilter(int column, const QStringList& strings) ; int rowCount(const QModelIndex& parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; @@ -125,11 +138,14 @@ public: void setMsgReadStatus(const QModelIndex& i, bool read_status); void setMsgStar(const QModelIndex& index,bool star) ; +public slots: + void updateMessages(); + signals: void messagesLoaded(); // emitted after the messages have been set. Can be used to updated the UI. private: - bool mFilteringEnabled; + bool passesFilter(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const; void preMods() ; void postMods() ; @@ -153,5 +169,10 @@ private: QColor mTextColorMissing ; BoxName mCurrentBox ; + QuickViewFilter mQuickViewFilter ; + QStringList mFilterStrings; + int mFilterColumn; + bool mFilteringEnabled; + std::vector mMessages; }; From 59b1d44e5b3065c87d690b35d108b89e17c276d4 Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 12 Mar 2019 14:27:06 +0100 Subject: [PATCH 23/81] resotred string filter system --- retroshare-gui/src/gui/MessagesDialog.cpp | 19 ++++++------------- retroshare-gui/src/gui/msgs/MessageModel.h | 3 +-- 2 files changed, 7 insertions(+), 15 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 5218e49b9..88f20c6c6 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -145,7 +145,7 @@ MessagesDialog::MessagesDialog(QWidget *parent) changeBox(RsMessageModel::BOX_INBOX); mMessageProxyModel->setFilterRole(RsMessageModel::FilterRole); - mMessageProxyModel->setFilterRegExp(QRegExp(QString(RsMessageModel::FilterString))) ; + //mMessageProxyModel->setFilterRegExp(QRegExp(QString(RsMessageModel::FilterString))) ; ui.messageTreeWidget->setSortingEnabled(true); @@ -1564,24 +1564,17 @@ void MessagesDialog::buttonStyle() void MessagesDialog::filterChanged(const QString& text) { -#ifdef TODO - ui.messageTreeWidget->filterItems(ui.filterLineEdit->currentFilter(), text); -#endif + QStringList items = text.split(' ',QString::SkipEmptyParts); + mMessageModel->setFilter(ui.filterLineEdit->currentFilter(),items); } void MessagesDialog::filterColumnChanged(int column) { - if (inProcessSettings) { + if (inProcessSettings) return; - } - if (column == COLUMN_CONTENT) { - // need content ... refill - //insertMessages(); - } -#ifdef TODO - ui.messageTreeWidget->filterItems(column, ui.filterLineEdit->text()); -#endif + QStringList items = ui.filterLineEdit->text().split(' ',QString::SkipEmptyParts); + mMessageModel->setFilter(column,items); // save index Settings->setValueToGroup("MessageDialog", "filterColumn", column); diff --git a/retroshare-gui/src/gui/msgs/MessageModel.h b/retroshare-gui/src/gui/msgs/MessageModel.h index 5e7f78d9f..06b7fecb3 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.h +++ b/retroshare-gui/src/gui/msgs/MessageModel.h @@ -95,11 +95,10 @@ public: void setCurrentBox(BoxName bn) ; void setQuickViewFilter(QuickViewFilter fn) ; + void setFilter(int column, const QStringList& strings) ; const RsMessageId& currentMessageId() const; - void setFilter(int column, const QStringList& strings) ; - int rowCount(const QModelIndex& parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; bool hasChildren(const QModelIndex &parent = QModelIndex()) const override; From c9561c2684d6ddd1142c1434c78f79518dae58ba Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 12 Mar 2019 15:59:54 +0100 Subject: [PATCH 24/81] fixed search filter --- retroshare-gui/src/gui/MessagesDialog.cpp | 77 +++++++------- retroshare-gui/src/gui/msgs/MessageModel.cpp | 103 ++++++++----------- retroshare-gui/src/gui/msgs/MessageModel.h | 14 ++- 3 files changed, 94 insertions(+), 100 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 88f20c6c6..8909abc11 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -823,7 +823,7 @@ void MessagesDialog::changeQuickView(int newrow) case 0x05: f = RsMessageModel::QUICK_VIEW_TODO ; break; case 0x06: f = RsMessageModel::QUICK_VIEW_LATER ; break; default: - f = RsMessageModel::QuickViewFilter( (int)RsMessageModel::QUICK_VIEW_USER + newrow - 0x06); + f = RsMessageModel::QuickViewFilter( (int)RsMessageModel::QUICK_VIEW_USER + newrow - 0x07); } mMessageModel->setQuickViewFilter(f); insertMsgTxtAndFiles(ui.messageTreeWidget->currentIndex()); @@ -1438,18 +1438,6 @@ void MessagesDialog::insertMsgTxtAndFiles(const QModelIndex& index) } mid = index.data(RsMessageModel::MsgIdRole).toString().toStdString(); -// int nCount = getSelectedMsgCount (NULL, NULL, NULL, NULL); -// -// if (nCount == 1) { -// ui.actionSaveAs->setEnabled(true); -// ui.actionPrintPreview->setEnabled(true); -// ui.actionPrint->setEnabled(true); -// } else { -// ui.actionSaveAs->setDisabled(true); -// ui.actionPrintPreview->setDisabled(true); -// ui.actionPrint->setDisabled(true); -// } - /* Save the Data.... for later */ MessageInfo msgInfo; @@ -1458,27 +1446,17 @@ void MessagesDialog::insertMsgTxtAndFiles(const QModelIndex& index) return; } -// QList items; -// items.append(item); -// -// bool bSetToReadOnActive = Settings->getMsgSetToReadOnActivate(); -// -// if (msgInfo.msgflags & RS_MSG_NEW) { -// // set always to read or unread -// if (bSetToReadOnActive == false || bSetToRead == false) { -// // set locally to unread -// setMsgAsReadUnread(items, false); -// } else { -// setMsgAsReadUnread(items, true); -// } -// updateMessageSummaryList(); -// } else { -// if ((msgInfo.msgflags & RS_MSG_UNREAD_BY_USER) && bSetToRead && bSetToReadOnActive) { -// // set to read -// setMsgAsReadUnread(items, true); -// updateMessageSummaryList(); -// } -// } + bool bSetToReadOnActive = Settings->getMsgSetToReadOnActivate(); + + if (msgInfo.msgflags & RS_MSG_NEW) // set always to read or unread + { + if (!bSetToReadOnActive) // set locally to unread + mMessageModel->setMsgReadStatus(index, false); + else + mMessageModel->setMsgReadStatus(index, true); + } + else if ((msgInfo.msgflags & RS_MSG_UNREAD_BY_USER) && bSetToReadOnActive) // set to read + mMessageModel->setMsgReadStatus(index, true); updateInterface(); msgWidget->fill(mid); @@ -1565,7 +1543,21 @@ void MessagesDialog::buttonStyle() void MessagesDialog::filterChanged(const QString& text) { QStringList items = text.split(' ',QString::SkipEmptyParts); - mMessageModel->setFilter(ui.filterLineEdit->currentFilter(),items); + + RsMessageModel::FilterType f = RsMessageModel::FILTER_TYPE_NONE; + + switch(ui.filterLineEdit->currentFilter()) + { + case COLUMN_SUBJECT: f = RsMessageModel::FILTER_TYPE_SUBJECT ; break; + case COLUMN_FROM: f = RsMessageModel::FILTER_TYPE_FROM ; break; + case COLUMN_DATE: f = RsMessageModel::FILTER_TYPE_DATE ; break; + case COLUMN_CONTENT: f = RsMessageModel::FILTER_TYPE_CONTENT ; break; + case COLUMN_TAGS: f = RsMessageModel::FILTER_TYPE_TAGS ; break; + case COLUMN_ATTACHEMENTS: f = RsMessageModel::FILTER_TYPE_ATTACHMENTS ; break; + default:break; + } + + mMessageModel->setFilter(f,items); } void MessagesDialog::filterColumnChanged(int column) @@ -1573,8 +1565,21 @@ void MessagesDialog::filterColumnChanged(int column) if (inProcessSettings) return; + RsMessageModel::FilterType f = RsMessageModel::FILTER_TYPE_NONE; + + switch(column) + { + case COLUMN_SUBJECT: f = RsMessageModel::FILTER_TYPE_SUBJECT ; break; + case COLUMN_FROM: f = RsMessageModel::FILTER_TYPE_FROM ; break; + case COLUMN_DATE: f = RsMessageModel::FILTER_TYPE_DATE ; break; + case COLUMN_CONTENT: f = RsMessageModel::FILTER_TYPE_CONTENT ; break; + case COLUMN_TAGS: f = RsMessageModel::FILTER_TYPE_TAGS ; break; + case COLUMN_ATTACHEMENTS: f = RsMessageModel::FILTER_TYPE_ATTACHMENTS ; break; + default:break; + } + QStringList items = ui.filterLineEdit->text().split(' ',QString::SkipEmptyParts); - mMessageModel->setFilter(column,items); + mMessageModel->setFilter(f,items); // save index Settings->setValueToGroup("MessageDialog", "filterColumn", column); diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index eccff958b..5e6fb3e41 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -51,6 +51,7 @@ RsMessageModel::RsMessageModel(QObject *parent) mFilteringEnabled=false; mCurrentBox = BOX_NONE; mQuickViewFilter = QUICK_VIEW_ALL; + mFilterType = FILTER_TYPE_NONE; } void RsMessageModel::preMods() @@ -277,13 +278,13 @@ QVariant RsMessageModel::data(const QModelIndex &index, int role) const QVariant RsMessageModel::textColorRole(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const { -// if( (fmpe.msgflags & ForumModelPostEntry::FLAG_POST_IS_MISSING)) -// return QVariant(mTextColorMissing); -// -// if(IS_MSG_UNREAD(fmpe.mMsgStatus) || (fmpe.mPostFlags & ForumModelPostEntry::FLAG_POST_IS_PINNED)) -// return QVariant(mTextColorUnread); -// else -// return QVariant(mTextColorRead); + Rs::Msgs::MsgTagType tags; + rsMsgs->getMessageTagTypes(tags); + + for(auto it(fmpe.msgtags.begin());it!=fmpe.msgtags.end();++it) + for(auto it2(tags.types.begin());it2!=tags.types.end();++it2) + if(it2->first == *it) + return QColor(it2->second.second); return QVariant(); } @@ -298,14 +299,42 @@ QVariant RsMessageModel::statusRole(const Rs::Msgs::MsgInfoSummary& fmpe,int col bool RsMessageModel::passesFilter(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const { - QString s = displayRole(fmpe,mFilterColumn).toString(); + QString s ; bool passes_strings = true ; if(!mFilterStrings.empty()) + { + switch(mFilterType) + { + case FILTER_TYPE_SUBJECT: s = displayRole(fmpe,COLUMN_THREAD_SUBJECT).toString(); + break; + + case FILTER_TYPE_FROM: + case FILTER_TYPE_DATE: s = displayRole(fmpe,COLUMN_THREAD_DATE).toString(); + break; + case FILTER_TYPE_CONTENT: { + Rs::Msgs::MessageInfo minfo; + rsMsgs->getMessage(fmpe.msgId,minfo); + s = QTextDocument(QString::fromUtf8(minfo.msg.c_str())).toPlainText(); + } + break; + case FILTER_TYPE_TAGS: s = displayRole(fmpe,COLUMN_THREAD_TAGS).toString(); + break; + + case FILTER_TYPE_ATTACHMENTS: + { + Rs::Msgs::MessageInfo minfo; + rsMsgs->getMessage(fmpe.msgId,minfo); + + for(auto it(minfo.files.begin());it!=minfo.files.end();++it) + s += QString::fromUtf8((*it).fname.c_str())+" "; + } + }; + } + + if(!s.isNull()) for(auto iter(mFilterStrings.begin()); iter != mFilterStrings.end(); ++iter) passes_strings = passes_strings && s.contains(*iter,Qt::CaseInsensitive); - else - passes_strings = true; bool passes_quick_view = (mQuickViewFilter==QUICK_VIEW_ALL) @@ -333,11 +362,11 @@ uint32_t RsMessageModel::updateFilterStatus(ForumModelIndex i,int column,const Q } -void RsMessageModel::setFilter(int column,const QStringList& strings) +void RsMessageModel::setFilter(FilterType filter_type, const QStringList& strings) { preMods(); - mFilterColumn = column; + mFilterType = filter_type; mFilterStrings = strings; postMods(); @@ -617,56 +646,6 @@ void RsMessageModel::updateMessages() setMessages(msgs); } -// RsThread::async([this, group_id]() -// { -// // 1 - get message data from p3GxsForums -// -// std::list forumIds; -// std::vector msg_metas; -// std::vector groups; -// -// forumIds.push_back(group_id); -// -// if(!rsGxsForums->getForumsInfo(forumIds,groups)) -// { -// std::cerr << __PRETTY_FUNCTION__ << " failed to retrieve forum group info for forum " << group_id << std::endl; -// return; -// } -// -// if(!rsGxsForums->getForumMsgMetaData(group_id,msg_metas)) -// { -// std::cerr << __PRETTY_FUNCTION__ << " failed to retrieve forum message info for forum " << group_id << std::endl; -// return; -// } -// -// // 2 - sort the messages into a proper hierarchy -// -// auto post_versions = new std::map > >() ; -// std::vector *vect = new std::vector(); -// RsGxsForumGroup group = groups[0]; -// -// computeMessagesHierarchy(group,msg_metas,*vect,*post_versions); -// -// // 3 - update the model in the UI thread. -// -// RsQThreadUtils::postToObject( [group,vect,post_versions,this]() -// { -// /* Here it goes any code you want to be executed on the Qt Gui -// * thread, for example to update the data model with new information -// * after a blocking call to RetroShare API complete, note that -// * Qt::QueuedConnection is important! -// */ -// -// setPosts(group,*vect,*post_versions) ; -// -// delete vect; -// delete post_versions; -// -// -// }, this ); -// -// }); - static bool decreasing_time_comp(const std::pair& e1,const std::pair& e2) { return e2.first < e1.first ; } void RsMessageModel::setMsgReadStatus(const QModelIndex& i,bool read_status) diff --git a/retroshare-gui/src/gui/msgs/MessageModel.h b/retroshare-gui/src/gui/msgs/MessageModel.h index 06b7fecb3..c6167a073 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.h +++ b/retroshare-gui/src/gui/msgs/MessageModel.h @@ -76,6 +76,16 @@ public: QUICK_VIEW_USER = 100 }; + enum FilterType { + FILTER_TYPE_NONE = 0x00, + FILTER_TYPE_SUBJECT = 0x01, // These numbers have been carefuly chosen to match the ones in rsmsgs.h + FILTER_TYPE_FROM = 0x02, + FILTER_TYPE_DATE = 0x03, + FILTER_TYPE_CONTENT = 0x04, + FILTER_TYPE_TAGS = 0x05, + FILTER_TYPE_ATTACHMENTS = 0x06, + }; + enum Roles{ SortRole = Qt::UserRole+1, StatusRole = Qt::UserRole+2, UnreadRole = Qt::UserRole+3, @@ -95,9 +105,9 @@ public: void setCurrentBox(BoxName bn) ; void setQuickViewFilter(QuickViewFilter fn) ; - void setFilter(int column, const QStringList& strings) ; const RsMessageId& currentMessageId() const; + void setFilter(FilterType filter_type, const QStringList& strings) ; int rowCount(const QModelIndex& parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override; @@ -170,7 +180,7 @@ private: BoxName mCurrentBox ; QuickViewFilter mQuickViewFilter ; QStringList mFilterStrings; - int mFilterColumn; + FilterType mFilterType; bool mFilteringEnabled; std::vector mMessages; From a67a35624df6c01872d325b61a17eba24ca69b3d Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 12 Mar 2019 16:40:35 +0100 Subject: [PATCH 25/81] fixed re-loading of icons in author item delegate --- .../src/gui/gxs/GxsIdTreeWidgetItem.h | 56 ++++++++++++++++++- 1 file changed, 53 insertions(+), 3 deletions(-) diff --git a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h index c8b83dbe0..771233aa6 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h +++ b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h @@ -22,8 +22,10 @@ #define _GXS_ID_TREEWIDGETITEM_H #include +#include #include #include +#include #include "gui/common/RSTreeWidgetItem.h" #include "gui/gxs/GxsIdDetails.h" @@ -75,8 +77,14 @@ private: class GxsIdTreeItemDelegate: public QStyledItemDelegate { + Q_OBJECT + public: - GxsIdTreeItemDelegate() {} + GxsIdTreeItemDelegate() + { + mLoading = false; + mReloadPeriod = 0; + } QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override { @@ -98,7 +106,10 @@ public: QIcon icon ; if(!GxsIdDetails::MakeIdDesc(id, true, str, icons, comment,GxsIdDetails::ICON_TYPE_AVATAR)) + { icon = GxsIdDetails::getLoadingIcon(id); + launchAsyncLoading(); + } else icon = *icons.begin(); @@ -135,8 +146,28 @@ public: QIcon icon ; - if(!GxsIdDetails::MakeIdDesc(id, true, str, icons, comment,GxsIdDetails::ICON_TYPE_AVATAR)) - icon = GxsIdDetails::getLoadingIcon(id); + if(id.isNull()) + { + str = tr("[Retroshare]"); + icon = QIcon(); + } + if(rsPeers->isFriend(RsPeerId(id))) // horrible trick because some widgets still use locations as IDs (e.g. messages) + { + str = QString::fromUtf8(rsPeers->getPeerName(RsPeerId(id)).c_str()) ; + } + else if(!GxsIdDetails::MakeIdDesc(id, true, str, icons, comment,GxsIdDetails::ICON_TYPE_AVATAR)) + { + if(mReloadPeriod > 3) + { + str = tr("[Unknown]"); + icon = QIcon(); + } + else + { + icon = GxsIdDetails::getLoadingIcon(id); + launchAsyncLoading(); + } + } else icon = *icons.begin(); @@ -147,6 +178,25 @@ public: painter->drawPixmap(r.topLeft() + p, pix); painter->drawText(r.topLeft() + QPoint(r.height()+ f/2.0 + f/2.0,f*1.0), str); } + + void launchAsyncLoading() const + { + if(mLoading) + return; + + mLoading = true; + ++mReloadPeriod; + std::cerr << "Re-loading" << std::endl; + + QTimer::singleShot(1000,this,SLOT(reload())); + } + +private slots: + void reload() { mLoading=false; emit commitData(NULL) ; } + +private: + mutable bool mLoading; + mutable int mReloadPeriod; }; From 14d29a4490cfb4f4f2b425b7e3cac8d1d90f96db Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 12 Mar 2019 16:59:45 +0100 Subject: [PATCH 26/81] fixed small bug in box initialization --- retroshare-gui/src/gui/MessagesDialog.cpp | 7 +------ retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h | 6 ------ retroshare-gui/src/gui/msgs/MessageModel.cpp | 11 +---------- retroshare-gui/src/gui/msgs/MessageModel.h | 1 - 4 files changed, 2 insertions(+), 23 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 8909abc11..1ed9b89c7 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -142,7 +142,7 @@ MessagesDialog::MessagesDialog(QWidget *parent) mMessageProxyModel->setSortRole(RsMessageModel::SortRole); ui.messageTreeWidget->setModel(mMessageProxyModel); - changeBox(RsMessageModel::BOX_INBOX); + changeBox(0); // set to inbox mMessageProxyModel->setFilterRole(RsMessageModel::FilterRole); //mMessageProxyModel->setFilterRegExp(QRegExp(QString(RsMessageModel::FilterString))) ; @@ -782,14 +782,9 @@ void MessagesDialog::changeBox(int box_row) inChange = true; -// ui.messageTreeWidget->clear(); - ui.quickViewWidget->setCurrentItem(NULL); listMode = LIST_BOX; -// insertMessages(); -// insertMsgTxtAndFiles(ui.messageTreeWidget->currentItem()); - switch(box_row) { case 0: mMessageModel->setCurrentBox(RsMessageModel::BOX_INBOX ); break; diff --git a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h index 771233aa6..abc198ad9 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h +++ b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h @@ -146,11 +146,6 @@ public: QIcon icon ; - if(id.isNull()) - { - str = tr("[Retroshare]"); - icon = QIcon(); - } if(rsPeers->isFriend(RsPeerId(id))) // horrible trick because some widgets still use locations as IDs (e.g. messages) { str = QString::fromUtf8(rsPeers->getPeerName(RsPeerId(id)).c_str()) ; @@ -186,7 +181,6 @@ public: mLoading = true; ++mReloadPeriod; - std::cerr << "Re-loading" << std::endl; QTimer::singleShot(1000,this,SLOT(reload())); } diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index 5e6fb3e41..bc7906d7a 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -48,10 +48,10 @@ const QString RsMessageModel::FilterString("filtered"); RsMessageModel::RsMessageModel(QObject *parent) : QAbstractItemModel(parent) { - mFilteringEnabled=false; mCurrentBox = BOX_NONE; mQuickViewFilter = QUICK_VIEW_ALL; mFilterType = FILTER_TYPE_NONE; + mFilterStrings.clear(); } void RsMessageModel::preMods() @@ -63,15 +63,6 @@ void RsMessageModel::postMods() emit dataChanged(createIndex(0,0,(void*)NULL), createIndex(mMessages.size()-1,COLUMN_THREAD_NB_COLUMNS-1,(void*)NULL)); } -// void RsGxsForumModel::setSortMode(SortMode mode) -// { -// preMods(); -// -// mSortMode = mode; -// -// postMods(); -// } - int RsMessageModel::rowCount(const QModelIndex& parent) const { if(!parent.isValid()) diff --git a/retroshare-gui/src/gui/msgs/MessageModel.h b/retroshare-gui/src/gui/msgs/MessageModel.h index c6167a073..8668bf05e 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.h +++ b/retroshare-gui/src/gui/msgs/MessageModel.h @@ -181,7 +181,6 @@ private: QuickViewFilter mQuickViewFilter ; QStringList mFilterStrings; FilterType mFilterType; - bool mFilteringEnabled; std::vector mMessages; }; From a4ee76e40208c29c4051e361eeb89e3a20db4697 Mon Sep 17 00:00:00 2001 From: hunbernd Date: Sat, 16 Mar 2019 16:36:54 +0100 Subject: [PATCH 27/81] Fixed some dependency issues --- libretroshare/src/libretroshare.pro | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index 528d15497..d772d3a74 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -893,12 +893,15 @@ rs_jsonapi { } INCLUDEPATH *= $${JSONAPI_GENERATOR_OUT} + DEPENDPATH *= $${JSONAPI_GENERATOR_OUT} apiheaders = $$files($${RS_SRC_PATH}/libretroshare/src/retroshare/*.h) + #Make sure that the jsonapigenerator executable are ready + apiheaders += $${JSONAPI_GENERATOR_EXE} genjsonapi.name = Generating jsonapi headers. genjsonapi.input = apiheaders - genjsonapi.output = $${WRAPPERS_INCL_FILE} $${WRAPPERS_INCL_FILE} - genjsonapi.clean = $${WRAPPERS_INCL_FILE} $${WRAPPERS_INCL_FILE} + genjsonapi.output = $${WRAPPERS_INCL_FILE} $${WRAPPERS_REG_FILE} + genjsonapi.clean = $${WRAPPERS_INCL_FILE} $${WRAPPERS_REG_FILE} genjsonapi.CONFIG += target_predeps combine no_link genjsonapi.variable_out = HEADERS genjsonapi.commands = \ From bc294b207db947b935c4688f26edb67cdd68b66f Mon Sep 17 00:00:00 2001 From: hunbernd Date: Sat, 16 Mar 2019 17:26:27 +0100 Subject: [PATCH 28/81] Fixed parallel compilation of librestbed --- libretroshare/src/libretroshare.pro | 34 +++++++++++++++++-------- libretroshare/src/use_libretroshare.pri | 5 ++-- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index d772d3a74..ca03a8a0c 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -861,9 +861,14 @@ rs_jsonapi { WRAPPERS_REG_FILE=$$clean_path($${JSONAPI_GENERATOR_OUT}/jsonapi-wrappers.inl) no_rs_cross_compiling { - restbed.target = $$clean_path($${RESTBED_BUILD_PATH}/library/librestbed.a) + DUMMYRESTBEDINPUT = FORCE + genrestbedlib.name = Generating libresbed. + genrestbedlib.input = DUMMYRESTBEDINPUT + genrestbedlib.output = $$clean_path($${RESTBED_BUILD_PATH}/librestbed.a) + genrestbedlib.CONFIG += target_predeps combine + genrestbedlib.variable_out = PRE_TARGETDEPS win32-g++ { - restbed.commands = \ + genrestbedlib.commands = \ cd $${RS_SRC_PATH} && \ git submodule update --init --recommend-shallow supportlibs/restbed && \ cd $${RESTBED_SRC_PATH} && \ @@ -873,9 +878,9 @@ rs_jsonapi { mkdir -p $${RESTBED_BUILD_PATH}; cd $${RESTBED_BUILD_PATH} && \ cmake -DCMAKE_CXX_COMPILER=$$QMAKE_CXX -G \"MSYS Makefiles\" -DBUILD_SSL=OFF \ -DCMAKE_INSTALL_PREFIX=. -B. -H$$shell_path($${RESTBED_SRC_PATH}) && \ - make && make install + make } else { - restbed.commands = \ + genrestbedlib.commands = \ cd $${RS_SRC_PATH};\ git submodule update --init --recommend-shallow supportlibs/restbed;\ cd $${RESTBED_SRC_PATH};\ @@ -885,21 +890,28 @@ rs_jsonapi { mkdir -p $${RESTBED_BUILD_PATH}; cd $${RESTBED_BUILD_PATH};\ cmake -DCMAKE_CXX_COMPILER=$$QMAKE_CXX -DBUILD_SSL=OFF \ -DCMAKE_INSTALL_PREFIX=. -B. -H$$shell_path($${RESTBED_SRC_PATH});\ - make; make install + make } - QMAKE_EXTRA_TARGETS += restbed - libretroshare.depends += restbed - PRE_TARGETDEPS *= $${restbed.target} + QMAKE_EXTRA_COMPILERS += genrestbedlib + + RESTBED_HEADER_FILE=$$clean_path($${RESTBED_BUILD_PATH}/include/restbed) + genrestbedheader.name = Generating restbed header. + genrestbedheader.input = genrestbedlib.output + genrestbedheader.output = $${RESTBED_HEADER_FILE} + genrestbedheader.CONFIG += target_predeps combine no_link + genrestbedheader.variable_out = HEADERS + genrestbedheader.commands = cd $${RESTBED_BUILD_PATH} && make install + QMAKE_EXTRA_COMPILERS += genrestbedheader } INCLUDEPATH *= $${JSONAPI_GENERATOR_OUT} DEPENDPATH *= $${JSONAPI_GENERATOR_OUT} - apiheaders = $$files($${RS_SRC_PATH}/libretroshare/src/retroshare/*.h) + APIHEADERS = $$files($${RS_SRC_PATH}/libretroshare/src/retroshare/*.h) #Make sure that the jsonapigenerator executable are ready - apiheaders += $${JSONAPI_GENERATOR_EXE} + APIHEADERS += $${JSONAPI_GENERATOR_EXE} genjsonapi.name = Generating jsonapi headers. - genjsonapi.input = apiheaders + genjsonapi.input = APIHEADERS genjsonapi.output = $${WRAPPERS_INCL_FILE} $${WRAPPERS_REG_FILE} genjsonapi.clean = $${WRAPPERS_INCL_FILE} $${WRAPPERS_REG_FILE} genjsonapi.CONFIG += target_predeps combine no_link diff --git a/libretroshare/src/use_libretroshare.pri b/libretroshare/src/use_libretroshare.pri index 79b83ad8c..d3dbb0e45 100644 --- a/libretroshare/src/use_libretroshare.pri +++ b/libretroshare/src/use_libretroshare.pri @@ -55,9 +55,10 @@ rs_jsonapi { RESTBED_SRC_PATH=$$clean_path($${RS_SRC_PATH}/supportlibs/restbed) RESTBED_BUILD_PATH=$$clean_path($${RS_BUILD_PATH}/supportlibs/restbed) INCLUDEPATH *= $$clean_path($${RESTBED_BUILD_PATH}/include/) - QMAKE_LIBDIR *= $$clean_path($${RESTBED_BUILD_PATH}/library/) + DEPENDPATH *= $$clean_path($${RESTBED_BUILD_PATH}/include/) + QMAKE_LIBDIR *= $$clean_path($${RESTBED_BUILD_PATH}/) # Using sLibs would fail as librestbed.a is generated at compile-time - LIBS *= -L$$clean_path($${RESTBED_BUILD_PATH}/library/) -lrestbed + LIBS *= -L$$clean_path($${RESTBED_BUILD_PATH}/) -lrestbed } else:sLibs *= restbed win32-g++:dLibs *= wsock32 From f355abe0257dd6d4d1bc34ef799ac80284d1c5f1 Mon Sep 17 00:00:00 2001 From: csoler Date: Mon, 18 Mar 2019 21:35:55 +0100 Subject: [PATCH 29/81] removed sorting sensitivity and some dead code --- retroshare-gui/src/gui/MessagesDialog.cpp | 5 ++++- retroshare-gui/src/gui/MessagesDialog.h | 3 ++- retroshare-gui/src/gui/msgs/MessageModel.cpp | 16 ++++++++-------- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 1ed9b89c7..a076ae94e 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -140,6 +140,9 @@ MessagesDialog::MessagesDialog(QWidget *parent) mMessageProxyModel = new MessageSortFilterProxyModel(ui.messageTreeWidget->header(),this); mMessageProxyModel->setSourceModel(mMessageModel); mMessageProxyModel->setSortRole(RsMessageModel::SortRole); + mMessageProxyModel->setDynamicSortFilter(false); + mMessageProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); + ui.messageTreeWidget->setModel(mMessageProxyModel); changeBox(0); // set to inbox @@ -179,7 +182,6 @@ MessagesDialog::MessagesDialog(QWidget *parent) headerItem->setToolTip(COLUMN_DATE, tr("Click to sort by date")); headerItem->setToolTip(COLUMN_TAGS, tr("Click to sort by tags")); headerItem->setToolTip(COLUMN_STAR, tr("Click to sort by star")); -#endif mMessageCompareRole = new RSTreeWidgetItemCompareRole; mMessageCompareRole->setRole(COLUMN_SUBJECT, RsMessageModel::SortRole); @@ -189,6 +191,7 @@ MessagesDialog::MessagesDialog(QWidget *parent) mMessageCompareRole->setRole(COLUMN_TAGS, RsMessageModel::SortRole); mMessageCompareRole->setRole(COLUMN_ATTACHEMENTS, RsMessageModel::SortRole); mMessageCompareRole->setRole(COLUMN_STAR, RsMessageModel::SortRole); +#endif RSElidedItemDelegate *itemDelegate = new RSElidedItemDelegate(this); itemDelegate->setSpacing(QSize(0, 2)); diff --git a/retroshare-gui/src/gui/MessagesDialog.h b/retroshare-gui/src/gui/MessagesDialog.h index ba56f0224..4206043f6 100644 --- a/retroshare-gui/src/gui/MessagesDialog.h +++ b/retroshare-gui/src/gui/MessagesDialog.h @@ -138,7 +138,8 @@ private: QTimer *timer; int timerIndex; - RSTreeWidgetItemCompareRole *mMessageCompareRole; + //RSTreeWidgetItemCompareRole *mMessageCompareRole; + MessageWidget *msgWidget; RsMessageModel *mMessageModel; QSortFilterProxyModel *mMessageProxyModel; diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index bc7906d7a..6495b95a3 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -427,14 +427,14 @@ QVariant RsMessageModel::sortRole(const Rs::Msgs::MsgInfoSummary& fmpe,int colum case COLUMN_THREAD_DATE: return QVariant(QString::number(fmpe.ts)); // we should probably have leading zeroes here case COLUMN_THREAD_READ: return QVariant((bool)IS_MESSAGE_UNREAD(fmpe.msgflags)); - case COLUMN_THREAD_AUTHOR: - { - QString str,comment ; - QList icons; - GxsIdDetails::MakeIdDesc(RsGxsId(fmpe.srcId), false, str, icons, comment,GxsIdDetails::ICON_TYPE_NONE); - - return QVariant(str); - } +// case COLUMN_THREAD_AUTHOR: +// { +// QString str,comment ; +// QList icons; +// GxsIdDetails::MakeIdDesc(RsGxsId(fmpe.srcId), false, str, icons, comment,GxsIdDetails::ICON_TYPE_NONE); +// +// return QVariant(str); +// } case COLUMN_THREAD_STAR: return QVariant((fmpe.msgflags & RS_MSG_STAR)? 1:0); default: From 258c544a7597a688bab0356a4afeb14e92525e87 Mon Sep 17 00:00:00 2001 From: csoler Date: Mon, 18 Mar 2019 22:00:15 +0100 Subject: [PATCH 30/81] fixed navigation with arrows in MessagesDialog --- retroshare-gui/src/gui/MessagesDialog.cpp | 75 ++++++++++++----------- retroshare-gui/src/gui/MessagesDialog.h | 1 + 2 files changed, 40 insertions(+), 36 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index a076ae94e..5a1e77f70 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -152,9 +152,7 @@ MessagesDialog::MessagesDialog(QWidget *parent) ui.messageTreeWidget->setSortingEnabled(true); - //ui.messageTreeWidget->setItemDelegateForColumn(RsMessageModel::COLUMN_THREAD_DISTRIBUTION,new DistributionItemDelegate()) ; ui.messageTreeWidget->setItemDelegateForColumn(RsMessageModel::COLUMN_THREAD_AUTHOR,new GxsIdTreeItemDelegate()) ; - //ui.messageTreeWidget->setItemDelegateForColumn(RsGxsForumModel::COLUMN_THREAD_READ,new ReadStatusItemDelegate()) ; #ifdef TO_REMOVE // Set the QStandardItemModel @@ -211,15 +209,18 @@ MessagesDialog::MessagesDialog(QWidget *parent) /* Set initial section sizes */ QHeaderView * msgwheader = ui.messageTreeWidget->header () ; msgwheader->resizeSection (COLUMN_ATTACHEMENTS, fm.width('0')*1.2f); - msgwheader->resizeSection (COLUMN_SUBJECT, 250); - msgwheader->resizeSection (COLUMN_FROM, 140); - msgwheader->resizeSection (COLUMN_DATE, 140); + msgwheader->resizeSection (COLUMN_SUBJECT, fm.width("You have a message")*3.0); + msgwheader->resizeSection (COLUMN_FROM, fm.width("[Retroshare]")*1.5); + msgwheader->resizeSection (COLUMN_DATE, fm.width("01/01/1970")*1.5); + msgwheader->resizeSection (COLUMN_STAR, fm.width('0')*1.5); + msgwheader->resizeSection (COLUMN_UNREAD, fm.width('0')*1.5); - QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_STAR, QHeaderView::Fixed); - msgwheader->resizeSection (COLUMN_STAR, 24); - - QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_UNREAD, QHeaderView::Fixed); - msgwheader->resizeSection (COLUMN_UNREAD, 24); + QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_ATTACHEMENTS, QHeaderView::Fixed); + QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_SUBJECT, QHeaderView::Interactive); + QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_FROM, QHeaderView::Interactive); + QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_DATE, QHeaderView::Interactive); + QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_STAR, QHeaderView::Fixed); + QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_UNREAD, QHeaderView::Fixed); ui.forwardmessageButton->setToolTip(tr("Forward selected Message")); ui.replyallmessageButton->setToolTip(tr("Reply to All")); @@ -240,11 +241,11 @@ MessagesDialog::MessagesDialog(QWidget *parent) /* add filter actions */ - ui.filterLineEdit->addFilter(QIcon(), tr("Subject"), COLUMN_SUBJECT, tr("Search Subject")); - ui.filterLineEdit->addFilter(QIcon(), tr("From"), COLUMN_FROM, tr("Search From")); - ui.filterLineEdit->addFilter(QIcon(), tr("Date"), COLUMN_DATE, tr("Search Date")); - ui.filterLineEdit->addFilter(QIcon(), tr("Content"), COLUMN_CONTENT, tr("Search Content")); - ui.filterLineEdit->addFilter(QIcon(), tr("Tags"), COLUMN_TAGS, tr("Search Tags")); + ui.filterLineEdit->addFilter(QIcon(), tr("Subject"), COLUMN_SUBJECT, tr("Search Subject")); + ui.filterLineEdit->addFilter(QIcon(), tr("From"), COLUMN_FROM, tr("Search From")); + ui.filterLineEdit->addFilter(QIcon(), tr("Date"), COLUMN_DATE, tr("Search Date")); + ui.filterLineEdit->addFilter(QIcon(), tr("Content"), COLUMN_CONTENT, tr("Search Content")); + ui.filterLineEdit->addFilter(QIcon(), tr("Tags"), COLUMN_TAGS, tr("Search Tags")); ui.filterLineEdit->addFilter(QIcon(), tr("Attachments"), COLUMN_ATTACHEMENTS, tr("Search Attachments")); //setting default filter by column as subject @@ -254,14 +255,6 @@ MessagesDialog::MessagesDialog(QWidget *parent) processSettings(true); /* Set header sizes for the fixed columns and resize modes, must be set after processSettings */ - QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_ATTACHEMENTS, QHeaderView::Fixed); - QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_DATE, QHeaderView::Interactive); - QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_UNREAD, QHeaderView::Fixed); - //QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_SIGNATURE, QHeaderView::Fixed); - msgwheader->resizeSection (COLUMN_UNREAD, 24); - //msgwheader->resizeSection (COLUMN_SIGNATURE, 24); - msgwheader->resizeSection (COLUMN_STAR, 24); - QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_STAR, QHeaderView::Fixed); msgwheader->setStretchLastSection(false); // fill folder list @@ -300,23 +293,23 @@ MessagesDialog::MessagesDialog(QWidget *parent) connect(NotifyQt::getInstance(), SIGNAL(messagesChanged()), mMessageModel, SLOT(updateMessages())); connect(NotifyQt::getInstance(), SIGNAL(messagesTagsChanged()), this, SLOT(messagesTagsChanged())); - connect(ui.messageTreeWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(messageTreeWidgetCustomPopupMenu(const QPoint&))); - connect(ui.listWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(folderlistWidgetCustomPopupMenu(QPoint))); - connect(ui.messageTreeWidget, SIGNAL(clicked(const QModelIndex&)) , this, SLOT(clicked(const QModelIndex&))); - connect(ui.messageTreeWidget, SIGNAL(doubleClicked(const QModelIndex&)) , this, SLOT(doubleClicked(const QModelIndex&))); - connect(ui.messageTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), this, SLOT(currentItemChanged(QTreeWidgetItem*))); - connect(ui.messageTreeWidget->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(currentChanged(const QModelIndex&))); - connect(ui.listWidget, SIGNAL(currentRowChanged(int)), this, SLOT(changeBox(int))); - connect(ui.quickViewWidget, SIGNAL(currentRowChanged(int)), this, SLOT(changeQuickView(int))); - connect(ui.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int))); - connect(ui.tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(tabCloseRequested(int))); - connect(ui.newmessageButton, SIGNAL(clicked()), this, SLOT(newmessage())); + + connect(ui.listWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(folderlistWidgetCustomPopupMenu(QPoint))); + connect(ui.listWidget, SIGNAL(currentRowChanged(int)), this, SLOT(changeBox(int))); + connect(ui.quickViewWidget, SIGNAL(currentRowChanged(int)), this, SLOT(changeQuickView(int))); + connect(ui.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int))); + connect(ui.tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(tabCloseRequested(int))); + connect(ui.newmessageButton, SIGNAL(clicked()), this, SLOT(newmessage())); connect(ui.actionTextBesideIcon, SIGNAL(triggered()), this, SLOT(buttonStyle())); - connect(ui.actionIconOnly, SIGNAL(triggered()), this, SLOT(buttonStyle())); - connect(ui.actionTextUnderIcon, SIGNAL(triggered()), this, SLOT(buttonStyle())); + connect(ui.actionIconOnly, SIGNAL(triggered()), this, SLOT(buttonStyle())); + connect(ui.actionTextUnderIcon, SIGNAL(triggered()), this, SLOT(buttonStyle())); + connect(ui.messageTreeWidget, SIGNAL(clicked(const QModelIndex&)) , this, SLOT(clicked(const QModelIndex&))); + connect(ui.messageTreeWidget, SIGNAL(doubleClicked(const QModelIndex&)) , this, SLOT(doubleClicked(const QModelIndex&))); + connect(ui.messageTreeWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(messageTreeWidgetCustomPopupMenu(const QPoint&))); + connect(ui.messageTreeWidget->selectionModel(), SIGNAL(currentChanged(const QModelIndex&,const QModelIndex&)), this, SLOT(currentChanged(const QModelIndex&,const QModelIndex&))); } MessagesDialog::~MessagesDialog() @@ -1299,6 +1292,16 @@ void MessagesDialog::insertMessages() } #endif +// click in messageTreeWidget +void MessagesDialog::currentChanged(const QModelIndex& new_index,const QModelIndex& old_index) +{ + if(!new_index.isValid()) + return; + + // show current message directly + insertMsgTxtAndFiles(new_index); +} + // click in messageTreeWidget void MessagesDialog::clicked(const QModelIndex& index) { diff --git a/retroshare-gui/src/gui/MessagesDialog.h b/retroshare-gui/src/gui/MessagesDialog.h index 4206043f6..dd5fb96be 100644 --- a/retroshare-gui/src/gui/MessagesDialog.h +++ b/retroshare-gui/src/gui/MessagesDialog.h @@ -77,6 +77,7 @@ private slots: void updateCurrentMessage(); void clicked(const QModelIndex&); void doubleClicked(const QModelIndex&); + void currentChanged(const QModelIndex& new_index, const QModelIndex &old_index); void newmessage(); void openAsWindow(); From 3419b44ec1c3efb0d052990fa0e3679e468cf477 Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 19 Mar 2019 10:22:20 +0100 Subject: [PATCH 31/81] fixed a few bugs in msg model and cleaned up dead code --- retroshare-gui/src/gui/MessagesDialog.cpp | 669 ++----------------- retroshare-gui/src/gui/MessagesDialog.h | 4 +- retroshare-gui/src/gui/msgs/MessageModel.cpp | 25 +- retroshare-gui/src/gui/msgs/MessageModel.h | 1 + 4 files changed, 72 insertions(+), 627 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 5a1e77f70..e8e6a8aeb 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -61,19 +61,6 @@ #define IMAGE_DECRYPTMESSAGE ":/images/decrypt-mail.png" #define IMAGE_AUTHOR_INFO ":/images/info16.png" -#define COLUMN_STAR 0 -#define COLUMN_ATTACHEMENTS 1 -#define COLUMN_SUBJECT 2 -#define COLUMN_UNREAD 3 -#define COLUMN_FROM 4 -//#define COLUMN_SIGNATURE 5 -#define COLUMN_DATE 5 -#define COLUMN_CONTENT 6 -#define COLUMN_TAGS 7 -#define COLUMN_COUNT 8 - -#define COLUMN_DATA 0 // column for storing the userdata like msgid and srcid - #define ROLE_QUICKVIEW_TYPE Qt::UserRole #define ROLE_QUICKVIEW_ID Qt::UserRole + 1 #define ROLE_QUICKVIEW_TEXT Qt::UserRole + 2 @@ -95,7 +82,7 @@ class MessageSortFilterProxyModel: public QSortFilterProxyModel { public: - MessageSortFilterProxyModel(const QHeaderView *header,QObject *parent = NULL): QSortFilterProxyModel(parent),m_header(header) {} + MessageSortFilterProxyModel(const QHeaderView *header,QObject *parent = NULL): QSortFilterProxyModel(parent),m_header(header) , m_sortingEnabled(false) {} bool lessThan(const QModelIndex& left, const QModelIndex& right) const override { @@ -107,8 +94,16 @@ public: return sourceModel()->index(source_row,0,source_parent).data(RsMessageModel::FilterRole).toString() == RsMessageModel::FilterString ; } + void sort( int column, Qt::SortOrder order = Qt::AscendingOrder ) override + { + if(m_sortingEnabled) + return QSortFilterProxyModel::sort(column,order) ; + } + + void setSortingEnabled(bool b) { m_sortingEnabled = b ; } private: const QHeaderView *m_header ; + bool m_sortingEnabled; }; /** Constructor */ @@ -148,54 +143,16 @@ MessagesDialog::MessagesDialog(QWidget *parent) changeBox(0); // set to inbox mMessageProxyModel->setFilterRole(RsMessageModel::FilterRole); - //mMessageProxyModel->setFilterRegExp(QRegExp(QString(RsMessageModel::FilterString))) ; ui.messageTreeWidget->setSortingEnabled(true); - ui.messageTreeWidget->setItemDelegateForColumn(RsMessageModel::COLUMN_THREAD_AUTHOR,new GxsIdTreeItemDelegate()) ; - -#ifdef TO_REMOVE - // Set the QStandardItemModel - ui.messageTreeWidget->setColumnCount(COLUMN_COUNT); - QTreeWidgetItem *headerItem = ui.messageTreeWidget->headerItem(); - headerItem->setText(COLUMN_ATTACHEMENTS, ""); - headerItem->setIcon(COLUMN_ATTACHEMENTS, QIcon(":/images/attachment.png")); - headerItem->setText(COLUMN_SUBJECT, tr("Subject")); - headerItem->setText(COLUMN_UNREAD, ""); - headerItem->setIcon(COLUMN_UNREAD, QIcon(":/images/message-state-header.png")); - headerItem->setText(COLUMN_FROM, tr("From")); - headerItem->setText(COLUMN_SIGNATURE, ""); - headerItem->setIcon(COLUMN_SIGNATURE, QIcon(":/images/signature.png")); - headerItem->setText(COLUMN_DATE, tr("Date")); - headerItem->setText(COLUMN_TAGS, tr("Tags")); - headerItem->setText(COLUMN_CONTENT, tr("Content")); - headerItem->setText(COLUMN_STAR, ""); - headerItem->setIcon(COLUMN_STAR, QIcon(IMAGE_STAR_ON)); - - headerItem->setToolTip(COLUMN_ATTACHEMENTS, tr("Click to sort by attachments")); - headerItem->setToolTip(COLUMN_SUBJECT, tr("Click to sort by subject")); - headerItem->setToolTip(COLUMN_UNREAD, tr("Click to sort by read")); - headerItem->setToolTip(COLUMN_FROM, tr("Click to sort by from")); - headerItem->setToolTip(COLUMN_SIGNATURE, tr("Click to sort by signature")); - headerItem->setToolTip(COLUMN_DATE, tr("Click to sort by date")); - headerItem->setToolTip(COLUMN_TAGS, tr("Click to sort by tags")); - headerItem->setToolTip(COLUMN_STAR, tr("Click to sort by star")); - - mMessageCompareRole = new RSTreeWidgetItemCompareRole; - mMessageCompareRole->setRole(COLUMN_SUBJECT, RsMessageModel::SortRole); - mMessageCompareRole->setRole(COLUMN_UNREAD, RsMessageModel::SortRole); - mMessageCompareRole->setRole(COLUMN_FROM, RsMessageModel::SortRole); - mMessageCompareRole->setRole(COLUMN_DATE, RsMessageModel::SortRole); - mMessageCompareRole->setRole(COLUMN_TAGS, RsMessageModel::SortRole); - mMessageCompareRole->setRole(COLUMN_ATTACHEMENTS, RsMessageModel::SortRole); - mMessageCompareRole->setRole(COLUMN_STAR, RsMessageModel::SortRole); -#endif + ui.messageTreeWidget->setColumnHidden(RsMessageModel::COLUMN_THREAD_CONTENT,true); RSElidedItemDelegate *itemDelegate = new RSElidedItemDelegate(this); itemDelegate->setSpacing(QSize(0, 2)); ui.messageTreeWidget->setItemDelegate(itemDelegate); - ui.messageTreeWidget->sortByColumn(COLUMN_DATA, Qt::DescendingOrder); + //ui.messageTreeWidget->sortByColumn(COLUMN_DATA, Qt::DescendingOrder); // workaround for Qt bug, should be solved in next Qt release 4.7.0 // http://bugreports.qt.nokia.com/browse/QTBUG-8270 @@ -208,19 +165,19 @@ MessagesDialog::MessagesDialog(QWidget *parent) /* Set initial section sizes */ QHeaderView * msgwheader = ui.messageTreeWidget->header () ; - msgwheader->resizeSection (COLUMN_ATTACHEMENTS, fm.width('0')*1.2f); - msgwheader->resizeSection (COLUMN_SUBJECT, fm.width("You have a message")*3.0); - msgwheader->resizeSection (COLUMN_FROM, fm.width("[Retroshare]")*1.5); - msgwheader->resizeSection (COLUMN_DATE, fm.width("01/01/1970")*1.5); - msgwheader->resizeSection (COLUMN_STAR, fm.width('0')*1.5); - msgwheader->resizeSection (COLUMN_UNREAD, fm.width('0')*1.5); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_STAR, fm.width('0')*1.1); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_ATTACHMENT, fm.width('0')*1.1); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_SUBJECT, fm.width("You have a message")*3.0); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_AUTHOR, fm.width("[Retroshare]")*1.5); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_DATE, fm.width("01/01/1970")*1.5); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_READ, fm.width('0')*1.1); - QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_ATTACHEMENTS, QHeaderView::Fixed); - QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_SUBJECT, QHeaderView::Interactive); - QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_FROM, QHeaderView::Interactive); - QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_DATE, QHeaderView::Interactive); - QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_STAR, QHeaderView::Fixed); - QHeaderView_setSectionResizeModeColumn(msgwheader, COLUMN_UNREAD, QHeaderView::Fixed); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_STAR, QHeaderView::Fixed); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_ATTACHMENT, QHeaderView::Fixed); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_SUBJECT, QHeaderView::Interactive); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_AUTHOR, QHeaderView::Interactive); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_DATE, QHeaderView::Interactive); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_READ, QHeaderView::Fixed); ui.forwardmessageButton->setToolTip(tr("Forward selected Message")); ui.replyallmessageButton->setToolTip(tr("Reply to All")); @@ -241,15 +198,15 @@ MessagesDialog::MessagesDialog(QWidget *parent) /* add filter actions */ - ui.filterLineEdit->addFilter(QIcon(), tr("Subject"), COLUMN_SUBJECT, tr("Search Subject")); - ui.filterLineEdit->addFilter(QIcon(), tr("From"), COLUMN_FROM, tr("Search From")); - ui.filterLineEdit->addFilter(QIcon(), tr("Date"), COLUMN_DATE, tr("Search Date")); - ui.filterLineEdit->addFilter(QIcon(), tr("Content"), COLUMN_CONTENT, tr("Search Content")); - ui.filterLineEdit->addFilter(QIcon(), tr("Tags"), COLUMN_TAGS, tr("Search Tags")); - ui.filterLineEdit->addFilter(QIcon(), tr("Attachments"), COLUMN_ATTACHEMENTS, tr("Search Attachments")); + ui.filterLineEdit->addFilter(QIcon(), tr("Subject"), RsMessageModel::COLUMN_THREAD_SUBJECT, tr("Search Subject")); + ui.filterLineEdit->addFilter(QIcon(), tr("From"), RsMessageModel::COLUMN_THREAD_AUTHOR, tr("Search From")); + ui.filterLineEdit->addFilter(QIcon(), tr("Date"), RsMessageModel::COLUMN_THREAD_DATE, tr("Search Date")); + ui.filterLineEdit->addFilter(QIcon(), tr("Content"), RsMessageModel::COLUMN_THREAD_CONTENT, tr("Search Content")); + ui.filterLineEdit->addFilter(QIcon(), tr("Tags"), RsMessageModel::COLUMN_THREAD_TAGS, tr("Search Tags")); + ui.filterLineEdit->addFilter(QIcon(), tr("Attachments"), RsMessageModel::COLUMN_THREAD_ATTACHMENT, tr("Search Attachments")); //setting default filter by column as subject - ui.filterLineEdit->setCurrentFilter(COLUMN_SUBJECT); + ui.filterLineEdit->setCurrentFilter(RsMessageModel::COLUMN_THREAD_SUBJECT); // load settings processSettings(true); @@ -309,9 +266,18 @@ MessagesDialog::MessagesDialog(QWidget *parent) connect(ui.messageTreeWidget, SIGNAL(doubleClicked(const QModelIndex&)) , this, SLOT(doubleClicked(const QModelIndex&))); connect(ui.messageTreeWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(messageTreeWidgetCustomPopupMenu(const QPoint&))); + connect(ui.messageTreeWidget->header(),SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), this, SLOT(sortColumn(int,Qt::SortOrder))); + connect(ui.messageTreeWidget->selectionModel(), SIGNAL(currentChanged(const QModelIndex&,const QModelIndex&)), this, SLOT(currentChanged(const QModelIndex&,const QModelIndex&))); } +void MessagesDialog::sortColumn(int col,Qt::SortOrder so) +{ + mMessageProxyModel->setSortingEnabled(true); + mMessageProxyModel->sort(col,so); + mMessageProxyModel->setSortingEnabled(false); +} + MessagesDialog::~MessagesDialog() { // save settings @@ -337,7 +303,7 @@ void MessagesDialog::processSettings(bool load) // load settings // filterColumn - ui.filterLineEdit->setCurrentFilter(Settings->value("filterColumn", COLUMN_SUBJECT).toInt()); + ui.filterLineEdit->setCurrentFilter(Settings->value("filterColumn", RsMessageModel::COLUMN_THREAD_SUBJECT).toInt()); // state of message tree if (Settings->value("MessageTreeVersion").toInt() == messageTreeVersion) { @@ -475,17 +441,6 @@ void MessagesDialog::fillQuickView() updateMessageSummaryList(); } -// replaced by shortcut -//void MessagesDialog::keyPressEvent(QKeyEvent *e) -//{ -// if(e->key() == Qt::Key_Delete) -// { -// removemessage() ; -// e->accept() ; -// } -// else -// MainPage::keyPressEvent(e) ; -//} int MessagesDialog::getSelectedMessages(QList& mid) { //To check if the selection has more than one row. @@ -494,7 +449,7 @@ int MessagesDialog::getSelectedMessages(QList& mid) QModelIndexList qmil = ui.messageTreeWidget->selectionModel()->selectedRows(); foreach(const QModelIndex& m, qmil) - mid.push_back(m.sibling(m.row(),COLUMN_DATA).data(RsMessageModel::MsgIdRole).toString()) ; + mid.push_back(m.sibling(m.row(),RsMessageModel::COLUMN_THREAD_MSGID).data(RsMessageModel::MsgIdRole).toString()) ; return mid.size(); } @@ -830,468 +785,6 @@ static void InitIconAndFont(QTreeWidgetItem *item) { } -#ifdef TO_REMOVE -void MessagesDialog::insertMessages() -{ - if (lockUpdate) { - return; - } - - std::list msgList; - std::list::const_iterator it; - MessageInfo msgInfo; - bool gotInfo; - QString text; - - RsPeerId ownId = rsPeers->getOwnId(); - - rsMail -> getMessageSummaries(msgList); - - int filterColumn = ui.filterLineEdit->currentFilter(); - - /* check the mode we are in */ - unsigned int msgbox = 0; - bool isTrash = false; - bool doFill = true; - int quickViewType = 0; - uint32_t quickViewId = 0; - QString boxText; - QIcon boxIcon; - QString placeholderText; - - switch (listMode) { - case LIST_NOTHING: - doFill = false; - break; - - case LIST_BOX: - { - QListWidgetItem *listItem = ui.listWidget->currentItem(); - if (listItem) { - boxIcon = listItem->icon(); - } - - int listrow = ui.listWidget->currentRow(); - - switch (listrow) { - case ROW_INBOX: - msgbox = RS_MSG_INBOX; - boxText = tr("Inbox"); - break; - case ROW_OUTBOX: - msgbox = RS_MSG_OUTBOX; - boxText = tr("Outbox"); - break; - case ROW_DRAFTBOX: - msgbox = RS_MSG_DRAFTBOX; - boxText = tr("Drafts"); - break; - case ROW_SENTBOX: - msgbox = RS_MSG_SENTBOX; - boxText = tr("Sent"); - break; - case ROW_TRASHBOX: - isTrash = true; - boxText = tr("Trash"); - break; - default: - doFill = false; - } - } - break; - - case LIST_QUICKVIEW: - { - QListWidgetItem *listItem = ui.quickViewWidget->currentItem(); - if (listItem) { - quickViewType = listItem->data(ROLE_QUICKVIEW_TYPE).toInt(); - quickViewId = listItem->data(ROLE_QUICKVIEW_ID).toInt(); - - boxText = listItem->text(); - boxIcon = listItem->icon(); - - switch (quickViewType) { - case QUICKVIEW_TYPE_NOTHING: - doFill = false; - break; - case QUICKVIEW_TYPE_STATIC: - switch (quickViewId) { - case QUICKVIEW_STATIC_ID_STARRED: - placeholderText = tr("No starred messages available. Stars let you give messages a special status to make them easier to find. To star a message, click on the light gray star beside any message."); - break; - case QUICKVIEW_STATIC_ID_SYSTEM: - placeholderText = tr("No system messages available."); - break; - } - break; - case QUICKVIEW_TYPE_TAG: - break; - } - } else { - doFill = false; - } - } - break; - - default: - doFill = false; - } - - ui.tabWidget->setTabText (0, boxText); - ui.tabWidget->setTabIcon (0, boxIcon); - ui.messageTreeWidget->setPlaceholderText(placeholderText); - - QTreeWidgetItem *headerItem = ui.messageTreeWidget->headerItem(); - if (msgbox == RS_MSG_INBOX) { - headerItem->setText(COLUMN_FROM, tr("From")); - headerItem->setToolTip(COLUMN_FROM, tr("Click to sort by from")); - } else { - headerItem->setText(COLUMN_FROM, tr("To")); - headerItem->setToolTip(COLUMN_FROM, tr("Click to sort by to")); - } - - if (doFill) { - MsgTagType Tags; - rsMail->getMessageTagTypes(Tags); - - /* search messages */ - std::list msgToShow; - for(it = msgList.begin(); it != msgList.end(); ++it) { - if (listMode == LIST_BOX) { - if (isTrash) { - if ((it->msgflags & RS_MSG_TRASH) == 0) { - continue; - } - } else { - if (it->msgflags & RS_MSG_TRASH) { - continue; - } - if ((it->msgflags & RS_MSG_BOXMASK) != msgbox) { - continue; - } - } - } else if (listMode == LIST_QUICKVIEW && quickViewType == QUICKVIEW_TYPE_TAG) { - MsgTagInfo tagInfo; - rsMail->getMessageTag(it->msgId, tagInfo); - if (std::find(tagInfo.tagIds.begin(), tagInfo.tagIds.end(), quickViewId) == tagInfo.tagIds.end()) { - continue; - } - } else if (listMode == LIST_QUICKVIEW && quickViewType == QUICKVIEW_TYPE_STATIC) { - if (quickViewId == QUICKVIEW_STATIC_ID_STARRED && (it->msgflags & RS_MSG_STAR) == 0) { - continue; - } - if (quickViewId == QUICKVIEW_STATIC_ID_SYSTEM && (it->msgflags & RS_MSG_SYSTEM) == 0) { - continue; - } - } else { - continue; - } - - msgToShow.push_back(*it); - } - - /* remove old items */ - QTreeWidgetItemIterator itemIterator(ui.messageTreeWidget); - QTreeWidgetItem *treeItem; - while ((treeItem = *itemIterator) != NULL) { - ++itemIterator; - std::string msgIdFromRow = treeItem->data(COLUMN_DATA, ROLE_MSGID).toString().toStdString(); - for(it = msgToShow.begin(); it != msgToShow.end(); ++it) { - if (it->msgId == msgIdFromRow) { - break; - } - } - - if (it == msgToShow.end ()) { - delete(treeItem); - } - } - - for(it = msgToShow.begin(); it != msgToShow.end(); ++it) - { - /* check the message flags, to decide which - * group it should go in... - * - * InBox - * OutBox - * Drafts - * Sent - * - * FLAGS = OUTGOING. - * -> Outbox/Drafts/Sent - * + SENT -> Sent - * + IN_PROGRESS -> Draft. - * + nuffing -> Outbox. - * FLAGS = INCOMING = (!OUTGOING) - * -> + NEW -> Bold. - * - */ - - gotInfo = false; - msgInfo = MessageInfo(); // clear - - // search exisisting items - QTreeWidgetItemIterator existingItemIterator(ui.messageTreeWidget); - while ((treeItem = *existingItemIterator) != NULL) { - ++existingItemIterator; - if (it->msgId == treeItem->data(COLUMN_DATA, ROLE_MSGID).toString().toStdString()) { - break; - } - } - - /* make a widget per friend */ - - bool insertItem = false; - - GxsIdRSTreeWidgetItem *item; - if (treeItem) { - item = dynamic_cast(treeItem); - if (!item) { - std::cerr << "MessagesDialog::insertMessages() Item is no GxsIdRSTreeWidgetItem" << std::endl; - continue; - } - } else { - item = new GxsIdRSTreeWidgetItem(mMessageCompareRole,GxsIdDetails::ICON_TYPE_AVATAR); - insertItem = true; - } - - /* So Text should be: - * (1) Msg / Broadcast - * (1b) Person / Channel Name - * (2) Rank - * (3) Date - * (4) Title - * (5) Msg - * (6) File Count - * (7) File Total - */ - - QString dateString; - // Date First.... (for sorting) - { - QDateTime qdatetime; - qdatetime.setTime_t(it->ts); - - // add string to all data - dateString = qdatetime.toString("_yyyyMMdd_hhmmss"); - - //if the mail is on same date show only time. - if (qdatetime.daysTo(QDateTime::currentDateTime()) == 0) - { - item->setText(COLUMN_DATE, DateTime::formatTime(qdatetime.time())); - } - else - { - item->setText(COLUMN_DATE, DateTime::formatDateTime(qdatetime)); - } - // for sorting - item->setData(COLUMN_DATE, ROLE_SORT, qdatetime); - } - - // From .... - { - bool setText = true; - if (msgbox == RS_MSG_INBOX || msgbox == RS_MSG_OUTBOX) - { - if ((it->msgflags & RS_MSG_SYSTEM) && it->srcId == ownId) { - text = "RetroShare"; - } - else - { - if (it->msgflags & RS_MSG_DISTANT) - { - // distant message - setText = false; - if (gotInfo || rsMail->getMessage(it->msgId, msgInfo)) { - gotInfo = true; - - if(msgbox != RS_MSG_INBOX && !msgInfo.rsgxsid_msgto.empty()) - item->setId(RsGxsId(*msgInfo.rsgxsid_msgto.begin()), COLUMN_FROM, false); - else - item->setId(RsGxsId(msgInfo.rsgxsid_srcId), COLUMN_FROM, false); - } - else - std::cerr << "MessagesDialog::insertMsgTxtAndFiles() Couldn't find Msg" << std::endl; - } - else - text = QString::fromUtf8(rsPeers->getPeerName(it->srcId).c_str()); - } - } - else - { - if (gotInfo || rsMail->getMessage(it->msgId, msgInfo)) { - gotInfo = true; - - text.clear(); - - for(std::set::const_iterator pit = msgInfo.rspeerid_msgto.begin(); pit != msgInfo.rspeerid_msgto.end(); ++pit) - { - if (!text.isEmpty()) - text += ", "; - - std::string peerName = rsPeers->getPeerName(*pit); - if (peerName.empty()) - text += PeerDefs::rsid("", *pit); - else - text += QString::fromUtf8(peerName.c_str()); - } - for(std::set::const_iterator pit = msgInfo.rsgxsid_msgto.begin(); pit != msgInfo.rsgxsid_msgto.end(); ++pit) - { - if (!text.isEmpty()) - text += ", "; - - RsIdentityDetails details; - if (rsIdentity->getIdDetails(*pit, details) && !details.mNickname.empty()) - text += QString::fromUtf8(details.mNickname.c_str()) ; - else - text += PeerDefs::rsid("", *pit); - } - } else { - std::cerr << "MessagesDialog::insertMsgTxtAndFiles() Couldn't find Msg" << std::endl; - } - } - if (setText) - { - item->setText(COLUMN_FROM, text); - item->setData(COLUMN_FROM, ROLE_SORT, text + dateString); - } else { - item->setData(COLUMN_FROM, ROLE_SORT, item->text(COLUMN_FROM) + dateString); - } - } - - // Subject - text = QString::fromUtf8(it->title.c_str()); - - item->setText(COLUMN_SUBJECT, text); - item->setData(COLUMN_SUBJECT, ROLE_SORT, text + dateString); - - // internal data - QString msgId = QString::fromStdString(it->msgId); - item->setData(COLUMN_DATA, ROLE_SRCID, QString::fromStdString(it->srcId.toStdString())); - item->setData(COLUMN_DATA, ROLE_MSGID, msgId); - item->setData(COLUMN_DATA, ROLE_MSGFLAGS, it->msgflags); - - // Init icon and font - InitIconAndFont(item); - - // Tags - MsgTagInfo tagInfo; - rsMail->getMessageTag(it->msgId, tagInfo); - - text.clear(); - - // build tag names - std::map >::iterator Tag; - for (std::list::iterator tagId = tagInfo.tagIds.begin(); tagId != tagInfo.tagIds.end(); ++tagId) { - if (text.isEmpty() == false) { - text += ","; - } - Tag = Tags.types.find(*tagId); - if (Tag != Tags.types.end()) { - text += TagDefs::name(Tag->first, Tag->second.first); - } else { - // clean tagId - rsMail->setMessageTag(it->msgId, *tagId, false); - } - } - item->setText(COLUMN_TAGS, text); - item->setData(COLUMN_TAGS, ROLE_SORT, text); - - // set color - QColor color; - if (tagInfo.tagIds.size()) { - Tag = Tags.types.find(tagInfo.tagIds.front()); - if (Tag != Tags.types.end()) { - color = Tag->second.second; - } else { - // clean tagId - rsMail->setMessageTag(it->msgId, tagInfo.tagIds.front(), false); - } - } - if (!color.isValid()) { - color = ui.messageTreeWidget->palette().color(QPalette::Text); - } - QBrush brush = QBrush(color); - for (int i = 0; i < COLUMN_COUNT; ++i) { - item->setForeground(i, brush); - } - - // No of Files. - { - item->setText(COLUMN_ATTACHEMENTS, QString::number(it->count)); - item->setData(COLUMN_ATTACHEMENTS, ROLE_SORT, item->text(COLUMN_ATTACHEMENTS) + dateString); - item->setTextAlignment(COLUMN_ATTACHEMENTS, Qt::AlignHCenter); - } - - if (filterColumn == COLUMN_CONTENT) { - // need content for filter - if (gotInfo || rsMail->getMessage(it->msgId, msgInfo)) { - gotInfo = true; - QTextDocument doc; - doc.setHtml(QString::fromUtf8(msgInfo.msg.c_str())); - item->setText(COLUMN_CONTENT, doc.toPlainText().replace(QString("\n"), QString(" "))); - } else { - std::cerr << "MessagesDialog::insertMsgTxtAndFiles() Couldn't find Msg" << std::endl; - item->setText(COLUMN_CONTENT, ""); - } - } - - else if(it->msgflags & RS_MSG_DISTANT) - { - item->setIcon(COLUMN_SIGNATURE, QIcon(":/images/blue_lock_open.png")) ; - item->setIcon(COLUMN_SUBJECT, QIcon(":/images/message-mail-read.png")) ; - - if (msgbox == RS_MSG_INBOX ) - { - item->setToolTip(COLUMN_SIGNATURE, tr("This message comes from a distant person.")) ; - } - else if (msgbox == RS_MSG_OUTBOX) - { - item->setToolTip(COLUMN_SIGNATURE, tr("This message goes to a distant person.")) ; - } - - if(it->msgflags & RS_MSG_SIGNED) - { - if(it->msgflags & RS_MSG_SIGNATURE_CHECKS) - { - item->setIcon(COLUMN_SIGNATURE, QIcon(":/images/stock_signature_ok.png")) ; - item->setToolTip(COLUMN_SIGNATURE, tr("This message was signed and the signature checks")) ; - } - else - { - item->setIcon(COLUMN_SIGNATURE, QIcon(":/images/stock_signature_bad.png")) ; - item->setToolTip(COLUMN_SIGNATURE, tr("This message was signed but the signature doesn't check")) ; - } - } - } - else - item->setIcon(COLUMN_SIGNATURE, QIcon()) ; - - if (insertItem) { - /* add to the list */ - ui.messageTreeWidget->addTopLevelItem(item); - } - } - } else { - ui.messageTreeWidget->clear(); - } - - ui.messageTreeWidget->showColumn(COLUMN_ATTACHEMENTS); - ui.messageTreeWidget->showColumn(COLUMN_SUBJECT); - ui.messageTreeWidget->showColumn(COLUMN_UNREAD); - ui.messageTreeWidget->showColumn(COLUMN_FROM); - ui.messageTreeWidget->showColumn(COLUMN_DATE); - ui.messageTreeWidget->showColumn(COLUMN_TAGS); - ui.messageTreeWidget->hideColumn(COLUMN_CONTENT); - - if (!ui.filterLineEdit->text().isEmpty()) { - ui.messageTreeWidget->filterItems(ui.filterLineEdit->currentFilter(), ui.filterLineEdit->text()); - } - - updateMessageSummaryList(); -} -#endif - // click in messageTreeWidget void MessagesDialog::currentChanged(const QModelIndex& new_index,const QModelIndex& old_index) { @@ -1310,14 +803,14 @@ void MessagesDialog::clicked(const QModelIndex& index) switch (index.column()) { - case COLUMN_UNREAD: + case RsMessageModel::COLUMN_THREAD_READ: { mMessageModel->setMsgReadStatus(index, !isMessageRead(index)); insertMsgTxtAndFiles(index); updateMessageSummaryList(); return; } - case COLUMN_STAR: + case RsMessageModel::COLUMN_THREAD_STAR: { mMessageModel->setMsgStar(index, !hasMessageStar(index)); return; @@ -1366,32 +859,6 @@ void MessagesDialog::updateCurrentMessage() { } -// void MessagesDialog::setMsgAsReadUnread(const QList &items, bool read) -// { -// LockUpdate Lock (this, false); -// -// foreach (QTreeWidgetItem *item, items) { -// std::string mid = item->data(COLUMN_DATA, RsMessageModel::MsgIdRole).toString().toStdString(); -// -// if (rsMail->MessageRead(mid, !read)) { -// int msgFlag = item->data(COLUMN_DATA, RsMessageModel::MsgFlagsRole).toInt(); -// msgFlag &= ~RS_MSG_NEW; -// -// if (read) { -// msgFlag &= ~RS_MSG_UNREAD_BY_USER; -// } else { -// msgFlag |= RS_MSG_UNREAD_BY_USER; -// } -// -// item->setData(COLUMN_DATA, RsMessageModel::MsgFlagsRole, msgFlag); -// -// InitIconAndFont(item); -// } -// } -// -// // LockUpdate -// } - void MessagesDialog::markAsRead() { QList itemsUnread; @@ -1460,6 +927,7 @@ void MessagesDialog::insertMsgTxtAndFiles(const QModelIndex& index) mMessageModel->setMsgReadStatus(index, true); updateInterface(); + updateMessageSummaryList(); msgWidget->fill(mid); } @@ -1467,26 +935,11 @@ bool MessagesDialog::getCurrentMsg(std::string &cid, std::string &mid) { QModelIndex indx = ui.messageTreeWidget->currentIndex(); -#ifdef TODO - /* get its Ids */ - if (!indx.isValid()) - { - //If no message is selected. assume first message is selected. - if (ui.messageTreeWidget->topLevelItemCount() == 0) - { - item = ui.messageTreeWidget->topLevelItem(0); - } - } - - if (!item) { - return false; - } -#endif if(!indx.isValid()) return false ; - cid = indx.sibling(indx.row(),COLUMN_DATA).data(RsMessageModel::SrcIdRole).toString().toStdString(); - mid = indx.sibling(indx.row(),COLUMN_DATA).data(RsMessageModel::MsgIdRole).toString().toStdString(); + cid = indx.sibling(indx.row(),RsMessageModel::COLUMN_THREAD_MSGID).data(RsMessageModel::SrcIdRole).toString().toStdString(); + mid = indx.sibling(indx.row(),RsMessageModel::COLUMN_THREAD_MSGID).data(RsMessageModel::MsgIdRole).toString().toStdString(); return true; } @@ -1513,6 +966,9 @@ void MessagesDialog::removemessage() rsMail->MessageToTrash(m.toStdString(), true); } } + + mMessageModel->updateMessages(); + updateMessageSummaryList(); } void MessagesDialog::undeletemessage() @@ -1522,6 +978,9 @@ void MessagesDialog::undeletemessage() foreach (const QString& s, msgids) rsMail->MessageToTrash(s.toStdString(), false); + + mMessageModel->updateMessages(); + updateMessageSummaryList(); } void MessagesDialog::setToolbarButtonStyle(Qt::ToolButtonStyle style) @@ -1549,12 +1008,12 @@ void MessagesDialog::filterChanged(const QString& text) switch(ui.filterLineEdit->currentFilter()) { - case COLUMN_SUBJECT: f = RsMessageModel::FILTER_TYPE_SUBJECT ; break; - case COLUMN_FROM: f = RsMessageModel::FILTER_TYPE_FROM ; break; - case COLUMN_DATE: f = RsMessageModel::FILTER_TYPE_DATE ; break; - case COLUMN_CONTENT: f = RsMessageModel::FILTER_TYPE_CONTENT ; break; - case COLUMN_TAGS: f = RsMessageModel::FILTER_TYPE_TAGS ; break; - case COLUMN_ATTACHEMENTS: f = RsMessageModel::FILTER_TYPE_ATTACHMENTS ; break; + case RsMessageModel::COLUMN_THREAD_SUBJECT: f = RsMessageModel::FILTER_TYPE_SUBJECT ; break; + case RsMessageModel::COLUMN_THREAD_AUTHOR: f = RsMessageModel::FILTER_TYPE_FROM ; break; + case RsMessageModel::COLUMN_THREAD_DATE: f = RsMessageModel::FILTER_TYPE_DATE ; break; + case RsMessageModel::COLUMN_THREAD_CONTENT: f = RsMessageModel::FILTER_TYPE_CONTENT ; break; + case RsMessageModel::COLUMN_THREAD_TAGS: f = RsMessageModel::FILTER_TYPE_TAGS ; break; + case RsMessageModel::COLUMN_THREAD_ATTACHMENT: f = RsMessageModel::FILTER_TYPE_ATTACHMENTS ; break; default:break; } @@ -1570,12 +1029,12 @@ void MessagesDialog::filterColumnChanged(int column) switch(column) { - case COLUMN_SUBJECT: f = RsMessageModel::FILTER_TYPE_SUBJECT ; break; - case COLUMN_FROM: f = RsMessageModel::FILTER_TYPE_FROM ; break; - case COLUMN_DATE: f = RsMessageModel::FILTER_TYPE_DATE ; break; - case COLUMN_CONTENT: f = RsMessageModel::FILTER_TYPE_CONTENT ; break; - case COLUMN_TAGS: f = RsMessageModel::FILTER_TYPE_TAGS ; break; - case COLUMN_ATTACHEMENTS: f = RsMessageModel::FILTER_TYPE_ATTACHMENTS ; break; + case RsMessageModel::COLUMN_THREAD_SUBJECT: f = RsMessageModel::FILTER_TYPE_SUBJECT ; break; + case RsMessageModel::COLUMN_THREAD_AUTHOR: f = RsMessageModel::FILTER_TYPE_FROM ; break; + case RsMessageModel::COLUMN_THREAD_DATE: f = RsMessageModel::FILTER_TYPE_DATE ; break; + case RsMessageModel::COLUMN_THREAD_CONTENT: f = RsMessageModel::FILTER_TYPE_CONTENT ; break; + case RsMessageModel::COLUMN_THREAD_TAGS: f = RsMessageModel::FILTER_TYPE_TAGS ; break; + case RsMessageModel::COLUMN_THREAD_ATTACHMENT: f = RsMessageModel::FILTER_TYPE_ATTACHMENTS ; break; default:break; } diff --git a/retroshare-gui/src/gui/MessagesDialog.h b/retroshare-gui/src/gui/MessagesDialog.h index dd5fb96be..0e371585e 100644 --- a/retroshare-gui/src/gui/MessagesDialog.h +++ b/retroshare-gui/src/gui/MessagesDialog.h @@ -32,6 +32,7 @@ class RSTreeWidgetItemCompareRole; class MessageWidget; class QTreeWidgetItem; class RsMessageModel; +class MessageSortFilterProxyModel ; class MessagesDialog : public MainPage { @@ -71,6 +72,7 @@ private slots: void messageTreeWidgetCustomPopupMenu(QPoint point); void folderlistWidgetCustomPopupMenu(QPoint); void showAuthorInPeopleTab(); + void sortColumn(int col,Qt::SortOrder so); void changeBox(int newrow); void changeQuickView(int newrow); @@ -143,7 +145,7 @@ private: MessageWidget *msgWidget; RsMessageModel *mMessageModel; - QSortFilterProxyModel *mMessageProxyModel; + MessageSortFilterProxyModel *mMessageProxyModel; /* Color definitions (for standard see qss.default) */ QColor mTextColorInbox; diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index 6495b95a3..f97351d25 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -406,35 +406,17 @@ QVariant RsMessageModel::sizeHintRole(int col) const QVariant RsMessageModel::authorRole(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const { -// if(column == COLUMN_THREAD_DATA) -// return QVariant(QString::fromStdString(fmpe.mAuthorId.toStdString())); - return QVariant(); } -// QVariant RsMessageModel::unreadRole(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const -// { -// if(column == COLUMN_THREAD_UNREAD) -// return QVariant(); -// lconst Rs::Msgs::MsgInfoSummary& fmpe,int column) const -// -// } - QVariant RsMessageModel::sortRole(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const { switch(column) { - case COLUMN_THREAD_DATE: return QVariant(QString::number(fmpe.ts)); // we should probably have leading zeroes here + case COLUMN_THREAD_DATE: return QVariant(QString::number(fmpe.ts)); // we should probably have leading zeroes here + + case COLUMN_THREAD_READ: return QVariant((bool)IS_MESSAGE_UNREAD(fmpe.msgflags)); - case COLUMN_THREAD_READ: return QVariant((bool)IS_MESSAGE_UNREAD(fmpe.msgflags)); -// case COLUMN_THREAD_AUTHOR: -// { -// QString str,comment ; -// QList icons; -// GxsIdDetails::MakeIdDesc(RsGxsId(fmpe.srcId), false, str, icons, comment,GxsIdDetails::ICON_TYPE_NONE); -// -// return QVariant(str); -// } case COLUMN_THREAD_STAR: return QVariant((fmpe.msgflags & RS_MSG_STAR)? 1:0); default: @@ -449,6 +431,7 @@ QVariant RsMessageModel::displayRole(const Rs::Msgs::MsgInfoSummary& fmpe,int co case COLUMN_THREAD_SUBJECT: return QVariant(QString::fromUtf8(fmpe.title.c_str())); case COLUMN_THREAD_ATTACHMENT:return QVariant(QString::number(fmpe.count)); + case COLUMN_THREAD_STAR: case COLUMN_THREAD_READ:return QVariant(); case COLUMN_THREAD_DATE:{ QDateTime qtime; diff --git a/retroshare-gui/src/gui/msgs/MessageModel.h b/retroshare-gui/src/gui/msgs/MessageModel.h index 8668bf05e..f971ecbfa 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.h +++ b/retroshare-gui/src/gui/msgs/MessageModel.h @@ -62,6 +62,7 @@ public: COLUMN_THREAD_TAGS = 0x06, COLUMN_THREAD_MSGID = 0x07, COLUMN_THREAD_NB_COLUMNS = 0x08, + COLUMN_THREAD_CONTENT = 0x08, }; enum QuickViewFilter { From dc24bb6f0319a013eb4c22ebff327c509d18deaf Mon Sep 17 00:00:00 2001 From: csoler Date: Thu, 21 Mar 2019 10:14:50 +0100 Subject: [PATCH 32/81] added save/restore current selection --- retroshare-gui/src/gui/MessagesDialog.cpp | 38 +++++++++++++++++++- retroshare-gui/src/gui/MessagesDialog.h | 10 +++++- retroshare-gui/src/gui/msgs/MessageModel.cpp | 25 +++++++------ retroshare-gui/src/gui/msgs/MessageModel.h | 2 ++ 4 files changed, 63 insertions(+), 12 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index e8e6a8aeb..5bac2d57b 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -144,9 +144,10 @@ MessagesDialog::MessagesDialog(QWidget *parent) mMessageProxyModel->setFilterRole(RsMessageModel::FilterRole); - ui.messageTreeWidget->setSortingEnabled(true); + ui.messageTreeWidget->setSortingEnabled(false); ui.messageTreeWidget->setItemDelegateForColumn(RsMessageModel::COLUMN_THREAD_AUTHOR,new GxsIdTreeItemDelegate()) ; ui.messageTreeWidget->setColumnHidden(RsMessageModel::COLUMN_THREAD_CONTENT,true); + ui.messageTreeWidget->setColumnHidden(RsMessageModel::COLUMN_THREAD_MSGID,true); RSElidedItemDelegate *itemDelegate = new RSElidedItemDelegate(this); itemDelegate->setSpacing(QSize(0, 2)); @@ -251,6 +252,9 @@ MessagesDialog::MessagesDialog(QWidget *parent) connect(NotifyQt::getInstance(), SIGNAL(messagesChanged()), mMessageModel, SLOT(updateMessages())); connect(NotifyQt::getInstance(), SIGNAL(messagesTagsChanged()), this, SLOT(messagesTagsChanged())); + connect(mMessageModel,SIGNAL(messagesAboutToLoad()),this,SLOT(preModelUpdate())); + connect(mMessageModel,SIGNAL(messagesLoaded()),this,SLOT(postModelUpdate())); + connect(ui.listWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(folderlistWidgetCustomPopupMenu(QPoint))); connect(ui.listWidget, SIGNAL(currentRowChanged(int)), this, SLOT(changeBox(int))); connect(ui.quickViewWidget, SIGNAL(currentRowChanged(int)), this, SLOT(changeQuickView(int))); @@ -271,10 +275,42 @@ MessagesDialog::MessagesDialog(QWidget *parent) connect(ui.messageTreeWidget->selectionModel(), SIGNAL(currentChanged(const QModelIndex&,const QModelIndex&)), this, SLOT(currentChanged(const QModelIndex&,const QModelIndex&))); } +void MessagesDialog::preModelUpdate() +{ + // save current selection + + mTmpSavedSelectedIds.clear(); + QModelIndexList qmil = ui.messageTreeWidget->selectionModel()->selectedRows(); + + foreach(const QModelIndex& m, qmil) + mTmpSavedSelectedIds.push_back(m.sibling(m.row(),RsMessageModel::COLUMN_THREAD_MSGID).data(RsMessageModel::MsgIdRole).toString()) ; + + std::cerr << "Pre-change: saving selection for " << mTmpSavedSelectedIds.size() << " indexes" << std::endl; +} + +void MessagesDialog::postModelUpdate() +{ + // restore selection + + std::cerr << "Post-change: restoring selection for " << mTmpSavedSelectedIds.size() << " indexes" << std::endl; + QItemSelection sel; + + foreach(const QString& s,mTmpSavedSelectedIds) + { + QModelIndex i = mMessageProxyModel->mapFromSource(mMessageModel->getIndexOfMessage(s.toStdString())); + + sel.select(i.sibling(i.row(),0),i.sibling(i.row(),RsMessageModel::COLUMN_THREAD_NB_COLUMNS-1)); + } + + ui.messageTreeWidget->selectionModel()->select(sel,QItemSelectionModel::SelectCurrent); +} + void MessagesDialog::sortColumn(int col,Qt::SortOrder so) { mMessageProxyModel->setSortingEnabled(true); + ui.messageTreeWidget->setSortingEnabled(true); mMessageProxyModel->sort(col,so); + ui.messageTreeWidget->setSortingEnabled(false); mMessageProxyModel->setSortingEnabled(false); } diff --git a/retroshare-gui/src/gui/MessagesDialog.h b/retroshare-gui/src/gui/MessagesDialog.h index 0e371585e..010f4a079 100644 --- a/retroshare-gui/src/gui/MessagesDialog.h +++ b/retroshare-gui/src/gui/MessagesDialog.h @@ -59,6 +59,10 @@ public: void setTextColorInbox(QColor color) { mTextColorInbox = color; } +signals: + void messagesAboutToLoad(); + void messagesLoaded(); + protected: bool eventFilter(QObject *obj, QEvent *ev); int getSelectedMessages(QList& mid); @@ -66,7 +70,9 @@ protected: public slots: //void insertMessages(); void messagesTagsChanged(); - + void preModelUpdate(); + void postModelUpdate(); + private slots: /** Create the context popup menu and it's submenus */ void messageTreeWidgetCustomPopupMenu(QPoint point); @@ -152,6 +158,8 @@ private: /** Qt Designer generated object */ Ui::MessagesDialog ui; + + QList mTmpSavedSelectedIds; }; #endif diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index f97351d25..839b5689d 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -547,9 +547,13 @@ void RsMessageModel::setMessages(const std::list& msgs endRemoveRows(); mMessages.clear(); + mMessagesMap.clear(); for(auto it(msgs.begin());it!=msgs.end();++it) + { + mMessagesMap[(*it).msgId] = mMessages.size(); mMessages.push_back(*it); + } // now update prow for all posts @@ -614,10 +618,14 @@ void RsMessageModel::getMessageSummaries(BoxName box,std::list msgs; getMessageSummaries(mCurrentBox,msgs); setMessages(msgs); + + emit messagesLoaded(); } static bool decreasing_time_comp(const std::pair& e1,const std::pair& e2) { return e2.first < e1.first ; } @@ -645,16 +653,15 @@ QModelIndex RsMessageModel::getIndexOfMessage(const std::string& mid) const { // Brutal search. This is not so nice, so dont call that in a loop! If too costly, we'll use a map. - for(uint32_t i=0;isecond >= mMessages.size()) + return QModelIndex(); - return QModelIndex(); + quintptr ref ; + convertMsgIndexToInternalId(it->second,ref); + + return createIndex(it->second,0,ref); } void RsMessageModel::debug_dump() const @@ -662,5 +669,3 @@ void RsMessageModel::debug_dump() const for(auto it(mMessages.begin());it!=mMessages.end();++it) std::cerr << "Id: " << it->msgId << ": from " << it->srcId << ": flags=" << it->msgflags << ": title=\"" << it->title << "\"" << std::endl; } - - diff --git a/retroshare-gui/src/gui/msgs/MessageModel.h b/retroshare-gui/src/gui/msgs/MessageModel.h index f971ecbfa..d6939fff1 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.h +++ b/retroshare-gui/src/gui/msgs/MessageModel.h @@ -153,6 +153,7 @@ public slots: signals: void messagesLoaded(); // emitted after the messages have been set. Can be used to updated the UI. + void messagesAboutToLoad(); private: bool passesFilter(const Rs::Msgs::MsgInfoSummary& fmpe,int column) const; @@ -184,4 +185,5 @@ private: FilterType mFilterType; std::vector mMessages; + std::map mMessagesMap; }; From b4ab766da914fe31459cec1ca482980b6dd22b97 Mon Sep 17 00:00:00 2001 From: csoler Date: Thu, 21 Mar 2019 22:39:32 +0100 Subject: [PATCH 33/81] factored some duplicate code in MessagesDialog.cpp --- retroshare-gui/src/gui/MessagesDialog.cpp | 13 ++++--------- retroshare-gui/src/gui/MessagesDialog.ui | 7 +++++-- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 5bac2d57b..947650af9 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -173,12 +173,12 @@ MessagesDialog::MessagesDialog(QWidget *parent) msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_DATE, fm.width("01/01/1970")*1.5); msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_READ, fm.width('0')*1.1); - QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_STAR, QHeaderView::Fixed); - QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_ATTACHMENT, QHeaderView::Fixed); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_STAR, QHeaderView::Interactive); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_ATTACHMENT, QHeaderView::Interactive); QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_SUBJECT, QHeaderView::Interactive); QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_AUTHOR, QHeaderView::Interactive); QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_DATE, QHeaderView::Interactive); - QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_READ, QHeaderView::Fixed); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_READ, QHeaderView::Interactive); ui.forwardmessageButton->setToolTip(tr("Forward selected Message")); ui.replyallmessageButton->setToolTip(tr("Reply to All")); @@ -196,7 +196,6 @@ MessagesDialog::MessagesDialog(QWidget *parent) // Set initial size of the splitter ui.listSplitter->setStretchFactor(0, 0); ui.listSplitter->setStretchFactor(1, 1); - /* add filter actions */ ui.filterLineEdit->addFilter(QIcon(), tr("Subject"), RsMessageModel::COLUMN_THREAD_SUBJECT, tr("Search Subject")); @@ -280,10 +279,7 @@ void MessagesDialog::preModelUpdate() // save current selection mTmpSavedSelectedIds.clear(); - QModelIndexList qmil = ui.messageTreeWidget->selectionModel()->selectedRows(); - - foreach(const QModelIndex& m, qmil) - mTmpSavedSelectedIds.push_back(m.sibling(m.row(),RsMessageModel::COLUMN_THREAD_MSGID).data(RsMessageModel::MsgIdRole).toString()) ; + getSelectedMessages(mTmpSavedSelectedIds); std::cerr << "Pre-change: saving selection for " << mTmpSavedSelectedIds.size() << " indexes" << std::endl; } @@ -298,7 +294,6 @@ void MessagesDialog::postModelUpdate() foreach(const QString& s,mTmpSavedSelectedIds) { QModelIndex i = mMessageProxyModel->mapFromSource(mMessageModel->getIndexOfMessage(s.toStdString())); - sel.select(i.sibling(i.row(),0),i.sibling(i.row(),RsMessageModel::COLUMN_THREAD_NB_COLUMNS-1)); } diff --git a/retroshare-gui/src/gui/MessagesDialog.ui b/retroshare-gui/src/gui/MessagesDialog.ui index 1ea2a904b..6d53864e6 100644 --- a/retroshare-gui/src/gui/MessagesDialog.ui +++ b/retroshare-gui/src/gui/MessagesDialog.ui @@ -454,7 +454,7 @@ Qt::NoFocus
- + :/icons/help_64.png:/icons/help_64.png @@ -745,6 +745,9 @@ false + + true +
@@ -850,8 +853,8 @@ listWidget - + From ae3f81a0c3da9aaaca50d3c733a5e8ce73761704 Mon Sep 17 00:00:00 2001 From: csoler Date: Thu, 21 Mar 2019 23:36:18 +0100 Subject: [PATCH 34/81] created a cache for default icons to avoid allocating them everytime we need them. Should save a lot of memory --- retroshare-gui/src/gui/gxs/GxsIdDetails.cpp | 51 ++++++++++++++++++++- retroshare-gui/src/gui/gxs/GxsIdDetails.h | 7 ++- 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/retroshare-gui/src/gui/gxs/GxsIdDetails.cpp b/retroshare-gui/src/gui/gxs/GxsIdDetails.cpp index 6168090eb..98f331730 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdDetails.cpp +++ b/retroshare-gui/src/gui/gxs/GxsIdDetails.cpp @@ -64,6 +64,12 @@ //const int kRecognTagType_Dev_Patcher = 4; //const int kRecognTagType_Dev_Developer = 5; +uint32_t GxsIdDetails::mImagesAllocated = 0; +time_t GxsIdDetails::mLastIconCacheCleaning = time(NULL); +std::map > GxsIdDetails::mDefaultIconCache ; + +#define ICON_CACHE_STORAGE_TIME 600 +#define DELAY_BETWEEN_ICON_CACHE_CLEANING 300 void ReputationItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { @@ -450,9 +456,50 @@ static bool findTagIcon(int tag_class, int /*tag_type*/, QIcon &icon) * Bring the source code from this adaptation: * http://francisshanahan.com/identicon5/test.html */ -QImage GxsIdDetails::makeDefaultIcon(const RsGxsId& id) +const QImage& GxsIdDetails::makeDefaultIcon(const RsGxsId& id) { - return drawIdentIcon(QString::fromStdString(id.toStdString()),64*3, true); + // We use a cache for images. QImage has its own smart pointer system, but it does not prevent + // the same image to be allocated many times. We do this using a cache. The cache is also cleaned-up + // on a regular time basis so as to get rid of unused images. + + time_t now = time(NULL); + + // cleanup the cache every 10 mins + + if(mLastIconCacheCleaning + DELAY_BETWEEN_ICON_CACHE_CLEANING < now) + { + std::cerr << "(II) Cleaning the icons cache." << std::endl; + int nb_deleted = 0; + + for(auto it(mDefaultIconCache.begin());it!=mDefaultIconCache.end();) + if(it->second.first + ICON_CACHE_STORAGE_TIME < now) + { + it = mDefaultIconCache.erase(it); + ++nb_deleted; + } + else + ++it; + + mLastIconCacheCleaning = now; + std::cerr << "(II) Removed " << nb_deleted << " unused icons. Cache contains " << mDefaultIconCache.size() << " icons"<< std::endl; + } + + // now look for the icon + + auto it = mDefaultIconCache.find(id); + + if(it != mDefaultIconCache.end()) + { + it->second.first = now; + return it->second.second; + } + + QImage image = drawIdentIcon(QString::fromStdString(id.toStdString()),64*3, true); + + mDefaultIconCache[id] = std::make_pair(now,image); + it = mDefaultIconCache.find(id); + + return it->second.second; } /** diff --git a/retroshare-gui/src/gui/gxs/GxsIdDetails.h b/retroshare-gui/src/gui/gxs/GxsIdDetails.h index 8c6c8edac..e506f5cf3 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdDetails.h +++ b/retroshare-gui/src/gui/gxs/GxsIdDetails.h @@ -101,7 +101,7 @@ public: static void GenerateCombinedPixmap(QPixmap &pixmap, const QList &icons, int iconSize); //static QImage makeDefaultIcon(const RsGxsId& id); - static QImage makeDefaultIcon(const RsGxsId& id); + static const QImage& makeDefaultIcon(const RsGxsId& id); /* Processing */ static void enableProcess(bool enable); @@ -155,6 +155,11 @@ protected: /* Pending data */ QMap mPendingData; QMap::iterator mPendingDataIterator; + + static uint32_t mImagesAllocated; + static std::map > mDefaultIconCache; + static time_t mLastIconCacheCleaning; + int mCheckTimerId; int mProcessDisableCount; From b6c7afe989a1e34eef79184077f545c174e09080 Mon Sep 17 00:00:00 2001 From: defnax Date: Fri, 22 Mar 2019 11:13:07 +0100 Subject: [PATCH 35/81] Added for posted links group icons --- libretroshare/src/retroshare/rsposted.h | 1 + libretroshare/src/rsitems/rsposteditems.cc | 48 ++++++++++++++++++- libretroshare/src/rsitems/rsposteditems.h | 6 ++- libretroshare/src/services/p3posted.cc | 13 +++-- .../src/gui/Posted/PostedDialog.cpp | 28 +++++++---- .../src/gui/Posted/PostedGroupDialog.cpp | 45 +++++++++++++---- .../src/gui/Posted/PostedGroupDialog.h | 3 ++ .../src/gui/feeds/PostedGroupItem.cpp | 17 +++++-- 8 files changed, 130 insertions(+), 31 deletions(-) diff --git a/libretroshare/src/retroshare/rsposted.h b/libretroshare/src/retroshare/rsposted.h index 02edb47c8..a42f06c40 100644 --- a/libretroshare/src/retroshare/rsposted.h +++ b/libretroshare/src/retroshare/rsposted.h @@ -44,6 +44,7 @@ class RsPostedGroup RsGroupMetaData mMeta; std::string mDescription; + RsGxsImage mGroupImage; }; diff --git a/libretroshare/src/rsitems/rsposteditems.cc b/libretroshare/src/rsitems/rsposteditems.cc index 7f7adac4d..23fb6633b 100644 --- a/libretroshare/src/rsitems/rsposteditems.cc +++ b/libretroshare/src/rsitems/rsposteditems.cc @@ -44,7 +44,15 @@ void RsGxsPostedPostItem::serial_process(RsGenericSerializer::SerializeJob j,RsG void RsGxsPostedGroupItem::serial_process(RsGenericSerializer::SerializeJob j,RsGenericSerializer::SerializeContext& ctx) { - RsTypeSerializer::serial_process(j,ctx,TLV_TYPE_STR_DESCR ,mGroup.mDescription,"mGroup.mDescription") ; + RsTypeSerializer::serial_process(j,ctx,TLV_TYPE_STR_DESCR ,mDescription,"mDescription") ; + + if(j == RsGenericSerializer::DESERIALIZE && ctx.mOffset == ctx.mSize) + return ; + + if((j == RsGenericSerializer::SIZE_ESTIMATE || j == RsGenericSerializer::SERIALIZE) && mGroupImage.empty()) + return ; + + RsTypeSerializer::serial_process(j,ctx,mGroupImage,"mGroupImage") ; } RsItem *RsGxsPostedSerialiser::create_item(uint16_t service_id,uint8_t item_subtype) const @@ -109,6 +117,42 @@ void RsGxsPostedPostItem::clear() } void RsGxsPostedGroupItem::clear() { - mGroup.mDescription.clear(); + mDescription.clear(); + mGroupImage.TlvClear(); } +bool RsGxsPostedGroupItem::fromPostedGroup(RsPostedGroup &group, bool moveImage) +{ + clear(); + meta = group.mMeta; + mDescription = group.mDescription; + + if (moveImage) + { + mGroupImage.binData.bin_data = group.mGroupImage.mData; + mGroupImage.binData.bin_len = group.mGroupImage.mSize; + group.mGroupImage.shallowClear(); + } + else + { + mGroupImage.binData.setBinData(group.mGroupImage.mData, group.mGroupImage.mSize); + } + return true; +} + +bool RsGxsPostedGroupItem::toPostedGroup(RsPostedGroup &group, bool moveImage) +{ + group.mMeta = meta; + group.mDescription = mDescription; + if (moveImage) + { + group.mGroupImage.take((uint8_t *) mGroupImage.binData.bin_data, mGroupImage.binData.bin_len); + // mGroupImage doesn't have a ShallowClear at the moment! + mGroupImage.binData.TlvShallowClear(); + } + else + { + group.mGroupImage.copy((uint8_t *) mGroupImage.binData.bin_data, mGroupImage.binData.bin_len); + } + return true; +} diff --git a/libretroshare/src/rsitems/rsposteditems.h b/libretroshare/src/rsitems/rsposteditems.h index ef88289b5..910471c19 100644 --- a/libretroshare/src/rsitems/rsposteditems.h +++ b/libretroshare/src/rsitems/rsposteditems.h @@ -42,8 +42,12 @@ public: virtual void serial_process(RsGenericSerializer::SerializeJob j,RsGenericSerializer::SerializeContext& ctx); - RsPostedGroup mGroup; + // use conversion functions to transform: + bool fromPostedGroup(RsPostedGroup &group, bool moveImage); + bool toPostedGroup(RsPostedGroup &group, bool moveImage); + std::string mDescription; + RsTlvImage mGroupImage; }; diff --git a/libretroshare/src/services/p3posted.cc b/libretroshare/src/services/p3posted.cc index d50c0624c..1a1efe0b6 100644 --- a/libretroshare/src/services/p3posted.cc +++ b/libretroshare/src/services/p3posted.cc @@ -79,9 +79,8 @@ bool p3Posted::getGroupData(const uint32_t &token, std::vector &g RsGxsPostedGroupItem* item = dynamic_cast(*vit); if (item) { - RsPostedGroup grp = item->mGroup; - item->mGroup.mMeta = item->meta; - grp.mMeta = item->mGroup.mMeta; + RsPostedGroup grp; + item->toPostedGroup(grp, true); delete item; groups.push_back(grp); } @@ -265,8 +264,8 @@ bool p3Posted::createGroup(uint32_t &token, RsPostedGroup &group) std::cerr << "p3Posted::createGroup()" << std::endl; RsGxsPostedGroupItem* grpItem = new RsGxsPostedGroupItem(); - grpItem->mGroup = group; - grpItem->meta = group.mMeta; + grpItem->fromPostedGroup(group, true); + RsGenExchange::publishGroup(token, grpItem); return true; @@ -278,8 +277,8 @@ bool p3Posted::updateGroup(uint32_t &token, RsPostedGroup &group) std::cerr << "p3Posted::updateGroup()" << std::endl; RsGxsPostedGroupItem* grpItem = new RsGxsPostedGroupItem(); - grpItem->mGroup = group; - grpItem->meta = group.mMeta; + grpItem->fromPostedGroup(group, true); + RsGenExchange::updateGroup(token, grpItem); return true; diff --git a/retroshare-gui/src/gui/Posted/PostedDialog.cpp b/retroshare-gui/src/gui/Posted/PostedDialog.cpp index 320618cab..d4c288732 100644 --- a/retroshare-gui/src/gui/Posted/PostedDialog.cpp +++ b/retroshare-gui/src/gui/Posted/PostedDialog.cpp @@ -35,6 +35,7 @@ public: PostedGroupInfoData() : RsUserdata() {} public: + QMap mIcon; QMap mDescription; }; @@ -102,15 +103,15 @@ QString PostedDialog::icon(IconType type) case ICON_NEW: return ":/icons/png/add.png"; case ICON_YOUR_GROUP: - return ":/icons/png/feedreader.png"; - case ICON_SUBSCRIBED_GROUP: - return ":/icons/png/feed-subscribed.png"; - case ICON_POPULAR_GROUP: - return ":/icons/png/feed-popular.png"; - case ICON_OTHER_GROUP: - return ":/icons/png/feed-other.png"; - case ICON_DEFAULT: return ""; + case ICON_SUBSCRIBED_GROUP: + return ""; + case ICON_POPULAR_GROUP: + return ""; + case ICON_OTHER_GROUP: + return ""; + case ICON_DEFAULT: + return ":/icons/png/posted.png"; } return ""; @@ -159,6 +160,12 @@ void PostedDialog::loadGroupSummaryToken(const uint32_t &token, std::listmIcon[group.mMeta.mGroupId] = image; + } if (!group.mDescription.empty()) { postedData->mDescription[group.mMeta.mGroupId] = QString::fromUtf8(group.mDescription.c_str()); @@ -181,4 +188,9 @@ void PostedDialog::groupInfoToGroupItemInfo(const RsGroupMetaData &groupInfo, Gr if (descriptionIt != postedData->mDescription.end()) { groupItemInfo.description = descriptionIt.value(); } + + QMap::const_iterator iconIt = postedData->mIcon.find(groupInfo.mGroupId); + if (iconIt != postedData->mIcon.end()) { + groupItemInfo.icon = iconIt.value(); + } } diff --git a/retroshare-gui/src/gui/Posted/PostedGroupDialog.cpp b/retroshare-gui/src/gui/Posted/PostedGroupDialog.cpp index 031ce7da0..6fcb14024 100644 --- a/retroshare-gui/src/gui/Posted/PostedGroupDialog.cpp +++ b/retroshare-gui/src/gui/Posted/PostedGroupDialog.cpp @@ -17,6 +17,7 @@ * along with this program. If not, see . * * * *******************************************************************************/ +#include #include "PostedGroupDialog.h" @@ -25,7 +26,7 @@ const uint32_t PostedCreateEnabledFlags = ( GXS_GROUP_FLAGS_NAME | - // GXS_GROUP_FLAGS_ICON | + GXS_GROUP_FLAGS_ICON | GXS_GROUP_FLAGS_DESCRIPTION | GXS_GROUP_FLAGS_DISTRIBUTION | // GXS_GROUP_FLAGS_PUBLISHSIGN | @@ -90,14 +91,31 @@ QPixmap PostedGroupDialog::serviceImage() return QPixmap(":/icons/png/posted.png"); } +void PostedGroupDialog::preparePostedGroup(RsPostedGroup &group, const RsGroupMetaData &meta) +{ + group.mMeta = meta; + group.mDescription = getDescription().toUtf8().constData(); + + QPixmap pixmap = getLogo(); + + if (!pixmap.isNull()) { + QByteArray ba; + QBuffer buffer(&ba); + + buffer.open(QIODevice::WriteOnly); + pixmap.save(&buffer, "PNG"); // writes image into ba in PNG format + + group.mGroupImage.copy((uint8_t *) ba.data(), ba.size()); + } else { + group.mGroupImage.clear(); + } +} + bool PostedGroupDialog::service_CreateGroup(uint32_t &token, const RsGroupMetaData &meta) { // Specific Function. RsPostedGroup grp; - grp.mMeta = meta; - grp.mDescription = getDescription().toStdString(); - std::cerr << "PostedGroupDialog::service_CreateGroup() storing to Queue"; - std::cerr << std::endl; + preparePostedGroup(grp, meta); rsPosted->createGroup(token, grp); @@ -107,8 +125,7 @@ bool PostedGroupDialog::service_CreateGroup(uint32_t &token, const RsGroupMetaDa bool PostedGroupDialog::service_EditGroup(uint32_t &token, RsGroupMetaData &editedMeta) { RsPostedGroup grp; - grp.mMeta = editedMeta; - grp.mDescription = getDescription().toUtf8().constData(); + preparePostedGroup(grp, editedMeta); std::cerr << "PostedGroupDialog::service_EditGroup() submitting changes"; std::cerr << std::endl; @@ -140,8 +157,18 @@ bool PostedGroupDialog::service_loadGroup(uint32_t token, Mode /*mode*/, RsGroup std::cerr << "PostedGroupDialog::service_loadGroup() Unfinished Loading"; std::cerr << std::endl; - groupMetaData = groups[0].mMeta; - description = QString::fromUtf8(groups[0].mDescription.c_str()); + const RsPostedGroup &group = groups[0]; + groupMetaData = group.mMeta; + description = QString::fromUtf8(group.mDescription.c_str()); + + if (group.mGroupImage.mData) { + QPixmap pixmap; + if (pixmap.loadFromData(group.mGroupImage.mData, group.mGroupImage.mSize, "PNG")) { + setLogo(pixmap); + } + } else { + setLogo(QPixmap(":/icons/png/posted.png")); + } return true; } diff --git a/retroshare-gui/src/gui/Posted/PostedGroupDialog.h b/retroshare-gui/src/gui/Posted/PostedGroupDialog.h index c96da3ebf..c0d860b96 100644 --- a/retroshare-gui/src/gui/Posted/PostedGroupDialog.h +++ b/retroshare-gui/src/gui/Posted/PostedGroupDialog.h @@ -39,6 +39,9 @@ protected: virtual bool service_CreateGroup(uint32_t &token, const RsGroupMetaData &meta); virtual bool service_loadGroup(uint32_t token, Mode mode, RsGroupMetaData& groupMetaData, QString &description); virtual bool service_EditGroup(uint32_t &token, RsGroupMetaData &editedMeta); + +private: + void preparePostedGroup(RsPostedGroup &group, const RsGroupMetaData &meta); }; #endif diff --git a/retroshare-gui/src/gui/feeds/PostedGroupItem.cpp b/retroshare-gui/src/gui/feeds/PostedGroupItem.cpp index 97c97c195..542e97a11 100644 --- a/retroshare-gui/src/gui/feeds/PostedGroupItem.cpp +++ b/retroshare-gui/src/gui/feeds/PostedGroupItem.cpp @@ -134,14 +134,23 @@ void PostedGroupItem::fill() // ui->nameLabel->setText(groupName()); ui->descLabel->setText(QString::fromUtf8(mGroup.mDescription.c_str())); - - //TODO - nice icon for subscribed group - if (IS_GROUP_PUBLISHER(mGroup.mMeta.mSubscribeFlags)) { - ui->logoLabel->setPixmap(QPixmap(":/images/posted_64.png")); + + if (mGroup.mGroupImage.mData != NULL) { + QPixmap postedImage; + postedImage.loadFromData(mGroup.mGroupImage.mData, mGroup.mGroupImage.mSize, "PNG"); + ui->logoLabel->setPixmap(QPixmap(postedImage)); } else { ui->logoLabel->setPixmap(QPixmap(":/images/posted_64.png")); } + + //TODO - nice icon for subscribed group +// if (IS_GROUP_PUBLISHER(mGroup.mMeta.mSubscribeFlags)) { +// ui->logoLabel->setPixmap(QPixmap(":/images/posted_64.png")); +// } else { +// ui->logoLabel->setPixmap(QPixmap(":/images/posted_64.png")); +// } + if (IS_GROUP_SUBSCRIBED(mGroup.mMeta.mSubscribeFlags)) { ui->subscribeButton->setEnabled(false); } else { From 8ee86ea0da26f53ff82cce93693292d9e9ad7232 Mon Sep 17 00:00:00 2001 From: defnax Date: Fri, 22 Mar 2019 22:31:06 +0100 Subject: [PATCH 36/81] Fixed stylesheet color when its a new posted message --- retroshare-gui/src/gui/qss/stylesheet/Standard.qss | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/retroshare-gui/src/gui/qss/stylesheet/Standard.qss b/retroshare-gui/src/gui/qss/stylesheet/Standard.qss index a6089ab59..f0f098b83 100644 --- a/retroshare-gui/src/gui/qss/stylesheet/Standard.qss +++ b/retroshare-gui/src/gui/qss/stylesheet/Standard.qss @@ -889,10 +889,14 @@ PostedItem QFrame#voteFrame { background: #f8f9fa; } -PostedItem QFrame#mainFrame{ +PostedItem QFrame#mainFrame [new=false]{ background: white; } +PostedItem > QFrame#mainFrame[new=true] { + background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #F0F8FD, stop:0.8 #E6F2FD, stop: 0.81 #E6F2FD, stop: 1 #D2E7FD); +} + PostedItem QFrame#frame_picture{ background: white; } From 2ad641d908af23ff7644f2667638ed877e8c09a2 Mon Sep 17 00:00:00 2001 From: csoler Date: Sat, 23 Mar 2019 22:59:37 +0100 Subject: [PATCH 37/81] added a test for QImage::isDetached() in cache to solve the problem of whether a cache image is still used or not --- retroshare-gui/src/gui/gxs/GxsIdDetails.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/retroshare-gui/src/gui/gxs/GxsIdDetails.cpp b/retroshare-gui/src/gui/gxs/GxsIdDetails.cpp index 98f331730..abcf8ef71 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdDetails.cpp +++ b/retroshare-gui/src/gui/gxs/GxsIdDetails.cpp @@ -472,7 +472,7 @@ const QImage& GxsIdDetails::makeDefaultIcon(const RsGxsId& id) int nb_deleted = 0; for(auto it(mDefaultIconCache.begin());it!=mDefaultIconCache.end();) - if(it->second.first + ICON_CACHE_STORAGE_TIME < now) + if(it->second.first + ICON_CACHE_STORAGE_TIME < now && it->second.second.isDetached()) { it = mDefaultIconCache.erase(it); ++nb_deleted; From 364c3917ac9061a7855b49fc60717de3a8f7e6de Mon Sep 17 00:00:00 2001 From: csoler Date: Sat, 23 Mar 2019 23:48:39 +0100 Subject: [PATCH 38/81] attempt to fix MacOS compilation --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index aebcc220b..63fb2a569 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,6 +22,7 @@ before_install: - if [ $TRAVIS_OS_NAME == osx ]; then brew install ccach; export PATH="/usr/local/opt/ccache/libexec:$PATH" ; fi - if [ $TRAVIS_OS_NAME == osx ]; then brew install qt5; fi - if [ $TRAVIS_OS_NAME == osx ]; then brew link --force qt5 ; fi + - if [ $TRAVIS_OS_NAME == osx ]; then brew doctor; fi - if [ $TRAVIS_OS_NAME == osx ]; then brew install openssl miniupnpc libmicrohttpd sqlcipher xapian; fi - if [ $TRAVIS_OS_NAME == osx ]; then brew install p7zip; fi - if [ $TRAVIS_OS_NAME == osx ]; then npm install -g appdmg; fi From 32729adb5e52a29127a8c471152dea154f2e7be9 Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 24 Mar 2019 12:56:43 +0100 Subject: [PATCH 39/81] attempt #2 to fix MacOS compilation --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 63fb2a569..2ac7a3a05 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,7 +10,7 @@ matrix: sudo: required compiler: gcc - os: osx - osx_image: xcode9.3 + osx_image: xcode10.1 compiler: clang sudo: false From 63ca76167b8bd0732fe39c4e68e9e30d16643bcc Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 24 Mar 2019 13:04:23 +0100 Subject: [PATCH 40/81] removed brew-doctor command --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 2ac7a3a05..9a08c22d5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,7 +22,6 @@ before_install: - if [ $TRAVIS_OS_NAME == osx ]; then brew install ccach; export PATH="/usr/local/opt/ccache/libexec:$PATH" ; fi - if [ $TRAVIS_OS_NAME == osx ]; then brew install qt5; fi - if [ $TRAVIS_OS_NAME == osx ]; then brew link --force qt5 ; fi - - if [ $TRAVIS_OS_NAME == osx ]; then brew doctor; fi - if [ $TRAVIS_OS_NAME == osx ]; then brew install openssl miniupnpc libmicrohttpd sqlcipher xapian; fi - if [ $TRAVIS_OS_NAME == osx ]; then brew install p7zip; fi - if [ $TRAVIS_OS_NAME == osx ]; then npm install -g appdmg; fi From e6d86b5b6f98bb7eb6469c906b043981d90d7f94 Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 24 Mar 2019 16:20:12 +0100 Subject: [PATCH 41/81] switched macOS version to 10.14 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 9a08c22d5..f1bddf0ac 100644 --- a/.travis.yml +++ b/.travis.yml @@ -48,7 +48,7 @@ addons: before_script: - if [ $TRAVIS_OS_NAME == linux ]; then qmake QMAKE_CC=$CC QMAKE_CXX=$CXX; fi - - if [ $TRAVIS_OS_NAME == osx ]; then qmake QMAKE_CC=$CC QMAKE_CXX=$CXX CONFIG+=rs_macos10.13 CONFIG+=no_retroshare_plugins INCLUDEPATH+=/usr/local/opt/openssl/include/ INCLUDEPATH+=/usr/local/Cellar/sqlcipher/4.0.1/include INCLUDEPATH+=/usr/local/Cellar/libmicrohttpd/0.9.62_1/include QMAKE_LIBDIR+=/usr/local/opt/openssl/lib/ QMAKE_LIBDIR+=/usr/local/Cellar/libmicrohttpd/0.9.62_1/lib QMAKE_LIBDIR+=/usr/local/Cellar/sqlcipher/4.0.1/lib; fi + - if [ $TRAVIS_OS_NAME == osx ]; then qmake QMAKE_CC=$CC QMAKE_CXX=$CXX CONFIG+=rs_macos10.14 CONFIG+=no_retroshare_plugins INCLUDEPATH+=/usr/local/opt/openssl/include/ INCLUDEPATH+=/usr/local/Cellar/sqlcipher/4.0.1/include INCLUDEPATH+=/usr/local/Cellar/libmicrohttpd/0.9.62_1/include QMAKE_LIBDIR+=/usr/local/opt/openssl/lib/ QMAKE_LIBDIR+=/usr/local/Cellar/libmicrohttpd/0.9.62_1/lib QMAKE_LIBDIR+=/usr/local/Cellar/sqlcipher/4.0.1/lib; fi script: - if [ $TRAVIS_OS_NAME == osx ] && [ "${COVERITY_SCAN_BRANCH}" != 1 ]; then make -j4; fi From 1d09269e42b959da6580f4f8a221ee054c20de72 Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 24 Mar 2019 16:22:17 +0100 Subject: [PATCH 42/81] switched macOS version to 10.14 --- retroshare.pri | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/retroshare.pri b/retroshare.pri index 24059540a..bfa51618b 100644 --- a/retroshare.pri +++ b/retroshare.pri @@ -155,6 +155,7 @@ rs_macos10.9:CONFIG -= rs_macos10.11 rs_macos10.10:CONFIG -= rs_macos10.11 rs_macos10.12:CONFIG -= rs_macos10.11 rs_macos10.13:CONFIG -= rs_macos10.11 +rs_macos10.14:CONFIG -= rs_macos10.11 # To enable JSON API append the following assignation to qmake command line # "CONFIG+=rs_jsonapi" @@ -644,6 +645,14 @@ macx-* { QMAKE_CXXFLAGS += -Wno-nullability-completeness QMAKE_CFLAGS += -Wno-nullability-completeness } + rs_macos10.14 { + message(***retroshare.pri: Set Target and SDK to MacOS 10.14 ) + QMAKE_MACOSX_DEPLOYMENT_TARGET=10.14 + QMAKE_MAC_SDK = macosx10.14 + QMAKE_CXXFLAGS += -Wno-nullability-completeness + QMAKE_CFLAGS += -Wno-nullability-completeness + } + message(***retroshare.pri:MacOSX) From db4f8f18b8407a1ab8e9981a2a9a838eda484407 Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 24 Mar 2019 18:58:18 +0100 Subject: [PATCH 43/81] fixed sqlcipher version on OS 10.14 --- retroshare.pri | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/retroshare.pri b/retroshare.pri index bfa51618b..3d25a335f 100644 --- a/retroshare.pri +++ b/retroshare.pri @@ -665,10 +665,10 @@ macx-* { BIN_DIR += "/Applications/Xcode.app/Contents/Developer/usr/bin" INC_DIR += "/usr/local/Cellar/miniupnpc/2.1/include" INC_DIR += "/usr/local/Cellar/libmicrohttpd/0.9.62_1/include" - INC_DIR += "/usr/local/Cellar/sqlcipher/4.0.1/include" + INC_DIR += "/usr/local/Cellar/sqlcipher/4.1.0/include" LIB_DIR += "/usr/local/opt/openssl/lib/" LIB_DIR += "/usr/local/Cellar/libmicrohttpd/0.9.62_1/lib" - LIB_DIR += "/usr/local/Cellar/sqlcipher/4.0.1/lib" + LIB_DIR += "/usr/local/Cellar/sqlcipher/4.1.0/lib" LIB_DIR += "/usr/local/Cellar/miniupnpc/2.1/lib" CONFIG += c++11 INCLUDEPATH += "/usr/local/include" From e76ad99f3bba4cbf27778c6273131e6f76eea0b7 Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 24 Mar 2019 19:59:43 +0100 Subject: [PATCH 44/81] removed explicit size on channel feed buttons that causes unbalanced items in high DPI screens --- .../src/gui/feeds/GxsChannelPostItem.ui | 34 ++----------------- 1 file changed, 2 insertions(+), 32 deletions(-) diff --git a/retroshare-gui/src/gui/feeds/GxsChannelPostItem.ui b/retroshare-gui/src/gui/feeds/GxsChannelPostItem.ui index 1d72a0693..cd6594674 100644 --- a/retroshare-gui/src/gui/feeds/GxsChannelPostItem.ui +++ b/retroshare-gui/src/gui/feeds/GxsChannelPostItem.ui @@ -6,8 +6,8 @@ 0 0 - 1052 - 338 + 1140 + 342
@@ -360,12 +360,6 @@ 0 - - - 24 - 16777215 - - Qt::NoFocus @@ -386,12 +380,6 @@ 0 - - - 24 - 16777215 - - Qt::NoFocus @@ -412,12 +400,6 @@ 0 - - - 24 - 16777215 - - Qt::NoFocus @@ -438,12 +420,6 @@ 0 - - - 24 - 16777215 - - Qt::NoFocus @@ -464,12 +440,6 @@ 0 - - - 24 - 16777215 - - Qt::NoFocus From 1f6589e68e93ad195d67288e7cffefac5b45db62 Mon Sep 17 00:00:00 2001 From: defnax Date: Tue, 26 Mar 2019 00:01:52 +0100 Subject: [PATCH 45/81] attempting to fix layout isssues Attempting to fix issues, layout and spacing --- retroshare-gui/src/gui/Posted/PostedItem.cpp | 15 +++++- retroshare-gui/src/gui/Posted/PostedItem.ui | 54 ++++++------------- .../src/gui/Posted/PostedListWidget.cpp | 5 ++ 3 files changed, 34 insertions(+), 40 deletions(-) diff --git a/retroshare-gui/src/gui/Posted/PostedItem.cpp b/retroshare-gui/src/gui/Posted/PostedItem.cpp index 4a38c2a5a..d107b660d 100644 --- a/retroshare-gui/src/gui/Posted/PostedItem.cpp +++ b/retroshare-gui/src/gui/Posted/PostedItem.cpp @@ -109,7 +109,18 @@ void PostedItem::setup() QAction *CopyLinkAction = new QAction(QIcon(""),tr("Copy RetroShare Link"), this); connect(CopyLinkAction, SIGNAL(triggered()), this, SLOT(copyMessageLink())); - + + + int S = QFontMetricsF(font()).height() ; + + ui->voteUpButton->setIconSize(QSize(S*1.5,S*1.5)); + ui->voteDownButton->setIconSize(QSize(S*1.5,S*1.5)); + ui->commentButton->setIconSize(QSize(S*1.5,S*1.5)); + ui->expandButton->setIconSize(QSize(S*1.5,S*1.5)); + ui->notesButton->setIconSize(QSize(S*1.5,S*1.5)); + ui->readButton->setIconSize(QSize(S*1.5,S*1.5)); + ui->shareButton->setIconSize(QSize(S*1.5,S*1.5)); + QMenu *menu = new QMenu(); menu->addAction(CopyLinkAction); ui->shareButton->setMenu(menu); @@ -290,7 +301,7 @@ void PostedItem::fill() urlstr += QString(" "); QString siteurl = url.scheme() + "://" + url.host(); - sitestr = QString(" %2 ").arg(siteurl).arg(siteurl); + sitestr = QString(" %2 ").arg(siteurl).arg(siteurl); ui->titleLabel->setText(urlstr); }else diff --git a/retroshare-gui/src/gui/Posted/PostedItem.ui b/retroshare-gui/src/gui/Posted/PostedItem.ui index af284a7a0..d991b99ef 100644 --- a/retroshare-gui/src/gui/Posted/PostedItem.ui +++ b/retroshare-gui/src/gui/Posted/PostedItem.ui @@ -67,6 +67,12 @@ + + + 37 + 0 + + @@ -100,12 +106,6 @@ 0 - - - 24 - 24 - - Vote up @@ -116,12 +116,6 @@ :/images/up-arrow.png:/images/up-arrow.png - - - 16 - 16 - - true @@ -161,12 +155,6 @@ :/images/down-arrow.png:/images/down-arrow.png - - - 16 - 16 - - true @@ -198,6 +186,12 @@ + + + 0 + 0 + + 100 @@ -312,7 +306,7 @@ - 3 + 5 0 @@ -371,25 +365,6 @@ - - - - - 0 - 0 - - - - - 75 - true - - - - Site - - - @@ -426,6 +401,9 @@ + + 6 + 0 diff --git a/retroshare-gui/src/gui/Posted/PostedListWidget.cpp b/retroshare-gui/src/gui/Posted/PostedListWidget.cpp index be8e0ad69..5c0dd3061 100644 --- a/retroshare-gui/src/gui/Posted/PostedListWidget.cpp +++ b/retroshare-gui/src/gui/Posted/PostedListWidget.cpp @@ -65,6 +65,11 @@ PostedListWidget::PostedListWidget(const RsGxsGroupId &postedId, QWidget *parent /* fill in the available OwnIds for signing */ ui->idChooser->loadIds(IDCHOOSER_ID_REQUIRED, RsGxsId()); + + int S = QFontMetricsF(font()).height() ; + + ui->submitPostButton->setIconSize(QSize(S*1.5,S*1.5)); + ui->comboBox->setIconSize(QSize(S*1.5,S*1.5)); connect(ui->submitPostButton, SIGNAL(clicked()), this, SLOT(newPost())); From d38ad9791115d316ae68884abbca3d5baf1e92f0 Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 26 Mar 2019 10:05:54 +0100 Subject: [PATCH 46/81] changed order of operation between init and processSettngs because it was messing up the msg list --- retroshare-gui/src/gui/MessagesDialog.cpp | 100 ++++++++++++---------- retroshare-gui/src/gui/MessagesDialog.h | 6 +- 2 files changed, 59 insertions(+), 47 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 947650af9..7f6220b4e 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -144,7 +144,6 @@ MessagesDialog::MessagesDialog(QWidget *parent) mMessageProxyModel->setFilterRole(RsMessageModel::FilterRole); - ui.messageTreeWidget->setSortingEnabled(false); ui.messageTreeWidget->setItemDelegateForColumn(RsMessageModel::COLUMN_THREAD_AUTHOR,new GxsIdTreeItemDelegate()) ; ui.messageTreeWidget->setColumnHidden(RsMessageModel::COLUMN_THREAD_CONTENT,true); ui.messageTreeWidget->setColumnHidden(RsMessageModel::COLUMN_THREAD_MSGID,true); @@ -166,19 +165,13 @@ MessagesDialog::MessagesDialog(QWidget *parent) /* Set initial section sizes */ QHeaderView * msgwheader = ui.messageTreeWidget->header () ; - msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_STAR, fm.width('0')*1.1); - msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_ATTACHMENT, fm.width('0')*1.1); msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_SUBJECT, fm.width("You have a message")*3.0); - msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_AUTHOR, fm.width("[Retroshare]")*1.5); - msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_DATE, fm.width("01/01/1970")*1.5); - msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_READ, fm.width('0')*1.1); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_AUTHOR, fm.width("[Retroshare]")*1.1); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_DATE, fm.width("01/01/1970")*1.1); - QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_STAR, QHeaderView::Interactive); - QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_ATTACHMENT, QHeaderView::Interactive); QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_SUBJECT, QHeaderView::Interactive); QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_AUTHOR, QHeaderView::Interactive); QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_DATE, QHeaderView::Interactive); - QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_READ, QHeaderView::Interactive); ui.forwardmessageButton->setToolTip(tr("Forward selected Message")); ui.replyallmessageButton->setToolTip(tr("Reply to All")); @@ -192,18 +185,18 @@ MessagesDialog::MessagesDialog(QWidget *parent) viewmenu->addAction(ui.actionTextBesideIcon); viewmenu->addAction(ui.actionIconOnly); ui.viewtoolButton->setMenu(viewmenu); - + // Set initial size of the splitter ui.listSplitter->setStretchFactor(0, 0); ui.listSplitter->setStretchFactor(1, 1); /* add filter actions */ - ui.filterLineEdit->addFilter(QIcon(), tr("Subject"), RsMessageModel::COLUMN_THREAD_SUBJECT, tr("Search Subject")); - ui.filterLineEdit->addFilter(QIcon(), tr("From"), RsMessageModel::COLUMN_THREAD_AUTHOR, tr("Search From")); - ui.filterLineEdit->addFilter(QIcon(), tr("Date"), RsMessageModel::COLUMN_THREAD_DATE, tr("Search Date")); - ui.filterLineEdit->addFilter(QIcon(), tr("Content"), RsMessageModel::COLUMN_THREAD_CONTENT, tr("Search Content")); - ui.filterLineEdit->addFilter(QIcon(), tr("Tags"), RsMessageModel::COLUMN_THREAD_TAGS, tr("Search Tags")); - ui.filterLineEdit->addFilter(QIcon(), tr("Attachments"), RsMessageModel::COLUMN_THREAD_ATTACHMENT, tr("Search Attachments")); + ui.filterLineEdit->addFilter(QIcon(), tr("Subject"), RsMessageModel::COLUMN_THREAD_SUBJECT, tr("Search Subject")); + ui.filterLineEdit->addFilter(QIcon(), tr("From"), RsMessageModel::COLUMN_THREAD_AUTHOR, tr("Search From")); + ui.filterLineEdit->addFilter(QIcon(), tr("Date"), RsMessageModel::COLUMN_THREAD_DATE, tr("Search Date")); + ui.filterLineEdit->addFilter(QIcon(), tr("Content"), RsMessageModel::COLUMN_THREAD_CONTENT, tr("Search Content")); + ui.filterLineEdit->addFilter(QIcon(), tr("Tags"), RsMessageModel::COLUMN_THREAD_TAGS, tr("Search Tags")); + ui.filterLineEdit->addFilter(QIcon(), tr("Attachments"), RsMessageModel::COLUMN_THREAD_ATTACHMENT,tr("Search Attachments")); //setting default filter by column as subject ui.filterLineEdit->setCurrentFilter(RsMessageModel::COLUMN_THREAD_SUBJECT); @@ -211,9 +204,24 @@ MessagesDialog::MessagesDialog(QWidget *parent) // load settings processSettings(true); + /////////////////////////////////////////////////////////////////////////////////////// + // Post "load settings" actions (which makes sure they are not affected by settings) // + /////////////////////////////////////////////////////////////////////////////////////// + + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_STAR, fm.width('0')*1.5); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_ATTACHMENT, fm.width('0')*1.5); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_READ, fm.width('0')*1.5); + + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_STAR, QHeaderView::Fixed); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_ATTACHMENT, QHeaderView::Fixed); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_READ, QHeaderView::Fixed); + + ui.messageTreeWidget->setSortingEnabled(true); + /* Set header sizes for the fixed columns and resize modes, must be set after processSettings */ msgwheader->setStretchLastSection(false); + // fill folder list updateMessageSummaryList(); ui.listWidget->setCurrentRow(ROW_INBOX); @@ -303,9 +311,9 @@ void MessagesDialog::postModelUpdate() void MessagesDialog::sortColumn(int col,Qt::SortOrder so) { mMessageProxyModel->setSortingEnabled(true); - ui.messageTreeWidget->setSortingEnabled(true); + //ui.messageTreeWidget->setSortingEnabled(true); mMessageProxyModel->sort(col,so); - ui.messageTreeWidget->setSortingEnabled(false); + //ui.messageTreeWidget->setSortingEnabled(false); mMessageProxyModel->setSortingEnabled(false); } @@ -512,20 +520,20 @@ int MessagesDialog::getSelectedMsgCount (QList *items, QListmapToSource(proxy_index); + + switch (proxy_index.column()) { case RsMessageModel::COLUMN_THREAD_READ: { - mMessageModel->setMsgReadStatus(index, !isMessageRead(index)); - insertMsgTxtAndFiles(index); + mMessageModel->setMsgReadStatus(real_index, !isMessageRead(proxy_index)); + insertMsgTxtAndFiles(proxy_index); updateMessageSummaryList(); return; } case RsMessageModel::COLUMN_THREAD_STAR: { - mMessageModel->setMsgStar(index, !hasMessageStar(index)); + mMessageModel->setMsgStar(real_index, !hasMessageStar(proxy_index)); return; } } // show current message directly - insertMsgTxtAndFiles(index); + insertMsgTxtAndFiles(proxy_index); } // double click in messageTreeWidget -void MessagesDialog::doubleClicked(const QModelIndex& index) +void MessagesDialog::doubleClicked(const QModelIndex& proxy_index) { /* activate row */ - clicked(index); + clicked(proxy_index); std::string cid; std::string mid; @@ -922,20 +932,22 @@ void MessagesDialog::markWithStar(bool checked) -void MessagesDialog::insertMsgTxtAndFiles(const QModelIndex& index) +void MessagesDialog::insertMsgTxtAndFiles(const QModelIndex& proxy_index) { /* get its Ids */ std::string cid; std::string mid; - if(!index.isValid()) + QModelIndex real_index = mMessageProxyModel->mapToSource(proxy_index); + + if(!real_index.isValid()) { mCurrMsgId.clear(); msgWidget->fill(mCurrMsgId); updateInterface(); return; } - mid = index.data(RsMessageModel::MsgIdRole).toString().toStdString(); + mid = real_index.data(RsMessageModel::MsgIdRole).toString().toStdString(); /* Save the Data.... for later */ @@ -950,12 +962,12 @@ void MessagesDialog::insertMsgTxtAndFiles(const QModelIndex& index) if (msgInfo.msgflags & RS_MSG_NEW) // set always to read or unread { if (!bSetToReadOnActive) // set locally to unread - mMessageModel->setMsgReadStatus(index, false); + mMessageModel->setMsgReadStatus(real_index, false); else - mMessageModel->setMsgReadStatus(index, true); + mMessageModel->setMsgReadStatus(real_index, true); } else if ((msgInfo.msgflags & RS_MSG_UNREAD_BY_USER) && bSetToReadOnActive) // set to read - mMessageModel->setMsgReadStatus(index, true); + mMessageModel->setMsgReadStatus(real_index, true); updateInterface(); updateMessageSummaryList(); @@ -1138,12 +1150,12 @@ void MessagesDialog::updateMessageSummaryList() break; } } - + int listrow = ui.listWidget->currentRow(); QString textTotal; - switch (listrow) + switch (listrow) { case ROW_INBOX: textTotal = tr("Total:") + " " + QString::number(inboxCount); diff --git a/retroshare-gui/src/gui/MessagesDialog.h b/retroshare-gui/src/gui/MessagesDialog.h index 010f4a079..9eeb577f0 100644 --- a/retroshare-gui/src/gui/MessagesDialog.h +++ b/retroshare-gui/src/gui/MessagesDialog.h @@ -85,7 +85,7 @@ private slots: void updateCurrentMessage(); void clicked(const QModelIndex&); void doubleClicked(const QModelIndex&); - void currentChanged(const QModelIndex& new_index, const QModelIndex &old_index); + void currentChanged(const QModelIndex& new_proxy_index, const QModelIndex &old_proxy_index); void newmessage(); void openAsWindow(); @@ -119,13 +119,13 @@ private: void connectActions(); void updateMessageSummaryList(); - void insertMsgTxtAndFiles(const QModelIndex& index = QModelIndex()); + void insertMsgTxtAndFiles(const QModelIndex& proxy_index = QModelIndex()); bool getCurrentMsg(std::string &cid, std::string &mid); void setMsgAsReadUnread(const QList &items, bool read); int getSelectedMsgCount (QList *items, QList *itemsRead, QList *itemsUnread, QList *itemsStar); - bool isMessageRead(const QModelIndex &index); + bool isMessageRead(const QModelIndex &real_index); bool hasMessageStar(const QModelIndex &index); void processSettings(bool load); From 90995f16ce366c17dcc74c8082603ef1fa586ff1 Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 26 Mar 2019 10:25:54 +0100 Subject: [PATCH 47/81] fixed filter/sort by author name --- retroshare-gui/src/gui/MessagesDialog.cpp | 13 +++-- .../src/gui/gxs/GxsIdTreeWidgetItem.h | 51 ++++++++++++------- retroshare-gui/src/gui/msgs/MessageModel.cpp | 10 +++- 3 files changed, 49 insertions(+), 25 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 7f6220b4e..40c828449 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -121,9 +121,6 @@ MessagesDialog::MessagesDialog(QWidget *parent) ui.actionIconOnly->setData(Qt::ToolButtonIconOnly); ui.actionTextUnderIcon->setData(Qt::ToolButtonTextUnderIcon); - connect(ui.filterLineEdit, SIGNAL(textChanged(QString)), this, SLOT(filterChanged(QString))); - connect(ui.filterLineEdit, SIGNAL(filterChanged(int)), this, SLOT(filterColumnChanged(int))); - msgWidget = new MessageWidget(true, this); ui.msgLayout->addWidget(msgWidget); @@ -145,15 +142,11 @@ MessagesDialog::MessagesDialog(QWidget *parent) mMessageProxyModel->setFilterRole(RsMessageModel::FilterRole); ui.messageTreeWidget->setItemDelegateForColumn(RsMessageModel::COLUMN_THREAD_AUTHOR,new GxsIdTreeItemDelegate()) ; - ui.messageTreeWidget->setColumnHidden(RsMessageModel::COLUMN_THREAD_CONTENT,true); - ui.messageTreeWidget->setColumnHidden(RsMessageModel::COLUMN_THREAD_MSGID,true); RSElidedItemDelegate *itemDelegate = new RSElidedItemDelegate(this); itemDelegate->setSpacing(QSize(0, 2)); ui.messageTreeWidget->setItemDelegate(itemDelegate); - //ui.messageTreeWidget->sortByColumn(COLUMN_DATA, Qt::DescendingOrder); - // workaround for Qt bug, should be solved in next Qt release 4.7.0 // http://bugreports.qt.nokia.com/browse/QTBUG-8270 QShortcut *Shortcut = new QShortcut(QKeySequence (Qt::Key_Delete), ui.messageTreeWidget, 0, 0, Qt::WidgetShortcut); @@ -208,6 +201,9 @@ MessagesDialog::MessagesDialog(QWidget *parent) // Post "load settings" actions (which makes sure they are not affected by settings) // /////////////////////////////////////////////////////////////////////////////////////// + ui.messageTreeWidget->setColumnHidden(RsMessageModel::COLUMN_THREAD_CONTENT,true); + ui.messageTreeWidget->setColumnHidden(RsMessageModel::COLUMN_THREAD_MSGID,true); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_STAR, fm.width('0')*1.5); msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_ATTACHMENT, fm.width('0')*1.5); msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_READ, fm.width('0')*1.5); @@ -259,6 +255,9 @@ MessagesDialog::MessagesDialog(QWidget *parent) connect(NotifyQt::getInstance(), SIGNAL(messagesChanged()), mMessageModel, SLOT(updateMessages())); connect(NotifyQt::getInstance(), SIGNAL(messagesTagsChanged()), this, SLOT(messagesTagsChanged())); + connect(ui.filterLineEdit, SIGNAL(textChanged(QString)), this, SLOT(filterChanged(QString))); + connect(ui.filterLineEdit, SIGNAL(filterChanged(int)), this, SLOT(filterColumnChanged(int))); + connect(mMessageModel,SIGNAL(messagesAboutToLoad()),this,SLOT(preModelUpdate())); connect(mMessageModel,SIGNAL(messagesLoaded()),this,SLOT(postModelUpdate())); diff --git a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h index 8a8452a34..02eff1d32 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h +++ b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h @@ -138,33 +138,23 @@ public: RsGxsId id(index.data(Qt::UserRole).toString().toStdString()); QString str; - QList icons; QString comment; QFontMetricsF fm(painter->font()); float f = fm.height(); QIcon icon ; - - if(rsPeers->isFriend(RsPeerId(id))) // horrible trick because some widgets still use locations as IDs (e.g. messages) - { - str = QString::fromUtf8(rsPeers->getPeerName(RsPeerId(id)).c_str()) ; - } - else if(!GxsIdDetails::MakeIdDesc(id, true, str, icons, comment,GxsIdDetails::ICON_TYPE_AVATAR)) - { + if(! computeNameIconAndComment(id,str,icon,comment)) if(mReloadPeriod > 3) - { + { str = tr("[Unknown]"); - icon = QIcon(); - } - else - { + icon = QIcon(); + } + else + { icon = GxsIdDetails::getLoadingIcon(id); launchAsyncLoading(); - } - } - else - icon = *icons.begin(); + } QPixmap pix = icon.pixmap(r.size()); const QPoint p = QPoint(r.height()/2.0, (r.height() - pix.height())/2); @@ -185,6 +175,33 @@ public: QTimer::singleShot(1000,this,SLOT(reload())); } + static bool computeName(const RsGxsId& id,QString& name) + { + QList icons; + QString comment; + + if(rsPeers->isFriend(RsPeerId(id))) // horrible trick because some widgets still use locations as IDs (e.g. messages) + name = QString::fromUtf8(rsPeers->getPeerName(RsPeerId(id)).c_str()) ; + else if(!GxsIdDetails::MakeIdDesc(id, false, name, icons, comment,GxsIdDetails::ICON_TYPE_NONE)) + return false; + + return true; + } + + static bool computeNameIconAndComment(const RsGxsId& id,QString& name,QIcon& icon,QString& comment) + { + QList icons; + + if(rsPeers->isFriend(RsPeerId(id))) // horrible trick because some widgets still use locations as IDs (e.g. messages) + name = QString::fromUtf8(rsPeers->getPeerName(RsPeerId(id)).c_str()) ; + else if(!GxsIdDetails::MakeIdDesc(id, true, name, icons, comment,GxsIdDetails::ICON_TYPE_AVATAR)) + return false; + else + icon = *icons.begin(); + + return true; + } + private slots: void reload() { mLoading=false; emit commitData(NULL) ; } diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index 839b5689d..2ee805ea8 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -30,6 +30,7 @@ #include "util/HandleRichText.h" #include "util/DateTime.h" #include "gui/gxs/GxsIdDetails.h" +#include "gui/gxs/GxsIdTreeWidgetItem.h" #include "MessageModel.h" #include "retroshare/rsexpr.h" #include "retroshare/rsmsgs.h" @@ -300,7 +301,8 @@ bool RsMessageModel::passesFilter(const Rs::Msgs::MsgInfoSummary& fmpe,int colum case FILTER_TYPE_SUBJECT: s = displayRole(fmpe,COLUMN_THREAD_SUBJECT).toString(); break; - case FILTER_TYPE_FROM: + case FILTER_TYPE_FROM: s = sortRole(fmpe.COLUMN_THREAD_AUTHOR).toString(); + break; case FILTER_TYPE_DATE: s = displayRole(fmpe,COLUMN_THREAD_DATE).toString(); break; case FILTER_TYPE_CONTENT: { @@ -419,6 +421,12 @@ QVariant RsMessageModel::sortRole(const Rs::Msgs::MsgInfoSummary& fmpe,int colum case COLUMN_THREAD_STAR: return QVariant((fmpe.msgflags & RS_MSG_STAR)? 1:0); + case COLUMN_THREAD_AUTHOR:{ + QString name; + + if(GxsIdTreeItemDelegate::computeName(RsGxsId(fmpe.srcId.toStdString()),name)) + return name; + } default: return displayRole(fmpe,column); } From 5820364b0dcab308f143bf0bdf1aef6500d6b8cb Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 26 Mar 2019 11:21:31 +0100 Subject: [PATCH 48/81] fixed sorting --- retroshare-gui/src/gui/MessagesDialog.cpp | 20 ++++++++++++++------ retroshare-gui/src/gui/msgs/MessageModel.cpp | 11 ++++++++++- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 40c828449..7ae9c4e3e 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -134,13 +134,13 @@ MessagesDialog::MessagesDialog(QWidget *parent) mMessageProxyModel->setSortRole(RsMessageModel::SortRole); mMessageProxyModel->setDynamicSortFilter(false); mMessageProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); + mMessageProxyModel->setFilterRole(RsMessageModel::FilterRole); + mMessageProxyModel->setFilterRegExp(QRegExp(RsMessageModel::FilterString)); ui.messageTreeWidget->setModel(mMessageProxyModel); changeBox(0); // set to inbox - mMessageProxyModel->setFilterRole(RsMessageModel::FilterRole); - ui.messageTreeWidget->setItemDelegateForColumn(RsMessageModel::COLUMN_THREAD_AUTHOR,new GxsIdTreeItemDelegate()) ; RSElidedItemDelegate *itemDelegate = new RSElidedItemDelegate(this); @@ -1042,6 +1042,8 @@ void MessagesDialog::buttonStyle() setToolbarButtonStyle((Qt::ToolButtonStyle) dynamic_cast(sender())->data().toInt()); } + + void MessagesDialog::filterChanged(const QString& text) { QStringList items = text.split(' ',QString::SkipEmptyParts); @@ -1051,15 +1053,18 @@ void MessagesDialog::filterChanged(const QString& text) switch(ui.filterLineEdit->currentFilter()) { case RsMessageModel::COLUMN_THREAD_SUBJECT: f = RsMessageModel::FILTER_TYPE_SUBJECT ; break; - case RsMessageModel::COLUMN_THREAD_AUTHOR: f = RsMessageModel::FILTER_TYPE_FROM ; break; + case RsMessageModel::COLUMN_THREAD_AUTHOR: f = RsMessageModel::FILTER_TYPE_FROM ; break; case RsMessageModel::COLUMN_THREAD_DATE: f = RsMessageModel::FILTER_TYPE_DATE ; break; case RsMessageModel::COLUMN_THREAD_CONTENT: f = RsMessageModel::FILTER_TYPE_CONTENT ; break; case RsMessageModel::COLUMN_THREAD_TAGS: f = RsMessageModel::FILTER_TYPE_TAGS ; break; - case RsMessageModel::COLUMN_THREAD_ATTACHMENT: f = RsMessageModel::FILTER_TYPE_ATTACHMENTS ; break; + case RsMessageModel::COLUMN_THREAD_ATTACHMENT: f = RsMessageModel::FILTER_TYPE_ATTACHMENTS ; break; default:break; } mMessageModel->setFilter(f,items); + mMessageProxyModel->setFilterRegExp(QRegExp(RsMessageModel::FilterString)); + + QCoreApplication::processEvents(); } void MessagesDialog::filterColumnChanged(int column) @@ -1072,19 +1077,22 @@ void MessagesDialog::filterColumnChanged(int column) switch(column) { case RsMessageModel::COLUMN_THREAD_SUBJECT: f = RsMessageModel::FILTER_TYPE_SUBJECT ; break; - case RsMessageModel::COLUMN_THREAD_AUTHOR: f = RsMessageModel::FILTER_TYPE_FROM ; break; + case RsMessageModel::COLUMN_THREAD_AUTHOR: f = RsMessageModel::FILTER_TYPE_FROM ; break; case RsMessageModel::COLUMN_THREAD_DATE: f = RsMessageModel::FILTER_TYPE_DATE ; break; case RsMessageModel::COLUMN_THREAD_CONTENT: f = RsMessageModel::FILTER_TYPE_CONTENT ; break; case RsMessageModel::COLUMN_THREAD_TAGS: f = RsMessageModel::FILTER_TYPE_TAGS ; break; - case RsMessageModel::COLUMN_THREAD_ATTACHMENT: f = RsMessageModel::FILTER_TYPE_ATTACHMENTS ; break; + case RsMessageModel::COLUMN_THREAD_ATTACHMENT: f = RsMessageModel::FILTER_TYPE_ATTACHMENTS ; break; default:break; } QStringList items = ui.filterLineEdit->text().split(' ',QString::SkipEmptyParts); mMessageModel->setFilter(f,items); + mMessageProxyModel->setFilterRegExp(QRegExp(RsMessageModel::FilterString)); // save index Settings->setValueToGroup("MessageDialog", "filterColumn", column); + + QCoreApplication::processEvents(); } void MessagesDialog::updateMessageSummaryList() diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index 2ee805ea8..cbfbc81bd 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -301,7 +301,9 @@ bool RsMessageModel::passesFilter(const Rs::Msgs::MsgInfoSummary& fmpe,int colum case FILTER_TYPE_SUBJECT: s = displayRole(fmpe,COLUMN_THREAD_SUBJECT).toString(); break; - case FILTER_TYPE_FROM: s = sortRole(fmpe.COLUMN_THREAD_AUTHOR).toString(); + case FILTER_TYPE_FROM: s = sortRole(fmpe,COLUMN_THREAD_AUTHOR).toString(); + if(s.isNull()) + passes_strings = false; break; case FILTER_TYPE_DATE: s = displayRole(fmpe,COLUMN_THREAD_DATE).toString(); break; @@ -335,6 +337,8 @@ bool RsMessageModel::passesFilter(const Rs::Msgs::MsgInfoSummary& fmpe,int colum || (mQuickViewFilter==QUICK_VIEW_STARRED && (fmpe.msgflags & RS_MSG_STAR)) || (mQuickViewFilter==QUICK_VIEW_SYSTEM && (fmpe.msgflags & RS_MSG_SYSTEM)); + std::cerr << "Passes filter: type=" << mFilterType << " s=\"" << s.toStdString() << "\" strings:" << passes_strings << " quick_view:" << passes_quick_view << std::endl; + return passes_quick_view && passes_strings; } @@ -357,6 +361,11 @@ uint32_t RsMessageModel::updateFilterStatus(ForumModelIndex i,int column,const Q void RsMessageModel::setFilter(FilterType filter_type, const QStringList& strings) { + std::cerr << "Setting filter to filter_type=" << int(filter_type) << " and strings to " ; + foreach(const QString& str,strings) + std::cerr << "\"" << str.toStdString() << "\" " ; + std::cerr << std::endl; + preMods(); mFilterType = filter_type; From 1d4934b71e7e56e917ff6927665f6bcfa947c731 Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 26 Mar 2019 11:32:43 +0100 Subject: [PATCH 49/81] fixed QuickView filtering --- retroshare-gui/src/gui/MessagesDialog.cpp | 6 ++++-- retroshare-gui/src/gui/msgs/MessageModel.cpp | 7 ++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 7ae9c4e3e..8b5b923ca 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -810,6 +810,8 @@ void MessagesDialog::changeQuickView(int newrow) f = RsMessageModel::QuickViewFilter( (int)RsMessageModel::QUICK_VIEW_USER + newrow - 0x07); } mMessageModel->setQuickViewFilter(f); + mMessageProxyModel->setFilterRegExp(QRegExp(RsMessageModel::FilterString)); // this triggers the update of the proxy model + insertMsgTxtAndFiles(ui.messageTreeWidget->currentIndex()); } @@ -1062,7 +1064,7 @@ void MessagesDialog::filterChanged(const QString& text) } mMessageModel->setFilter(f,items); - mMessageProxyModel->setFilterRegExp(QRegExp(RsMessageModel::FilterString)); + mMessageProxyModel->setFilterRegExp(QRegExp(RsMessageModel::FilterString)); // this triggers the update of the proxy model QCoreApplication::processEvents(); } @@ -1087,7 +1089,7 @@ void MessagesDialog::filterColumnChanged(int column) QStringList items = ui.filterLineEdit->text().split(' ',QString::SkipEmptyParts); mMessageModel->setFilter(f,items); - mMessageProxyModel->setFilterRegExp(QRegExp(RsMessageModel::FilterString)); + mMessageProxyModel->setFilterRegExp(QRegExp(RsMessageModel::FilterString)); // this triggers the update of the proxy model // save index Settings->setValueToGroup("MessageDialog", "filterColumn", column); diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index cbfbc81bd..3f30b2342 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -337,7 +337,10 @@ bool RsMessageModel::passesFilter(const Rs::Msgs::MsgInfoSummary& fmpe,int colum || (mQuickViewFilter==QUICK_VIEW_STARRED && (fmpe.msgflags & RS_MSG_STAR)) || (mQuickViewFilter==QUICK_VIEW_SYSTEM && (fmpe.msgflags & RS_MSG_SYSTEM)); - std::cerr << "Passes filter: type=" << mFilterType << " s=\"" << s.toStdString() << "\" strings:" << passes_strings << " quick_view:" << passes_quick_view << std::endl; + std::cerr << "Passes filter: type=" << mFilterType << " s=\"" << s.toStdString() + << "MsgFlags=" << fmpe.msgflags << " msgtags=" ; + foreach(uint32_t i,fmpe.msgtags) std::cerr << i << " " ; + std::cerr << "\" strings:" << passes_strings << " quick_view:" << passes_quick_view << std::endl; return passes_quick_view && passes_strings; } @@ -598,6 +601,8 @@ void RsMessageModel::setQuickViewFilter(QuickViewFilter fn) { if(fn != mQuickViewFilter) { + std::cerr << "Changing new quickview filter to " << fn << std::endl; + preMods(); mQuickViewFilter = fn ; postMods(); From f404962b51823b7ce850c77822df15a730318f7b Mon Sep 17 00:00:00 2001 From: csoler Date: Tue, 26 Mar 2019 11:47:11 +0100 Subject: [PATCH 50/81] fixed notification display for msgs --- retroshare-gui/src/gui/MessagesDialog.cpp | 2 +- retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h | 11 ++++++++++- retroshare-gui/src/gui/msgs/MessageWidget.cpp | 4 ++-- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 8b5b923ca..16f7b80b3 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -215,7 +215,7 @@ MessagesDialog::MessagesDialog(QWidget *parent) ui.messageTreeWidget->setSortingEnabled(true); /* Set header sizes for the fixed columns and resize modes, must be set after processSettings */ - msgwheader->setStretchLastSection(false); + msgwheader->setStretchLastSection(true); // fill folder list diff --git a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h index 02eff1d32..6e910b63b 100644 --- a/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h +++ b/retroshare-gui/src/gui/gxs/GxsIdTreeWidgetItem.h @@ -144,7 +144,13 @@ public: float f = fm.height(); QIcon icon ; - if(! computeNameIconAndComment(id,str,icon,comment)) + + if(id.isNull()) + { + str = tr("[Notification]"); + icon = QIcon(":/icons/logo_128.png"); + } + else if(! computeNameIconAndComment(id,str,icon,comment)) if(mReloadPeriod > 3) { str = tr("[Unknown]"); @@ -193,7 +199,10 @@ public: QList icons; if(rsPeers->isFriend(RsPeerId(id))) // horrible trick because some widgets still use locations as IDs (e.g. messages) + { name = QString::fromUtf8(rsPeers->getPeerName(RsPeerId(id)).c_str()) ; + icon = QIcon(":/icons/avatar_128.png"); + } else if(!GxsIdDetails::MakeIdDesc(id, true, name, icons, comment,GxsIdDetails::ICON_TYPE_AVATAR)) return false; else diff --git a/retroshare-gui/src/gui/msgs/MessageWidget.cpp b/retroshare-gui/src/gui/msgs/MessageWidget.cpp index 5294c1d26..d0a59e14b 100644 --- a/retroshare-gui/src/gui/msgs/MessageWidget.cpp +++ b/retroshare-gui/src/gui/msgs/MessageWidget.cpp @@ -600,8 +600,8 @@ void MessageWidget::fill(const std::string &msgId) link = RetroShareLink::createMessage(msgInfo.rspeerid_srcId, ""); } - if ((msgInfo.msgflags & RS_MSG_SYSTEM) && msgInfo.rspeerid_srcId == ownId) { - ui.fromText->setText("RetroShare"); + if (((msgInfo.msgflags & RS_MSG_SYSTEM) && msgInfo.rspeerid_srcId == ownId) || msgInfo.rspeerid_srcId.isNull()) { + ui.fromText->setText("[Notification]"); if (toolButtonReply) toolButtonReply->setEnabled(false); } else { ui.fromText->setText(link.toHtml()); From b65883921457f3983bad4e33a79b715e19dbf391 Mon Sep 17 00:00:00 2001 From: defnax Date: Tue, 26 Mar 2019 18:35:10 +0100 Subject: [PATCH 51/81] Removed the dummy buttons & added sorting the comments treewidget via combobox --- .../src/gui/gxs/GxsCommentDialog.cpp | 28 ++++++ retroshare-gui/src/gui/gxs/GxsCommentDialog.h | 1 + .../src/gui/gxs/GxsCommentDialog.ui | 93 ++++++++++--------- .../src/gui/gxs/GxsCommentTreeWidget.cpp | 7 ++ .../src/gui/gxs/GxsCommentTreeWidget.h | 4 + retroshare-gui/src/gui/gxs/GxsGroupDialog.ui | 2 +- .../src/gui/qss/stylesheet/Standard.qss | 8 +- 7 files changed, 99 insertions(+), 44 deletions(-) diff --git a/retroshare-gui/src/gui/gxs/GxsCommentDialog.cpp b/retroshare-gui/src/gui/gxs/GxsCommentDialog.cpp index 99f363f8d..57fc7031b 100644 --- a/retroshare-gui/src/gui/gxs/GxsCommentDialog.cpp +++ b/retroshare-gui/src/gui/gxs/GxsCommentDialog.cpp @@ -49,6 +49,15 @@ GxsCommentDialog::GxsCommentDialog(QWidget *parent, RsTokenService *token_servic connect(ui->refreshButton, SIGNAL(clicked()), this, SLOT(refresh())); connect(ui->idChooser, SIGNAL(currentIndexChanged( int )), this, SLOT(voterSelectionChanged( int ))); connect(ui->idChooser, SIGNAL(idsLoaded()), this, SLOT(idChooserReady())); + + connect(ui->sortBox, SIGNAL(currentIndexChanged(int)), this, SLOT(sortComments(int))); + + // default sort method "HOT". + ui->treeWidget->sortByColumn(4, Qt::DescendingOrder); + + int S = QFontMetricsF(font()).height() ; + + ui->sortBox->setIconSize(QSize(S*1.5,S*1.5)); } GxsCommentDialog::~GxsCommentDialog() @@ -141,3 +150,22 @@ void GxsCommentDialog::setCommentHeader(QWidget *header) ui->notesBrowser->setPlainText(QString::fromStdString(mCurrentPost.mNotes)); #endif } + +void GxsCommentDialog::sortComments(int i) +{ + + switch(i) + { + default: + case 0: + ui->treeWidget->sortByColumn(4, Qt::DescendingOrder); + break; + case 1: + ui->treeWidget->sortByColumn(2, Qt::DescendingOrder); + break; + case 2: + ui->treeWidget->sortByColumn(3, Qt::DescendingOrder); + break; + } + +} diff --git a/retroshare-gui/src/gui/gxs/GxsCommentDialog.h b/retroshare-gui/src/gui/gxs/GxsCommentDialog.h index 1a6999880..82d2fdbd1 100644 --- a/retroshare-gui/src/gui/gxs/GxsCommentDialog.h +++ b/retroshare-gui/src/gui/gxs/GxsCommentDialog.h @@ -45,6 +45,7 @@ private slots: void refresh(); void idChooserReady(); void voterSelectionChanged( int index ); + void sortComments(int); private: RsGxsGroupId mGrpId; diff --git a/retroshare-gui/src/gui/gxs/GxsCommentDialog.ui b/retroshare-gui/src/gui/gxs/GxsCommentDialog.ui index 7961136c0..6bf6b1112 100644 --- a/retroshare-gui/src/gui/gxs/GxsCommentDialog.ui +++ b/retroshare-gui/src/gui/gxs/GxsCommentDialog.ui @@ -13,8 +13,8 @@ Form - - + + @@ -24,59 +24,63 @@ - 9 + 1 1 + + 1 + 1 - + - - - Hot + + + <html><head/><body><p><span style=" font-family:'-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol'; font-size:14px; color:#24292e; background-color:#ffffff;">sort by</span></p></body></html> - - true + + - - true - - - - - - - New - - - true - - - true - - - - - - - Top - - - true - - - false - - - true + + + 24 + 24 + + + + Hot + + + + :/icons/png/flame.png:/icons/png/flame.png + + + + + New + + + + :/icons/png/new.png:/icons/png/new.png + + + + + Top + + + + :/icons/png/top.png:/icons/png/top.png + + @@ -111,8 +115,11 @@ - + + + true + Comment @@ -164,6 +171,8 @@
gui/gxs/GxsCommentTreeWidget.h
- + + + diff --git a/retroshare-gui/src/gui/gxs/GxsCommentTreeWidget.cpp b/retroshare-gui/src/gui/gxs/GxsCommentTreeWidget.cpp index dc1734556..a66b93b34 100644 --- a/retroshare-gui/src/gui/gxs/GxsCommentTreeWidget.cpp +++ b/retroshare-gui/src/gui/gxs/GxsCommentTreeWidget.cpp @@ -31,6 +31,7 @@ #include "gui/gxs/GxsCommentTreeWidget.h" #include "gui/gxs/GxsCreateCommentDialog.h" #include "gui/gxs/GxsIdTreeWidgetItem.h" +#include "gui/common/RSTreeWidgetItem.h" #include @@ -45,6 +46,7 @@ #define PCITEM_COLUMN_PARENTID 8 #define PCITEM_COLUMN_AUTHORID 9 +#define ROLE_SORT Qt::UserRole + 1 #define GXSCOMMENTS_LOADTHREAD 1 @@ -139,6 +141,9 @@ GxsCommentTreeWidget::GxsCommentTreeWidget(QWidget *parent) setWordWrap(true); setItemDelegateForColumn(PCITEM_COLUMN_COMMENT,new MultiLinesCommentDelegate(QFontMetricsF(font()))) ; + + commentsRole = new RSTreeWidgetItemCompareRole; + commentsRole->setRole(PCITEM_COLUMN_DATE, ROLE_SORT); // QFont font = QFont("ARIAL", 10); // font.setBold(true); @@ -537,6 +542,8 @@ void GxsCommentTreeWidget::service_loadThread(const uint32_t &token) text = qtime.toString("yyyy-MM-dd hh:mm:ss") ; item->setText(PCITEM_COLUMN_DATE, text) ; item->setToolTip(PCITEM_COLUMN_DATE, text) ; + item->setData(PCITEM_COLUMN_DATE, ROLE_SORT, comment.mMeta.mPublishTs); + } text = QString::fromUtf8(comment.mComment.c_str()); diff --git a/retroshare-gui/src/gui/gxs/GxsCommentTreeWidget.h b/retroshare-gui/src/gui/gxs/GxsCommentTreeWidget.h index a7e25df6e..a1977ab93 100644 --- a/retroshare-gui/src/gui/gxs/GxsCommentTreeWidget.h +++ b/retroshare-gui/src/gui/gxs/GxsCommentTreeWidget.h @@ -27,6 +27,8 @@ #include #include +class RSTreeWidgetItemCompareRole; + class GxsCommentTreeWidget : public QTreeWidget, public TokenResponse { Q_OBJECT @@ -96,6 +98,8 @@ protected: std::map mLoadingMap; std::multimap mPendingInsertMap; + + RSTreeWidgetItemCompareRole *commentsRole; TokenQueue *mTokenQueue; RsTokenService *mRsTokenService; diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.ui b/retroshare-gui/src/gui/gxs/GxsGroupDialog.ui index 3cd4a50c6..9c6a9b662 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.ui +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.ui @@ -7,7 +7,7 @@ 0 0 600 - 736 + 633 diff --git a/retroshare-gui/src/gui/qss/stylesheet/Standard.qss b/retroshare-gui/src/gui/qss/stylesheet/Standard.qss index f0f098b83..a12d62db6 100644 --- a/retroshare-gui/src/gui/qss/stylesheet/Standard.qss +++ b/retroshare-gui/src/gui/qss/stylesheet/Standard.qss @@ -914,4 +914,10 @@ PostedItem QToolButton#commentButton, QPushButton#shareButton, QToolButton#notes font-size: 12px; color: #878a8c; font-weight: bold; -} \ No newline at end of file +} + +GxsCommentDialog QComboBox#sortBox { + font: bold; + font-size: 12px; + color: #0099cc; +} From d2d336ee01d80a054c344162709bc5b0a1b56f91 Mon Sep 17 00:00:00 2001 From: hunbernd Date: Tue, 26 Mar 2019 20:54:36 +0100 Subject: [PATCH 52/81] Made the restbed compile command better --- libretroshare/src/libretroshare.pro | 38 ++++++++++------------------- 1 file changed, 13 insertions(+), 25 deletions(-) diff --git a/libretroshare/src/libretroshare.pro b/libretroshare/src/libretroshare.pro index ca03a8a0c..1c77fa4d7 100644 --- a/libretroshare/src/libretroshare.pro +++ b/libretroshare/src/libretroshare.pro @@ -862,36 +862,24 @@ rs_jsonapi { no_rs_cross_compiling { DUMMYRESTBEDINPUT = FORCE + CMAKE_GENERATOR_OVERRIDE="" + win32-g++:CMAKE_GENERATOR_OVERRIDE="-G \"MSYS Makefiles\"" genrestbedlib.name = Generating libresbed. genrestbedlib.input = DUMMYRESTBEDINPUT genrestbedlib.output = $$clean_path($${RESTBED_BUILD_PATH}/librestbed.a) genrestbedlib.CONFIG += target_predeps combine genrestbedlib.variable_out = PRE_TARGETDEPS - win32-g++ { - genrestbedlib.commands = \ - cd $${RS_SRC_PATH} && \ - git submodule update --init --recommend-shallow supportlibs/restbed && \ - cd $${RESTBED_SRC_PATH} && \ - git submodule update --init --recommend-shallow dependency/asio && \ - git submodule update --init --recommend-shallow dependency/catch && \ - git submodule update --init --recommend-shallow dependency/kashmir && \ - mkdir -p $${RESTBED_BUILD_PATH}; cd $${RESTBED_BUILD_PATH} && \ - cmake -DCMAKE_CXX_COMPILER=$$QMAKE_CXX -G \"MSYS Makefiles\" -DBUILD_SSL=OFF \ - -DCMAKE_INSTALL_PREFIX=. -B. -H$$shell_path($${RESTBED_SRC_PATH}) && \ - make - } else { - genrestbedlib.commands = \ - cd $${RS_SRC_PATH};\ - git submodule update --init --recommend-shallow supportlibs/restbed;\ - cd $${RESTBED_SRC_PATH};\ - git submodule update --init --recommend-shallow dependency/asio;\ - git submodule update --init --recommend-shallow dependency/catch;\ - git submodule update --init --recommend-shallow dependency/kashmir;\ - mkdir -p $${RESTBED_BUILD_PATH}; cd $${RESTBED_BUILD_PATH};\ - cmake -DCMAKE_CXX_COMPILER=$$QMAKE_CXX -DBUILD_SSL=OFF \ - -DCMAKE_INSTALL_PREFIX=. -B. -H$$shell_path($${RESTBED_SRC_PATH});\ - make - } + genrestbedlib.commands = \ + cd $${RS_SRC_PATH} && \ + git submodule update --init --recommend-shallow supportlibs/restbed && \ + cd $${RESTBED_SRC_PATH} && \ + git submodule update --init --recommend-shallow dependency/asio && \ + git submodule update --init --recommend-shallow dependency/catch && \ + git submodule update --init --recommend-shallow dependency/kashmir && \ + mkdir -p $${RESTBED_BUILD_PATH}; cd $${RESTBED_BUILD_PATH} && \ + cmake -DCMAKE_CXX_COMPILER=$$QMAKE_CXX $${CMAKE_GENERATOR_OVERRIDE} -DBUILD_SSL=OFF \ + -DCMAKE_INSTALL_PREFIX=. -B. -H$$shell_path($${RESTBED_SRC_PATH}) && \ + make QMAKE_EXTRA_COMPILERS += genrestbedlib RESTBED_HEADER_FILE=$$clean_path($${RESTBED_BUILD_PATH}/include/restbed) From c2ebd10aa6beb4fba212bfb1dab077461776b969 Mon Sep 17 00:00:00 2001 From: defnax Date: Wed, 27 Mar 2019 19:33:10 +0100 Subject: [PATCH 53/81] Count subscribers on the channels subscribe button like Youtube --- .../gui/gxschannels/GxsChannelPostsWidget.cpp | 10 +++++---- .../gui/gxschannels/GxsChannelPostsWidget.ui | 22 ------------------- 2 files changed, 6 insertions(+), 26 deletions(-) diff --git a/retroshare-gui/src/gui/gxschannels/GxsChannelPostsWidget.cpp b/retroshare-gui/src/gui/gxschannels/GxsChannelPostsWidget.cpp index 3cf412606..215036c1e 100644 --- a/retroshare-gui/src/gui/gxschannels/GxsChannelPostsWidget.cpp +++ b/retroshare-gui/src/gui/gxschannels/GxsChannelPostsWidget.cpp @@ -244,8 +244,6 @@ void GxsChannelPostsWidget::insertChannelDetails(const RsGxsChannelGroup &group) } ui->logoLabel->setPixmap(chanImage); - ui->subscribersLabel->setText(QString::number(group.mMeta.mPop)) ; - if (group.mMeta.mSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_PUBLISH) { mStateHelper->setWidgetEnabled(ui->postButton, true); @@ -271,6 +269,9 @@ void GxsChannelPostsWidget::insertChannelDetails(const RsGxsChannelGroup &group) ui->fileToolButton->setEnabled(true); ui->infoWidget->hide(); setViewMode(viewMode()); + + ui->subscribeToolButton->setText(tr("Subscribed") + " " + QString::number(group.mMeta.mPop) ); + ui->infoPosts->clear(); ui->infoDescription->clear(); @@ -332,6 +333,9 @@ void GxsChannelPostsWidget::insertChannelDetails(const RsGxsChannelGroup &group) ui->feedToolButton->setEnabled(false); ui->fileToolButton->setEnabled(false); + + ui->subscribeToolButton->setText(tr("Subscribe ") + " " + QString::number(group.mMeta.mPop) ); + } } @@ -622,8 +626,6 @@ void GxsChannelPostsWidget::blank() mStateHelper->setWidgetEnabled(ui->postButton, false); mStateHelper->setWidgetEnabled(ui->subscribeToolButton, false); - ui->subscribersLabel->setText("") ; - clearPosts(); groupNameChanged(QString()); diff --git a/retroshare-gui/src/gui/gxschannels/GxsChannelPostsWidget.ui b/retroshare-gui/src/gui/gxschannels/GxsChannelPostsWidget.ui index b86d3265c..c175d95d8 100644 --- a/retroshare-gui/src/gui/gxschannels/GxsChannelPostsWidget.ui +++ b/retroshare-gui/src/gui/gxschannels/GxsChannelPostsWidget.ui @@ -138,28 +138,6 @@
- - - - - 30 - 0 - - - - Subscribers - - - - - - - - - Qt::AlignCenter - - - From 94997bd0d37be56e06796396728fbac848d8d682 Mon Sep 17 00:00:00 2001 From: defnax Date: Thu, 28 Mar 2019 02:00:42 +0100 Subject: [PATCH 54/81] Added infoframe for Posted List Widget * Added infoframe for Posted List Widget * Fixed channels infoframe look both same --- .../src/gui/Posted/PostedListWidget.cpp | 67 ++++ .../src/gui/Posted/PostedListWidget.ui | 185 +++++++++ .../gui/gxschannels/GxsChannelPostsWidget.ui | 351 ++++++++---------- .../src/gui/qss/stylesheet/Standard.qss | 5 +- 4 files changed, 411 insertions(+), 197 deletions(-) diff --git a/retroshare-gui/src/gui/Posted/PostedListWidget.cpp b/retroshare-gui/src/gui/Posted/PostedListWidget.cpp index 5c0dd3061..2d8d2cfd9 100644 --- a/retroshare-gui/src/gui/Posted/PostedListWidget.cpp +++ b/retroshare-gui/src/gui/Posted/PostedListWidget.cpp @@ -26,8 +26,12 @@ #include "PostedCreatePostDialog.h" #include "PostedItem.h" #include "gui/common/UIStateHelper.h" +#include "gui/RetroShareLink.h" +#include "util/HandleRichText.h" +#include "util/DateTime.h" #include +#include "retroshare/rsgxscircles.h" #define POSTED_DEFAULT_LISTING_LENGTH 10 #define POSTED_MAX_INDEX 10000 @@ -76,6 +80,8 @@ PostedListWidget::PostedListWidget(const RsGxsGroupId &postedId, QWidget *parent ui->subscribeToolButton->setToolTip(tr( "

Subscribing to the links will gather \ available posts from your subscribed friends, and make the \ links visible to all other friends.

Afterwards you can unsubscribe from the context menu of the links list at left.

")); + + ui->infoframe->hide(); /* load settings */ processSettings(true); @@ -298,6 +304,67 @@ void PostedListWidget::insertPostedDetails(const RsPostedGroup &group) mStateHelper->setWidgetEnabled(ui->submitPostButton, IS_GROUP_SUBSCRIBED(group.mMeta.mSubscribeFlags)); ui->subscribeToolButton->setSubscribed(IS_GROUP_SUBSCRIBED(group.mMeta.mSubscribeFlags)); ui->subscribeToolButton->setHidden(IS_GROUP_SUBSCRIBED(group.mMeta.mSubscribeFlags)) ; + + RetroShareLink link; + + if (IS_GROUP_SUBSCRIBED(group.mMeta.mSubscribeFlags)) { + + ui->infoframe->hide(); + + } else { + + ui->infoPosts->setText(QString::number(group.mMeta.mVisibleMsgCount)); + + if(group.mMeta.mLastPost==0) + ui->infoLastPost->setText(tr("Never")); + else + + ui->infoLastPost->setText(DateTime::formatLongDateTime(group.mMeta.mLastPost)); + + QString formatDescription = QString::fromUtf8(group.mDescription.c_str()); + + unsigned int formatFlag = RSHTML_FORMATTEXT_EMBED_LINKS; + + formatDescription = RsHtml().formatText(NULL, formatDescription, formatFlag); + + ui->infoDescription->setText(formatDescription); + + ui->infoAdministrator->setId(group.mMeta.mAuthorId) ; + + link = RetroShareLink::createMessage(group.mMeta.mAuthorId, ""); + ui->infoAdministrator->setText(link.toHtml()); + + QString distrib_string ( "[unknown]" ); + + switch(group.mMeta.mCircleType) + { + case GXS_CIRCLE_TYPE_PUBLIC: distrib_string = tr("Public") ; + break ; + case GXS_CIRCLE_TYPE_EXTERNAL: + { + RsGxsCircleDetails det ; + + // !! What we need here is some sort of CircleLabel, which loads the circle and updates the label when done. + + if(rsGxsCircles->getCircleDetails(group.mMeta.mCircleId,det)) + distrib_string = tr("Restricted to members of circle \"")+QString::fromUtf8(det.mCircleName.c_str()) +"\""; + else + distrib_string = tr("Restricted to members of circle ")+QString::fromStdString(group.mMeta.mCircleId.toStdString()) ; + } + break ; + case GXS_CIRCLE_TYPE_YOUR_EYES_ONLY: distrib_string = tr("Your eyes only"); + break ; + case GXS_CIRCLE_TYPE_LOCAL: distrib_string = tr("You and your friend nodes"); + break ; + default: + std::cerr << "(EE) badly initialised group distribution ID = " << group.mMeta.mCircleType << std::endl; + } + + ui->infoDistribution->setText(distrib_string); + + ui->infoframe->show(); + + } } /*********************** **** **** **** ***********************/ diff --git a/retroshare-gui/src/gui/Posted/PostedListWidget.ui b/retroshare-gui/src/gui/Posted/PostedListWidget.ui index c96951823..13b3e208d 100644 --- a/retroshare-gui/src/gui/Posted/PostedListWidget.ui +++ b/retroshare-gui/src/gui/Posted/PostedListWidget.ui @@ -205,6 +205,186 @@
+ + + + QFrame::StyledPanel + + + QFrame::Raised + + + + 6 + + + 6 + + + 6 + + + 6 + + + + + false + + + + + + Topic Details + + + false + + + false + + + + + + 6 + + + + + + 75 + true + + + + Administrator: + + + + + + + + 0 + 0 + + + + + 75 + true + + + + Posts: + + + + + + + + 0 + 0 + + + + + 75 + true + + + + Last Post: + + + + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Description</span></p></body></html> + + + Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse + + + true + + + true + + + + + + + + 75 + true + + + + Description: + + + + + + + unknown + + + true + + + + + + + 0 + + + + + + + unknown + + + + + + + + 75 + true + + + + Distribution: + + + + + + + unknown + + + + + + + + + + + @@ -258,6 +438,11 @@ QComboBox
gui/gxs/GxsIdChooser.h
+ + GxsIdLabel + QLabel +
gui/gxs/GxsIdLabel.h
+
diff --git a/retroshare-gui/src/gui/gxschannels/GxsChannelPostsWidget.ui b/retroshare-gui/src/gui/gxschannels/GxsChannelPostsWidget.ui index b86d3265c..146c07aee 100644 --- a/retroshare-gui/src/gui/gxschannels/GxsChannelPostsWidget.ui +++ b/retroshare-gui/src/gui/gxschannels/GxsChannelPostsWidget.ui @@ -316,7 +316,7 @@ 3
- 3 + 0 3 @@ -326,211 +326,176 @@ - - - - - - - 255 - 255 - 255 - - - - - - - 255 - 255 - 178 - - - - - - - - - 255 - 255 - 255 - - - - - - - 255 - 255 - 178 - - - - - - - - - 255 - 255 - 178 - - - - - - - 255 - 255 - 178 - - - - - - - true + false - QFrame::Box + QFrame::NoFrame QFrame::Plain + + 6 + + + 6 + + + 6 + + + 6 + - - - - - - 75 - true - - - - Administrator: - - - - - - - - 0 - 0 - - - - - 75 - true - - - - Posts (at neighbor nodes): - - - - - - - - 0 - 0 - - - - - 75 - true - - - - Last Post: - - - - - - - <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> + + + Channel details + + + + 9 + + + 9 + + + 9 + + + 9 + + + + + + 75 + true + + + + Administrator: + + + + + + + + 0 + 0 + + + + + 75 + true + + + + Posts: + + + + + + + + 0 + 0 + + + + + 75 + true + + + + Last Post: + + + + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;"> <p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Description</span></p></body></html> - - - Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse - - - true - - - true - - - - - - - - 75 - true - - - - Description: - - - - - - - unknown - - - true - - - - - - - 0 - - - - - - - unknown - - - - - - - - 75 - true - - - - Distribution: - - - - - - - unknown - - - - + + + Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse + + + true + + + true + + + + + + + + 75 + true + + + + Description: + + + + + + + unknown + + + true + + + + + + + 0 + + + + + + + unknown + + + + + + + + 75 + true + + + + Distribution: + + + + + + + unknown + + + + +
diff --git a/retroshare-gui/src/gui/qss/stylesheet/Standard.qss b/retroshare-gui/src/gui/qss/stylesheet/Standard.qss index a12d62db6..8226d7f28 100644 --- a/retroshare-gui/src/gui/qss/stylesheet/Standard.qss +++ b/retroshare-gui/src/gui/qss/stylesheet/Standard.qss @@ -830,10 +830,7 @@ GxsForumThreadWidget QToolButton#subscribeToolButton:hover { GxsChannelPostsWidget QFrame#infoFrame { - border: 1px solid #DCDC41; - border-radius: 6px; - background: #FFFFD7; - background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #FFFFD7, stop:1 #FFFFB2); + } GxsChannelPostsWidget QToolButton#subscribeToolButton { From 031a717de0f14532eae90f76f71647065d55855c Mon Sep 17 00:00:00 2001 From: csoler Date: Thu, 28 Mar 2019 20:06:32 +0100 Subject: [PATCH 55/81] moved column resize after procesSettings() --- retroshare-gui/src/gui/MessagesDialog.cpp | 29 +++++++---------------- 1 file changed, 8 insertions(+), 21 deletions(-) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/MessagesDialog.cpp index 16f7b80b3..e8c130e88 100644 --- a/retroshare-gui/src/gui/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/MessagesDialog.cpp @@ -158,13 +158,6 @@ MessagesDialog::MessagesDialog(QWidget *parent) /* Set initial section sizes */ QHeaderView * msgwheader = ui.messageTreeWidget->header () ; - msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_SUBJECT, fm.width("You have a message")*3.0); - msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_AUTHOR, fm.width("[Retroshare]")*1.1); - msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_DATE, fm.width("01/01/1970")*1.1); - - QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_SUBJECT, QHeaderView::Interactive); - QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_AUTHOR, QHeaderView::Interactive); - QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_DATE, QHeaderView::Interactive); ui.forwardmessageButton->setToolTip(tr("Forward selected Message")); ui.replyallmessageButton->setToolTip(tr("Reply to All")); @@ -208,6 +201,14 @@ MessagesDialog::MessagesDialog(QWidget *parent) msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_ATTACHMENT, fm.width('0')*1.5); msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_READ, fm.width('0')*1.5); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_SUBJECT, fm.width("You have a message")*3.0); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_AUTHOR, fm.width("[Retroshare]")*1.1); + msgwheader->resizeSection (RsMessageModel::COLUMN_THREAD_DATE, fm.width("01/01/1970")*1.1); + + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_SUBJECT, QHeaderView::Interactive); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_AUTHOR, QHeaderView::Interactive); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_DATE, QHeaderView::Interactive); + QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_STAR, QHeaderView::Fixed); QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_ATTACHMENT, QHeaderView::Fixed); QHeaderView_setSectionResizeModeColumn(msgwheader, RsMessageModel::COLUMN_THREAD_READ, QHeaderView::Fixed); @@ -397,20 +398,6 @@ bool MessagesDialog::eventFilter(QObject *obj, QEvent *event) return MainPage::eventFilter(obj, event); } -// void MessagesDialog::changeEvent(QEvent *e) -// { -// QWidget::changeEvent(e); -// -// switch (e->type()) { -// case QEvent::StyleChange: -// insertMessages(); -// break; -// default: -// // remove compiler warnings -// break; -// } -// } - void MessagesDialog::fillQuickView() { MsgTagType tags; From a1ca31afa0ba3af6933171e037bbfc54491e5758 Mon Sep 17 00:00:00 2001 From: defnax Date: Fri, 29 Mar 2019 02:00:13 +0100 Subject: [PATCH 56/81] fixes from cyril & removed stylesheets from some buttons fixed size of thumbnail on all screens fixed aspect ratio removede the stylsheet for comments,share, notes --- retroshare-gui/src/gui/Posted/PostedItem.cpp | 17 +++++++++++------ retroshare-gui/src/gui/Posted/PostedItem.ui | 6 +++--- .../src/gui/gxs/GxsCommentTreeWidget.cpp | 2 +- .../src/gui/qss/stylesheet/Standard.qss | 6 +----- 4 files changed, 16 insertions(+), 15 deletions(-) diff --git a/retroshare-gui/src/gui/Posted/PostedItem.cpp b/retroshare-gui/src/gui/Posted/PostedItem.cpp index d107b660d..9ad0aa839 100644 --- a/retroshare-gui/src/gui/Posted/PostedItem.cpp +++ b/retroshare-gui/src/gui/Posted/PostedItem.cpp @@ -246,20 +246,25 @@ void PostedItem::fill() return; } + QPixmap sqpixmap2 = QPixmap(":/images/thumb-default.png"); + mInFill = true; - + int desired_height = 1.5*(ui->voteDownButton->height() + ui->voteUpButton->height() + ui->scoreLabel->height()); + int desired_width = sqpixmap2.width()*desired_height/(float)sqpixmap2.height(); + if(mPost.mImage.mData != NULL) { QPixmap pixmap; pixmap.loadFromData(mPost.mImage.mData, mPost.mImage.mSize, "PNG"); // Wiping data - as its been passed to thumbnail. - QPixmap sqpixmap = pixmap.scaled(800, 600, Qt::KeepAspectRatio, Qt::SmoothTransformation); - ui->pictureLabel->setPixmap(sqpixmap); - - ui->thumbnailLabel->setPixmap(pixmap); - }else + QPixmap sqpixmap = pixmap.scaled(desired_width,desired_height, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); + ui->thumbnailLabel->setPixmap(sqpixmap); + ui->pictureLabel->setPixmap(pixmap); + } + else { + //ui->thumbnailLabel->setFixedSize(desired_width,desired_height); ui->expandButton->setDisabled(true); } diff --git a/retroshare-gui/src/gui/Posted/PostedItem.ui b/retroshare-gui/src/gui/Posted/PostedItem.ui index d991b99ef..250f43007 100644 --- a/retroshare-gui/src/gui/Posted/PostedItem.ui +++ b/retroshare-gui/src/gui/Posted/PostedItem.ui @@ -6,8 +6,8 @@ 0 0 - 617 - 190 + 825 + 337 @@ -683,8 +683,8 @@ - + diff --git a/retroshare-gui/src/gui/gxs/GxsCommentTreeWidget.cpp b/retroshare-gui/src/gui/gxs/GxsCommentTreeWidget.cpp index a66b93b34..296ce68c8 100644 --- a/retroshare-gui/src/gui/gxs/GxsCommentTreeWidget.cpp +++ b/retroshare-gui/src/gui/gxs/GxsCommentTreeWidget.cpp @@ -542,7 +542,7 @@ void GxsCommentTreeWidget::service_loadThread(const uint32_t &token) text = qtime.toString("yyyy-MM-dd hh:mm:ss") ; item->setText(PCITEM_COLUMN_DATE, text) ; item->setToolTip(PCITEM_COLUMN_DATE, text) ; - item->setData(PCITEM_COLUMN_DATE, ROLE_SORT, comment.mMeta.mPublishTs); + item->setData(PCITEM_COLUMN_DATE, ROLE_SORT, QVariant(qlonglong(comment.mMeta.mPublishTs))); } diff --git a/retroshare-gui/src/gui/qss/stylesheet/Standard.qss b/retroshare-gui/src/gui/qss/stylesheet/Standard.qss index 8226d7f28..0c858f972 100644 --- a/retroshare-gui/src/gui/qss/stylesheet/Standard.qss +++ b/retroshare-gui/src/gui/qss/stylesheet/Standard.qss @@ -907,11 +907,7 @@ PostedItem QLabel#fromBoldLabel, QLabel#fromLabel, QLabel#dateLabel, QLabel#site color: #787c7e; } -PostedItem QToolButton#commentButton, QPushButton#shareButton, QToolButton#notesButton{ - font-size: 12px; - color: #878a8c; - font-weight: bold; -} + GxsCommentDialog QComboBox#sortBox { font: bold; From 5ee86262aa1d85625ff22ca3007f21c7b99be3fa Mon Sep 17 00:00:00 2001 From: csoler Date: Fri, 29 Mar 2019 09:17:32 +0100 Subject: [PATCH 57/81] fixed compilation --- retroshare-gui/src/gui/People/IdentityWidget.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/retroshare-gui/src/gui/People/IdentityWidget.cpp b/retroshare-gui/src/gui/People/IdentityWidget.cpp index 15eed8852..64f1873d9 100644 --- a/retroshare-gui/src/gui/People/IdentityWidget.cpp +++ b/retroshare-gui/src/gui/People/IdentityWidget.cpp @@ -18,6 +18,7 @@ * * *******************************************************************************/ +#include "retroshare/rsreputations.h" #include "gui/People/IdentityWidget.h" #include "ui_IdentityWidget.h" @@ -85,7 +86,7 @@ void IdentityWidget::updateData(const RsGxsIdGroup &gxs_group_info) _group_info = gxs_group_info; _haveGXSId = true; - RsReputations::ReputationInfo info ; + RsReputationInfo info ; rsReputations->getReputationInfo(RsGxsId(_group_info.mMeta.mGroupId),_group_info.mPgpId,info) ; m_myName = QString::fromUtf8(_group_info.mMeta.mGroupName.c_str()); From e0af46eb854848d27d2d457264cbb1ae3bd3d987 Mon Sep 17 00:00:00 2001 From: csoler Date: Sat, 30 Mar 2019 22:53:14 +0100 Subject: [PATCH 58/81] added new method to create a channel with more explicit parameters and JSon API for it --- libretroshare/src/retroshare/rsgxschannels.h | 22 ++++ libretroshare/src/retroshare/rsgxsflags.h | 7 +- libretroshare/src/services/p3gxschannels.cc | 111 ++++++++++++++++++ libretroshare/src/services/p3gxschannels.h | 10 ++ retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp | 4 +- .../gui/gxschannels/GxsChannelGroupDialog.cpp | 4 + 6 files changed, 153 insertions(+), 5 deletions(-) diff --git a/libretroshare/src/retroshare/rsgxschannels.h b/libretroshare/src/retroshare/rsgxschannels.h index 4d28cad22..8ed0dc285 100644 --- a/libretroshare/src/retroshare/rsgxschannels.h +++ b/libretroshare/src/retroshare/rsgxschannels.h @@ -107,6 +107,28 @@ public: */ virtual bool createChannel(RsGxsChannelGroup& channel) = 0; + /** + * @brief Create channel. Blocking API. + * @jsonapi{development} + * @param[in] name Name of the channel + * @param[in] description Description of the channel + * @param[in] image Thumbnail that is shown to advertise the channel. Possibly empty. + * @param[in] author_id GxsId of the contact author. For an anonymous channel, leave this to RsGxsId()="00000....0000" + * @param[in] circle_type Type of visibility restriction, among { GXS_CIRCLE_TYPE_PUBLIC, GXS_CIRCLE_TYPE_EXTERNAL, GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY, GXS_CIRCLE_TYPE_YOUR_EYES_ONLY } + * @param[in] circle_id Id of the circle (should be an external circle or GXS_CIRCLE_TYPE_EXTERNAL, a local friend group for GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY, GxsCircleId()="000....000" otherwise + * @param[out] channel_group_id Group id of the created channel, if command succeeds. + * @param[out] error_message Error messsage supplied when the channel creation fails. + * @return False on error, true otherwise. + */ + virtual bool createChannel(const std::string& name, + const std::string& description, + const RsGxsImage& image, + const RsGxsId& author_id, + uint32_t circle_type, + RsGxsCircleId& circle_id, + RsGxsGroupId& channel_group_id, + std::string& error_message)=0; + /** * @brief Add a comment on a post or on another comment * @jsonapi{development} diff --git a/libretroshare/src/retroshare/rsgxsflags.h b/libretroshare/src/retroshare/rsgxsflags.h index 7a737c74c..ff6f164c2 100644 --- a/libretroshare/src/retroshare/rsgxsflags.h +++ b/libretroshare/src/retroshare/rsgxsflags.h @@ -52,14 +52,15 @@ namespace GXS_SERV { static const uint32_t FLAG_AUTHOR_AUTHENTICATION_MASK = 0x0000ff00; static const uint32_t FLAG_AUTHOR_AUTHENTICATION_NONE = 0x00000000; static const uint32_t FLAG_AUTHOR_AUTHENTICATION_GPG = 0x00000100; // Anti-spam feature. Allows to ask higher reputation to anonymous IDs - static const uint32_t FLAG_AUTHOR_AUTHENTICATION_REQUIRED = 0x00000200; - static const uint32_t FLAG_AUTHOR_AUTHENTICATION_IFNOPUBSIGN = 0x00000400; + static const uint32_t FLAG_AUTHOR_AUTHENTICATION_REQUIRED = 0x00000200; // unused + static const uint32_t FLAG_AUTHOR_AUTHENTICATION_IFNOPUBSIGN = 0x00000400; // ??? static const uint32_t FLAG_AUTHOR_AUTHENTICATION_TRACK_MESSAGES = 0x00000800; // not used anymore static const uint32_t FLAG_AUTHOR_AUTHENTICATION_GPG_KNOWN = 0x00001000; // Anti-spam feature. Allows to ask higher reputation to unknown IDs and anonymous IDs + // These are *not used* static const uint32_t FLAG_GROUP_SIGN_PUBLISH_MASK = 0x000000ff; static const uint32_t FLAG_GROUP_SIGN_PUBLISH_ENCRYPTED = 0x00000001; - static const uint32_t FLAG_GROUP_SIGN_PUBLISH_ALLSIGNED = 0x00000002; + static const uint32_t FLAG_GROUP_SIGN_PUBLISH_ALLSIGNED = 0x00000002; // unused static const uint32_t FLAG_GROUP_SIGN_PUBLISH_THREADHEAD = 0x00000004; static const uint32_t FLAG_GROUP_SIGN_PUBLISH_NONEREQ = 0x00000008; diff --git a/libretroshare/src/services/p3gxschannels.cc b/libretroshare/src/services/p3gxschannels.cc index 3f34b6438..f332dfbac 100644 --- a/libretroshare/src/services/p3gxschannels.cc +++ b/libretroshare/src/services/p3gxschannels.cc @@ -31,6 +31,7 @@ #include "retroshare/rsgxsflags.h" #include "retroshare/rsfiles.h" +#include "retroshare/rspeers.h" #include "rsserver/p3face.h" #include "retroshare/rsnotify.h" @@ -1055,6 +1056,116 @@ bool p3GxsChannels::getChannelContent( const RsGxsGroupId& channelId, return getPostData(token, posts, comments); } +bool p3GxsChannels::createChannel(const std::string& name, + const std::string& description, + const RsGxsImage& image, + const RsGxsId& author_id, + uint32_t circle_type, + RsGxsCircleId& circle_id, + RsGxsGroupId& channel_group_id, + std::string& error_message) +{ + // do some checks + + if( circle_type != GXS_CIRCLE_TYPE_PUBLIC + && circle_type != GXS_CIRCLE_TYPE_EXTERNAL + && circle_type != GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY + && circle_type != GXS_CIRCLE_TYPE_LOCAL + && circle_type != GXS_CIRCLE_TYPE_YOUR_EYES_ONLY ) + { + error_message = std::string("circle_type has a non allowed value") ; + return false ; + } + + switch(circle_type) + { + case GXS_CIRCLE_TYPE_EXTERNAL: + if(circle_id.isNull()) + { + error_message = std::string("circle_type is GXS_CIRCLE_TYPE_EXTERNAL but circle_id is null"); + return false ; + } + break; + + case GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY: + { + RsGroupInfo ginfo; + + if(!rsPeers->getGroupInfo(RsNodeGroupId(circle_id),ginfo)) + { + error_message = std::string("circle_type is GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY but circle_id is not set or does not correspond to a actual group of friends"); + return false; + } + } + break; + + default: + if(!circle_id.isNull()) + { + error_message = std::string("circle_type requires a null circle id, but a non null circle id (" + circle_id.toStdString() + ") was supplied"); + return false; + } + } + + // Create a consistent channel group meta from the information supplied + + RsGxsChannelGroup channel ; + + channel.mMeta.mGroupName = name ; + channel.mMeta.mAuthorId = author_id ; + channel.mMeta.mCircleType = circle_type ; + + channel.mMeta.mSignFlags = GXS_SERV::FLAG_GROUP_SIGN_PUBLISH_NONEREQ + | GXS_SERV::FLAG_AUTHOR_AUTHENTICATION_REQUIRED; + + channel.mMeta.mGroupFlags = GXS_SERV::FLAG_PRIVACY_PUBLIC; + + channel.mMeta.mCircleId.clear(); + channel.mMeta.mInternalCircle.clear(); + + if(circle_type == GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY) + channel.mMeta.mInternalCircle = circle_id; + else if(circle_type == GXS_CIRCLE_TYPE_EXTERNAL) + channel.mMeta.mCircleId = circle_id; + + // Create the channel + + channel.mDescription = description ; + channel.mImage = image ; + + uint32_t token; + if(!createGroup(token, channel)) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! Failed creating group." + << std::endl; + return false; + } + + // wait for the group creation to complete. + + if(waitToken(token) != RsTokenService::COMPLETE) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! GXS operation failed." + << std::endl; + return false; + } + + if(!RsGenExchange::getPublishedGroupMeta(token, channel.mMeta)) + { + std::cerr << __PRETTY_FUNCTION__ << "Error! Failure getting updated " + << " group data." << std::endl; + return false; + } + + channel_group_id = channel.mMeta.mGroupId; + +#ifdef RS_DEEP_SEARCH + DeepSearch::indexChannelGroup(channel); +#endif // RS_DEEP_SEARCH + + return true; +} + bool p3GxsChannels::createChannel(RsGxsChannelGroup& channel) { uint32_t token; diff --git a/libretroshare/src/services/p3gxschannels.h b/libretroshare/src/services/p3gxschannels.h index 7ac63f8e7..6ddcedadb 100644 --- a/libretroshare/src/services/p3gxschannels.h +++ b/libretroshare/src/services/p3gxschannels.h @@ -197,6 +197,16 @@ virtual bool ExtraFileRemove(const RsFileHash &hash); /// Implementation of @see RsGxsChannels::createChannel virtual bool createChannel(RsGxsChannelGroup& channel); + /// Implementation of @see RsGxsChannels::createChannel + virtual bool createChannel(const std::string& name, + const std::string& description, + const RsGxsImage& image, + const RsGxsId& author_id, + uint32_t circle_type, + RsGxsCircleId& circle_id, + RsGxsGroupId& channel_group_id, + std::string& error_message); + /// Implementation of @see RsGxsChannels::createComment virtual bool createComment(RsGxsComment& comment); diff --git a/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp b/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp index 4bf950a5e..fb50f9acc 100644 --- a/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp +++ b/retroshare-gui/src/gui/gxs/GxsGroupDialog.cpp @@ -755,12 +755,12 @@ void GxsGroupDialog::setGroupSignFlags(uint32_t signFlags) // (cyril) very weird piece of code. Need to clear this up. ui.comments_allowed->setChecked(true); - ui.commentsValueLabel->setText("Allowed") ; + ui.commentsValueLabel->setText("Allowed") ; } else { ui.comments_no->setChecked(true); - ui.commentsValueLabel->setText("Allowed") ; + ui.commentsValueLabel->setText("Forbidden") ; } } diff --git a/retroshare-gui/src/gui/gxschannels/GxsChannelGroupDialog.cpp b/retroshare-gui/src/gui/gxschannels/GxsChannelGroupDialog.cpp index b33c49b60..6fb832a69 100644 --- a/retroshare-gui/src/gui/gxschannels/GxsChannelGroupDialog.cpp +++ b/retroshare-gui/src/gui/gxschannels/GxsChannelGroupDialog.cpp @@ -61,11 +61,15 @@ const uint32_t ChannelEditDefaultsFlags = ChannelCreateDefaultsFlags; GxsChannelGroupDialog::GxsChannelGroupDialog(TokenQueue *tokenQueue, QWidget *parent) : GxsGroupDialog(tokenQueue, ChannelCreateEnabledFlags, ChannelCreateDefaultsFlags, parent) { + ui.commentGroupBox->setEnabled(false); // These are here because comments_allowed are actually not used yet, so the group will not be changed by the setting and when + ui.comments_allowed->setChecked(true); // the group info is displayed it will therefore be set to "disabled" in all cases although it is enabled. } GxsChannelGroupDialog::GxsChannelGroupDialog(TokenQueue *tokenExternalQueue, RsTokenService *tokenService, Mode mode, RsGxsGroupId groupId, QWidget *parent) : GxsGroupDialog(tokenExternalQueue, tokenService, mode, groupId, ChannelEditEnabledFlags, ChannelEditDefaultsFlags, parent) { + ui.commentGroupBox->setEnabled(false); // These are here because comments_allowed are actually not used yet, so the group will not be changed by the setting and when + ui.comments_allowed->setChecked(true); // the group info is displayed it will therefore be set to "disabled" in all cases although it is enabled. } void GxsChannelGroupDialog::initUi() From 44c1f1580f762d5d172526b703e7d63dfc611ef2 Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 31 Mar 2019 22:11:09 +0200 Subject: [PATCH 59/81] added other clean API entries for channel: createComment(), createVote() and createPost() --- libretroshare/src/retroshare/rsgxschannels.h | 63 ++++-- libretroshare/src/services/p3gxschannels.cc | 200 ++++++++++++++++--- libretroshare/src/services/p3gxschannels.h | 33 +++ 3 files changed, 256 insertions(+), 40 deletions(-) diff --git a/libretroshare/src/retroshare/rsgxschannels.h b/libretroshare/src/retroshare/rsgxschannels.h index 8ed0dc285..9f76aec84 100644 --- a/libretroshare/src/retroshare/rsgxschannels.h +++ b/libretroshare/src/retroshare/rsgxschannels.h @@ -99,6 +99,7 @@ public: explicit RsGxsChannels(RsGxsIface& gxs) : RsGxsIfaceHelper(gxs) {} virtual ~RsGxsChannels() {} +#ifdef REMOVED /** * @brief Create channel. Blocking API. * @jsonapi{development} @@ -106,6 +107,7 @@ public: * @return false on error, true otherwise */ virtual bool createChannel(RsGxsChannelGroup& channel) = 0; +#endif /** * @brief Create channel. Blocking API. @@ -115,43 +117,76 @@ public: * @param[in] image Thumbnail that is shown to advertise the channel. Possibly empty. * @param[in] author_id GxsId of the contact author. For an anonymous channel, leave this to RsGxsId()="00000....0000" * @param[in] circle_type Type of visibility restriction, among { GXS_CIRCLE_TYPE_PUBLIC, GXS_CIRCLE_TYPE_EXTERNAL, GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY, GXS_CIRCLE_TYPE_YOUR_EYES_ONLY } - * @param[in] circle_id Id of the circle (should be an external circle or GXS_CIRCLE_TYPE_EXTERNAL, a local friend group for GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY, GxsCircleId()="000....000" otherwise + * @param[in] circle_id Id of the circle (should be an external circle for GXS_CIRCLE_TYPE_EXTERNAL, a local friend group for GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY, GxsCircleId()="000....000" otherwise * @param[out] channel_group_id Group id of the created channel, if command succeeds. * @param[out] error_message Error messsage supplied when the channel creation fails. * @return False on error, true otherwise. */ virtual bool createChannel(const std::string& name, const std::string& description, - const RsGxsImage& image, - const RsGxsId& author_id, - uint32_t circle_type, - RsGxsCircleId& circle_id, - RsGxsGroupId& channel_group_id, - std::string& error_message)=0; + const RsGxsImage& image, + const RsGxsId& author_id, + uint32_t circle_type, + RsGxsCircleId& circle_id, + RsGxsGroupId& channel_group_id, + std::string& error_message )=0; /** * @brief Add a comment on a post or on another comment * @jsonapi{development} - * @param[inout] comment + * @param[in] groupId Id of the channel in which the comment is to be posted + * @param[in] parentMsgId Id of the parent of the comment that is either a channel post Id or the Id of another comment. + * @param[in] comment UTF-8 string containing the comment + * @param[out] commentMessageId Id of the comment that was created + * @param[out] error_string Error message supplied when the comment creation fails. * @return false on error, true otherwise */ - virtual bool createComment(RsGxsComment& comment) = 0; + virtual bool createComment(const RsGxsGroupId& groupId, + const RsGxsMessageId& parentMsgId, + const std::string& comment, + RsGxsMessageId& commentMessageId, + std::string& error_message )=0; /** * @brief Create channel post. Blocking API. * @jsonapi{development} - * @param[inout] post + * @param[in] groupId Id of the channel where to put the post (publish rights needed!) + * @param[in] origMsgId Id of the post you are replacing. If left blank (RsGxsMssageId()="0000.....0000", a new post will be created + * @param[in] msgName Title of the post + * @param[in] msg Text content of the post + * @param[in] files List of attached files. These are supposed to be shared otherwise (use ExtraFileHash() below) + * @param[in] thumbnail Image displayed in the list of posts. Can be left blank. + * @param[out] messsageId Id of the message that was created + * @param[out] error_message Error text if anything bad happens * @return false on error, true otherwise */ - virtual bool createPost(RsGxsChannelPost& post) = 0; - + virtual bool createPost(const RsGxsGroupId& groupId, + const RsGxsMessageId& origMsgId, + const std::string& msgName, + const std::string& msg, + const std::list& files, + const RsGxsImage& thumbnail, + RsGxsMessageId& messageId, + std::string& error_message) = 0; /** * @brief createVote * @jsonapi{development} - * @param[inout] vote + * @param[in] groupId Id of the channel where to put the post (publish rights needed!) + * @param[in] threadId Id of the channel post in which a comment is voted + * @param[in] commentMesssageId Id of the comment that is voted + * @param[in] authorId Id of the author. Needs to be your identity. + * @param[in] voteType Type of vote (GXS_VOTE_NONE=0x00, GXS_VOTE_DOWN=0x01, GXS_VOTE_UP=0x02) + * @param[out] voteMessageId Id of the vote message produced + * @param[out] error_message Error text if anything bad happens * @return false on error, true otherwise */ - virtual bool createVote(RsGxsVote& vote) = 0; + virtual bool createVote( const RsGxsGroupId& groupId, + const RsGxsMessageId& threadId, + const RsGxsMessageId& commentMessageId, + const RsGxsId& authorId, + uint32_t voteType, + RsGxsMessageId& voteMessageId, + std::string& error_message)=0; /** * @brief Edit channel details. diff --git a/libretroshare/src/services/p3gxschannels.cc b/libretroshare/src/services/p3gxschannels.cc index f332dfbac..e1fdd9281 100644 --- a/libretroshare/src/services/p3gxschannels.cc +++ b/libretroshare/src/services/p3gxschannels.cc @@ -1166,6 +1166,7 @@ bool p3GxsChannels::createChannel(const std::string& name, return true; } +#ifdef REMOVED bool p3GxsChannels::createChannel(RsGxsChannelGroup& channel) { uint32_t token; @@ -1196,58 +1197,91 @@ bool p3GxsChannels::createChannel(RsGxsChannelGroup& channel) return true; } +#endif -bool p3GxsChannels::createComment(RsGxsComment& comment) +bool p3GxsChannels::createVote( const RsGxsGroupId& groupId, + const RsGxsMessageId & threadId, + const RsGxsMessageId& commentMessageId, + const RsGxsId& authorId, + uint32_t voteType, + RsGxsMessageId& voteMessageId, + std::string& error_message) { - uint32_t token; - if(!createNewComment(token, comment)) + // Do some checks + + std::vector channelsInfo; + + if(!getChannelsInfo(std::list({groupId}),channelsInfo)) // does the channel actually exist? + { + error_message = std::string("Channel with Id " + groupId.toStdString() + " does not exist."); + return false; + } + + if(commentMessageId.isNull()) // has a correct comment msg id been supplied? + { + error_message = std::string("You cannot vote on null comment " + commentMessageId.toStdString() + " of channel with Id " + groupId.toStdString() + ": please supply a non null comment Id!"); + return false; + } + + std::set s({commentMessageId}); + std::vector posts; + std::vector comments; + + if(!getChannelContent( groupId,s,posts,comments )) // does the comment to vote actually exist? { - std::cerr << __PRETTY_FUNCTION__ << "Error! Failed creating comment." - << std::endl; + error_message = std::string("You cannot vote on comment " + commentMessageId.toStdString() + " of channel with Id " + groupId.toStdString() + ": this comment does not locally exist!"); return false; } - if(waitToken(token) != RsTokenService::COMPLETE) + if(posts.front().mMeta.mParentId.isNull()) // is the ID a comment ID or a post ID? It should be comment => should have a parent ID { - std::cerr << __PRETTY_FUNCTION__ << "Error! GXS operation failed." - << std::endl; + error_message = std::string("You cannot vote on channel message " + commentMessageId.toStdString() + " of channel with Id " + groupId.toStdString() + ": this ID refers to a post, not a comment!"); return false; } - if(!RsGenExchange::getPublishedMsgMeta(token, comment.mMeta)) - { - std::cerr << __PRETTY_FUNCTION__ << "Error! Failure getting generated " - << " comment data." << std::endl; + if(voteType != GXS_VOTE_NONE && voteType != GXS_VOTE_UP && voteType != GXS_VOTE_DOWN) // is voteType consistent? + { + error_message = std::string("Your vote to channel with Id " + groupId.toStdString() + " has wrong vote type. Only GXS_VOTE_NONE, GXS_VOTE_UP, GXS_VOTE_DOWN accepted."); return false; - } + } - return true; -} + if(!rsIdentity->isOwnId(authorId)) // is the voter ID actually ours? + { + error_message = std::string("You cannot vote to channel with Id " + groupId.toStdString() + " with identity " + authorId.toStdString() + " because it is not yours."); + return false; + } + + // Create the vote + + RsGxsVote vote; + + vote.mMeta.mGroupId = groupId; + vote.mMeta.mThreadId = threadId; + vote.mMeta.mParentId = commentMessageId; + vote.mMeta.mAuthorId = authorId; + + vote.mVoteType = voteType; -bool p3GxsChannels::createVote(RsGxsVote& vote) -{ uint32_t token; if(!createNewVote(token, vote)) { - std::cerr << __PRETTY_FUNCTION__ << "Error! Failed creating vote." - << std::endl; + error_message = std::string("Error! Failed creating vote."); return false; } if(waitToken(token) != RsTokenService::COMPLETE) { - std::cerr << __PRETTY_FUNCTION__ << "Error! GXS operation failed." - << std::endl; + error_message = std::string("Error! GXS operation failed."); return false; } if(!RsGenExchange::getPublishedMsgMeta(token, vote.mMeta)) { - std::cerr << __PRETTY_FUNCTION__ << "Error! Failure getting generated " - << " vote data." << std::endl; + error_message = std::string("Error! Failure getting generated vote data."); return false; } + voteMessageId = vote.mMeta.mMsgId; return true; } @@ -1282,11 +1316,60 @@ bool p3GxsChannels::editChannel(RsGxsChannelGroup& channel) return true; } -bool p3GxsChannels::createPost(RsGxsChannelPost& post) +bool p3GxsChannels::createPost(const RsGxsGroupId& groupId, + const RsGxsMessageId &origMsgId, + const std::string& msgName, + const std::string& msg, + const std::list& files, + const RsGxsImage& thumbnail, + RsGxsMessageId &message_id, + std::string& error_message) { + // Do some checks + + std::vector channelsInfo; + + if(!getChannelsInfo(std::list({groupId}),channelsInfo)) + { + error_message = std::string("Channel with Id " + groupId.toStdString() + " does not exist."); + return false; + } + + const RsGxsChannelGroup& cg(*channelsInfo.begin()); + + if(!(cg.mMeta.mSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_PUBLISH)) + { + error_message = std::string("You cannot post to channel with Id " + groupId.toStdString() + ": missing publish rights!"); + return false; + } + + if(!origMsgId.isNull()) + { + std::set s({origMsgId}); + std::vector posts; + std::vector comments; + + if(!getChannelContent( groupId,s,posts,comments )) + { + error_message = std::string("You cannot edit post " + origMsgId.toStdString() + " of channel with Id " + groupId.toStdString() + ": this post does not locally exist!"); + return false; + } + } + + // Create the post + RsGxsChannelPost post; + + post.mMeta.mGroupId = groupId; + post.mMeta.mOrigMsgId = origMsgId; + post.mMeta.mMsgName = msgName; + + post.mMsg = msg; + post.mFiles = files; + post.mThumbnail = thumbnail; + uint32_t token; - if( !createPost(token, post) - || waitToken(token) != RsTokenService::COMPLETE ) return false; + if( !createPost(token, post) || waitToken(token) != RsTokenService::COMPLETE ) + return false; if(RsGenExchange::getPublishedMsgMeta(token,post.mMeta)) { @@ -1294,12 +1377,77 @@ bool p3GxsChannels::createPost(RsGxsChannelPost& post) DeepSearch::indexChannelPost(post); #endif // RS_DEEP_SEARCH + message_id = post.mMeta.mMsgId; return true; } + error_message = std::string("cannot publish message. Check that you have publish rights on this channel?"); return false; } +bool p3GxsChannels::createComment(const RsGxsGroupId& groupId, + const RsGxsMessageId& parentMsgId, + const std::string& comment, + RsGxsMessageId& commentMessageId, + std::string& error_message) +{ + // Do some checks + + std::vector channelsInfo; + + if(!getChannelsInfo(std::list({groupId}),channelsInfo)) + { + error_message = std::string("Channel with Id " + groupId.toStdString() + " does not exist."); + return false; + } + + if(parentMsgId.isNull()) + { + error_message = std::string("You cannot comment post " + parentMsgId.toStdString() + " of channel with Id " + groupId.toStdString() + ": please supply a non null post Id!"); + return false; + } + + std::set s({parentMsgId}); + std::vector posts; + std::vector comments; + + if(!getChannelContent( groupId,s,posts,comments )) + { + error_message = std::string("You cannot comment post " + parentMsgId.toStdString() + " of channel with Id " + groupId.toStdString() + ": this post does not locally exist!"); + return false; + } + + // Now create the comment + + RsGxsComment cmt; + + cmt.mComment = comment; + cmt.mMeta.mGroupId = groupId; + cmt.mMeta.mParentId = parentMsgId; + + uint32_t token; + if(!createNewComment(token, cmt)) + { + error_message = std::string("Error! Failed creating comment."); + return false; + } + + if(waitToken(token) != RsTokenService::COMPLETE) + { + error_message = std::string("Error! GXS operation failed."); + return false; + } + + if(!RsGenExchange::getPublishedMsgMeta(token, cmt.mMeta)) + { + error_message = std::string("Error! Failure getting generated comment data."); + return false; + } + + commentMessageId = cmt.mMeta.mMsgId; + return true; +} + bool p3GxsChannels::subscribeToChannel( const RsGxsGroupId& groupId, bool subscribe ) { diff --git a/libretroshare/src/services/p3gxschannels.h b/libretroshare/src/services/p3gxschannels.h index 6ddcedadb..3203be1dd 100644 --- a/libretroshare/src/services/p3gxschannels.h +++ b/libretroshare/src/services/p3gxschannels.h @@ -194,8 +194,10 @@ virtual bool ExtraFileRemove(const RsFileHash &hash); virtual bool getContentSummaries( const RsGxsGroupId& channelId, std::vector& summaries ); +#ifdef REMOVED /// Implementation of @see RsGxsChannels::createChannel virtual bool createChannel(RsGxsChannelGroup& channel); +#endif /// Implementation of @see RsGxsChannels::createChannel virtual bool createChannel(const std::string& name, @@ -207,17 +209,48 @@ virtual bool ExtraFileRemove(const RsFileHash &hash); RsGxsGroupId& channel_group_id, std::string& error_message); +#ifdef REMOVED /// Implementation of @see RsGxsChannels::createComment virtual bool createComment(RsGxsComment& comment); +#endif + + /// Implementation of @see RsGxsChannels::createComment + virtual bool createComment(const RsGxsGroupId& groupId, + const RsGxsMessageId& parentMsgId, + const std::string& comment, + RsGxsMessageId& commentMessageId, + std::string& error_message); /// Implementation of @see RsGxsChannels::editChannel virtual bool editChannel(RsGxsChannelGroup& channel); +#ifdef REMOVED /// Implementation of @see RsGxsChannels::createPost virtual bool createPost(RsGxsChannelPost& post); +#endif + /// Implementation of @see RsGxsChannels::createPost + virtual bool createPost(const RsGxsGroupId& groupId, + const RsGxsMessageId& origMsgId, + const std::string& msgName, + const std::string& msg, + const std::list& files, + const RsGxsImage& thumbnail, + RsGxsMessageId &message_id, + std::string& error_message) ; +#ifdef REMOVED /// Implementation of @see RsGxsChannels::createVote virtual bool createVote(RsGxsVote& vote); +#endif + + /// Implementation of @see RsGxsChannels::createVote + virtual bool createVote(const RsGxsGroupId& groupId, + const RsGxsMessageId& threadId, + const RsGxsMessageId& commentMessageId, + const RsGxsId& authorId, + uint32_t voteType, + RsGxsMessageId& voteMessageId, + std::string& error_message); /// Implementation of @see RsGxsChannels::subscribeToChannel virtual bool subscribeToChannel( const RsGxsGroupId &groupId, From 7504964899aa924e0393464a139c961525224270 Mon Sep 17 00:00:00 2001 From: RetroPooh Date: Wed, 3 Apr 2019 17:29:13 +0300 Subject: [PATCH 60/81] display session traffic --- libretroshare/src/pqi/pqi_base.h | 18 +++++++++++++++++- libretroshare/src/pqi/pqihandler.cc | 11 ++++++++++- libretroshare/src/pqi/pqihandler.h | 4 ++++ libretroshare/src/pqi/pqiperson.cc | 7 +++++++ libretroshare/src/pqi/pqiperson.h | 1 + libretroshare/src/pqi/pqistreamer.cc | 5 +++-- libretroshare/src/rsserver/p3serverconfig.cc | 6 +++++- libretroshare/src/rsserver/p3serverconfig.h | 1 + retroshare-gui/src/gui/MainWindow.cpp | 5 ++++- .../src/gui/statusbar/ratesstatus.cpp | 9 +++++---- retroshare-gui/src/gui/statusbar/ratesstatus.h | 2 +- 11 files changed, 58 insertions(+), 11 deletions(-) diff --git a/libretroshare/src/pqi/pqi_base.h b/libretroshare/src/pqi/pqi_base.h index a7d06c644..bafd8b572 100644 --- a/libretroshare/src/pqi/pqi_base.h +++ b/libretroshare/src/pqi/pqi_base.h @@ -192,7 +192,7 @@ class NetInterface; class PQInterface: public RateInterface { public: - explicit PQInterface(const RsPeerId &id) :peerId(id) { return; } + explicit PQInterface(const RsPeerId &id) :peerId(id), traf_in(0), traf_out(0) { return; } virtual ~PQInterface() { return; } /*! @@ -234,6 +234,22 @@ class PQInterface: public RateInterface const sockaddr_storage & /*remote_peer_address*/) { return 0; } + virtual uint64_t getTraffic(bool in) + { + uint64_t ret = 0; + if (in) + { + ret = traf_in; + traf_in = 0; + return ret; + } + ret = traf_out; + traf_out = 0; + return ret; + } + uint64_t traf_in; + uint64_t traf_out; + private: RsPeerId peerId; diff --git a/libretroshare/src/pqi/pqihandler.cc b/libretroshare/src/pqi/pqihandler.cc index a589f7e26..a5e79c9ff 100644 --- a/libretroshare/src/pqi/pqihandler.cc +++ b/libretroshare/src/pqi/pqihandler.cc @@ -87,6 +87,8 @@ pqihandler::pqihandler() : coreMtx("pqihandler") rateMax_in = 0.01; rateTotal_in = 0.0 ; rateTotal_out = 0.0 ; + traffInSum = 0; + traffOutSum = 0; last_m = time(NULL) ; nb_ticks = 0 ; mLastRateCapUpdate = 0 ; @@ -375,6 +377,9 @@ int pqihandler::UpdateRates() { SearchModule *mod = (it -> second); float crate_in = mod -> pqi -> getRate(true); + + traffInSum += mod -> pqi -> getTraffic(true); + traffOutSum += mod -> pqi -> getTraffic(false); #ifdef PQI_HDL_DEBUG_UR if(crate_in > 0.0) @@ -544,4 +549,8 @@ void pqihandler::locked_StoreCurrentRates(float in, float out) rateTotal_out = out; } - +void pqihandler::GetTraffic(uint64_t &in, uint64_t &out) +{ + in = traffInSum; + out = traffOutSum; +} diff --git a/libretroshare/src/pqi/pqihandler.h b/libretroshare/src/pqi/pqihandler.h index cf1f19429..126b82615 100644 --- a/libretroshare/src/pqi/pqihandler.h +++ b/libretroshare/src/pqi/pqihandler.h @@ -91,6 +91,10 @@ class pqihandler: public P3Interface, public pqiPublisher int ExtractRates(std::map &ratemap, RsBwRates &totals); int ExtractTrafficInfo(std::list &out_lst, std::list &in_lst); + uint64_t traffInSum; + uint64_t traffOutSum; + void GetTraffic(uint64_t &in, uint64_t &out); + protected: /* check to be overloaded by those that can * generates warnings otherwise diff --git a/libretroshare/src/pqi/pqiperson.cc b/libretroshare/src/pqi/pqiperson.cc index 7f33a3e1b..aa8096d7b 100644 --- a/libretroshare/src/pqi/pqiperson.cc +++ b/libretroshare/src/pqi/pqiperson.cc @@ -647,6 +647,13 @@ float pqiperson::getRate(bool in) return activepqi -> getRate(in); } +uint64_t pqiperson::getTraffic(bool in) +{ + if ((!active) || (activepqi == NULL)) + return 0; + return activepqi -> getTraffic(in); +} + void pqiperson::setMaxRate(bool in, float val) { RS_STACK_MUTEX(mPersonMtx); diff --git a/libretroshare/src/pqi/pqiperson.h b/libretroshare/src/pqi/pqiperson.h index 69faec48c..5c74502b0 100644 --- a/libretroshare/src/pqi/pqiperson.h +++ b/libretroshare/src/pqi/pqiperson.h @@ -149,6 +149,7 @@ public: virtual int getQueueSize(bool in); virtual void getRates(RsBwRates &rates); virtual float getRate(bool in); + virtual uint64_t getTraffic(bool in); virtual void setMaxRate(bool in, float val); virtual void setRateCap(float val_in, float val_out); virtual int gatherStatistics(std::list& outqueue_lst, diff --git a/libretroshare/src/pqi/pqistreamer.cc b/libretroshare/src/pqi/pqistreamer.cc index 839a5364e..e990ee20b 100644 --- a/libretroshare/src/pqi/pqistreamer.cc +++ b/libretroshare/src/pqi/pqistreamer.cc @@ -221,6 +221,7 @@ float pqistreamer::getRate(bool b) RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ return RateInterface::getRate(b) ; } + void pqistreamer::setMaxRate(bool b,float f) { RsStackMutex stack(mStreamerMtx); /**** LOCKED MUTEX ****/ @@ -1231,7 +1232,7 @@ void pqistreamer::outSentBytes_locked(uint32_t outb) mTotalSent += outb; mCurrSent += outb; mAvgSentCount += outb; - + PQInterface::traf_out += outb; return; } @@ -1248,7 +1249,7 @@ void pqistreamer::inReadBytes_locked(uint32_t inb) mTotalRead += inb; mCurrRead += inb; mAvgReadCount += inb; - + PQInterface::traf_in += inb; return; } diff --git a/libretroshare/src/rsserver/p3serverconfig.cc b/libretroshare/src/rsserver/p3serverconfig.cc index eab0f5722..0154427f5 100644 --- a/libretroshare/src/rsserver/p3serverconfig.cc +++ b/libretroshare/src/rsserver/p3serverconfig.cc @@ -564,4 +564,8 @@ int p3ServerConfig::GetCurrentDataRates( float &inKb, float &outKb ) return 1; } - +int p3ServerConfig::GetTrafficSum(uint64_t &inb, uint64_t &outb ) +{ + mPqiHandler->GetTraffic(inb, outb); + return 1; +} diff --git a/libretroshare/src/rsserver/p3serverconfig.h b/libretroshare/src/rsserver/p3serverconfig.h index 134558049..139b2b316 100644 --- a/libretroshare/src/rsserver/p3serverconfig.h +++ b/libretroshare/src/rsserver/p3serverconfig.h @@ -96,6 +96,7 @@ virtual bool setOperatingMode(const std::string &opModeStr); virtual int SetMaxDataRates( int downKb, int upKb ); virtual int GetMaxDataRates( int &downKb, int &upKb ); virtual int GetCurrentDataRates( float &inKb, float &outKb ); +virtual int GetTrafficSum( uint64_t &inb, uint64_t &outb ); /********************* ABOVE is RsConfig Interface *******/ diff --git a/retroshare-gui/src/gui/MainWindow.cpp b/retroshare-gui/src/gui/MainWindow.cpp index 6219575b5..77c98b031 100644 --- a/retroshare-gui/src/gui/MainWindow.cpp +++ b/retroshare-gui/src/gui/MainWindow.cpp @@ -726,9 +726,12 @@ void MainWindow::updateStatus() float downKb = 0; float upKb = 0; rsConfig->GetCurrentDataRates(downKb, upKb); + uint64_t down = 0; + uint64_t up = 0; + rsConfig->GetTrafficSum(down, up); if (ratesstatus) - ratesstatus->getRatesStatus(downKb, upKb); + ratesstatus->getRatesStatus(downKb, down, upKb, up); if(torstatus) torstatus->getTorStatus(); diff --git a/retroshare-gui/src/gui/statusbar/ratesstatus.cpp b/retroshare-gui/src/gui/statusbar/ratesstatus.cpp index c2289d153..1c78bbc6b 100644 --- a/retroshare-gui/src/gui/statusbar/ratesstatus.cpp +++ b/retroshare-gui/src/gui/statusbar/ratesstatus.cpp @@ -24,6 +24,7 @@ #include "ratesstatus.h" #include +#include "util/misc.h" #include @@ -48,13 +49,13 @@ RatesStatus::RatesStatus(QWidget *parent) setLayout(hbox); } -void RatesStatus::getRatesStatus(float downKb, float upKb) +void RatesStatus::getRatesStatus(float downKb, uint64_t down, float upKb, uint64_t upl) { /* set users/friends/network */ - QString normalText = QString("%1: %2 (kB/s) | %3: %4 (kB/s) ") - .arg(tr("Down")).arg(downKb, 0, 'f', 2) - .arg(tr("Up")).arg(upKb, 0, 'f', 2); + QString normalText = QString("%1: %2 kB/s (%3) | %4: %5 kB/s (%6)") + .arg(tr("Down")).arg(downKb, 0, 'f', 2).arg(misc::friendlyUnit(down)) + .arg(tr("Up")).arg(upKb, 0, 'f', 2).arg(misc::friendlyUnit(upl)); QString compactText = QString("%1|%2").arg(downKb, 0, 'f', 2).arg(upKb, 0, 'f', 2); if (statusRates) { diff --git a/retroshare-gui/src/gui/statusbar/ratesstatus.h b/retroshare-gui/src/gui/statusbar/ratesstatus.h index b0bfeb710..78c7475d6 100644 --- a/retroshare-gui/src/gui/statusbar/ratesstatus.h +++ b/retroshare-gui/src/gui/statusbar/ratesstatus.h @@ -32,7 +32,7 @@ class RatesStatus : public QWidget public: RatesStatus(QWidget *parent = 0); - void getRatesStatus(float downKb, float upKb); + void getRatesStatus(float downKb, uint64_t down, float upKb, uint64_t upl); void setCompactMode(bool compact) {_compactMode = compact; } private: From 683e3579aa1f80f61ac1c4dff954b8f7a6d43bf7 Mon Sep 17 00:00:00 2001 From: zapek Date: Wed, 3 Apr 2019 21:29:34 +0200 Subject: [PATCH 61/81] fixed wrong file hash daylight saving time warnings on windows --- libretroshare/src/file_sharing/hash_cache.cc | 8 -------- 1 file changed, 8 deletions(-) diff --git a/libretroshare/src/file_sharing/hash_cache.cc b/libretroshare/src/file_sharing/hash_cache.cc index 222bb81e0..fcb20c540 100644 --- a/libretroshare/src/file_sharing/hash_cache.cc +++ b/libretroshare/src/file_sharing/hash_cache.cc @@ -261,14 +261,6 @@ bool HashStorage::requestHash(const std::string& full_path,uint64_t size,rstime_ { it->second.time_stamp = now ; -#ifdef WINDOWS_SYS - if(it->second.time_stamp != (uint64_t)mod_time) - { - std::cerr << "(WW) detected a 1 hour shift in file modification time. This normally happens to many files at once, when daylight saving time shifts (file=\"" << full_path << "\")." << std::endl; - it->second.time_stamp = (uint64_t)mod_time; - } -#endif - known_hash = it->second.hash; #ifdef HASHSTORAGE_DEBUG std::cerr << "Found in cache." << std::endl ; From db9d202ab76505b7e76e0f3b4b7900920154469e Mon Sep 17 00:00:00 2001 From: csoler Date: Thu, 4 Apr 2019 22:41:02 +0200 Subject: [PATCH 62/81] fixed missign read-only flag on identity info display --- retroshare-gui/src/gui/Identity/IdDialog.ui | 24 +++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/retroshare-gui/src/gui/Identity/IdDialog.ui b/retroshare-gui/src/gui/Identity/IdDialog.ui index e571555a1..c940f763f 100644 --- a/retroshare-gui/src/gui/Identity/IdDialog.ui +++ b/retroshare-gui/src/gui/Identity/IdDialog.ui @@ -117,7 +117,7 @@ Qt::NoFocus - + :/icons/help_64.png:/icons/help_64.png @@ -284,7 +284,7 @@ 0 0 1372 - 1000 + 999 @@ -562,7 +562,11 @@ border-image: url(:/images/closepressed.png)
- + + + true + + @@ -646,7 +650,11 @@ p, li { white-space: pre-wrap; } - + + + true + + @@ -891,7 +899,11 @@ p, li { white-space: pre-wrap; } - + + + true + + @@ -1087,8 +1099,8 @@ p, li { white-space: pre-wrap; } idTreeWidget - + From 61aeae67ea16c09c506856fd8c9acc2121e8425f Mon Sep 17 00:00:00 2001 From: csoler Date: Thu, 4 Apr 2019 22:52:25 +0200 Subject: [PATCH 63/81] disable auto-ban identities for own IDs --- retroshare-gui/src/gui/Identity/IdDialog.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/retroshare-gui/src/gui/Identity/IdDialog.cpp b/retroshare-gui/src/gui/Identity/IdDialog.cpp index 703405bb0..d9e06df09 100644 --- a/retroshare-gui/src/gui/Identity/IdDialog.cpp +++ b/retroshare-gui/src/gui/Identity/IdDialog.cpp @@ -1878,6 +1878,7 @@ void IdDialog::insertIdDetails(uint32_t token) if (isOwnId) { mStateHelper->setWidgetEnabled(ui->ownOpinion_CB, false); + mStateHelper->setWidgetEnabled(ui->autoBanIdentities_CB, false); ui->editIdentity->setEnabled(true); ui->removeIdentity->setEnabled(true); ui->chatIdentity->setEnabled(false); @@ -1887,6 +1888,7 @@ void IdDialog::insertIdDetails(uint32_t token) { // No Reputation yet! mStateHelper->setWidgetEnabled(ui->ownOpinion_CB, true); + mStateHelper->setWidgetEnabled(ui->autoBanIdentities_CB, true); ui->editIdentity->setEnabled(false); ui->removeIdentity->setEnabled(false); ui->chatIdentity->setEnabled(true); @@ -2086,7 +2088,7 @@ void IdDialog::modifyReputation() case 2: op = RsOpinion::POSITIVE; break; default: std::cerr << "Wrong value from opinion combobox. Bug??" << std::endl; - break; + return; } rsReputations->setOwnOpinion(id,op); From 5ab75d0308426d15addeca2c7f7dc2571727c37d Mon Sep 17 00:00:00 2001 From: Phenom Date: Thu, 4 Apr 2019 20:55:23 +0200 Subject: [PATCH 64/81] Fix AppVeyor build --- appveyor.yml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 42d2f0a58..420e0bb9b 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -85,7 +85,8 @@ environment: # - cmd: echo This is batch again # - cmd: set MY_VAR=12345 install: - - git submodule update --init + # We cannot get OBS submodule as it use illegal folder name for windows. + #- git submodule update --init # Configuring MSys2 - set PATH=C:\msys64\usr\bin;%PATH% - set PATH=C:\msys64\mingw32\bin;%PATH% @@ -195,11 +196,13 @@ after_build: - windeployqt %RS_DEPLOY%\retroshare.exe - copy C:\msys64\mingw32\bin\libbz2*.dll %RS_DEPLOY%\ - - copy C:\msys64\mingw32\bin\libeay32.dll %RS_DEPLOY%\ + #- copy C:\msys64\mingw32\bin\libeay32.dll %RS_DEPLOY%\ + - copy C:\OpenSSL-Win32\libeay32.dll %RS_DEPLOY%\ - copy C:\msys64\mingw32\bin\libminiupnpc.dll %RS_DEPLOY%\ - copy C:\msys64\mingw32\bin\libsqlcipher*.dll %RS_DEPLOY%\ - copy C:\msys64\mingw32\bin\libsqlite3*.dll %RS_DEPLOY%\ - - copy C:\msys64\mingw32\bin\ssleay32.dll %RS_DEPLOY%\ + #- copy C:\msys64\mingw32\bin\ssleay32.dll %RS_DEPLOY%\ + - copy C:\OpenSSL-Win32\ssleay32.dll %RS_DEPLOY%\ - copy C:\msys64\mingw32\bin\zlib*.dll %RS_DEPLOY%\ - copy C:\msys64\mingw32\bin\libgcc_s_dw2*.dll %RS_DEPLOY%\ - copy C:\msys64\mingw32\bin\libstdc*.dll %RS_DEPLOY%\ From ab80d9a374434ec85fa00682121c7a44a72c1a29 Mon Sep 17 00:00:00 2001 From: Gioacchino Mazzurco Date: Fri, 5 Apr 2019 01:43:23 +0200 Subject: [PATCH 65/81] Fix compilation, retrocompatibility and enums Workaround miss-behaviour on old Android phones Cleanup indentation a bit Consistent param naming Introduce default parameter values also for output paramethers --- libretroshare/src/retroshare/rsgxschannels.h | 191 ++++--- libretroshare/src/retroshare/rsgxscircles.h | 69 ++- libretroshare/src/retroshare/rsgxscommon.h | 24 +- .../src/retroshare/rsgxsifacehelper.h | 44 +- libretroshare/src/retroshare/rstokenservice.h | 13 +- libretroshare/src/services/p3gxschannels.cc | 485 +++++++++++------- libretroshare/src/services/p3gxschannels.h | 120 ++--- libretroshare/src/util/rsmemory.h | 3 + 8 files changed, 584 insertions(+), 365 deletions(-) diff --git a/libretroshare/src/retroshare/rsgxschannels.h b/libretroshare/src/retroshare/rsgxschannels.h index 9f76aec84..b341a4448 100644 --- a/libretroshare/src/retroshare/rsgxschannels.h +++ b/libretroshare/src/retroshare/rsgxschannels.h @@ -4,7 +4,7 @@ * libretroshare: retroshare core library * * * * Copyright (C) 2012 Robert Fernie * - * Copyright (C) 2018 Gioacchino Mazzurco * + * Copyright (C) 2018-2019 Gioacchino Mazzurco * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * @@ -33,6 +33,8 @@ #include "serialiser/rsserializable.h" #include "retroshare/rsturtle.h" #include "util/rsdeprecate.h" +#include "retroshare/rsgxscircles.h" +#include "util/rsmemory.h" class RsGxsChannels; @@ -99,94 +101,101 @@ public: explicit RsGxsChannels(RsGxsIface& gxs) : RsGxsIfaceHelper(gxs) {} virtual ~RsGxsChannels() {} -#ifdef REMOVED /** * @brief Create channel. Blocking API. * @jsonapi{development} - * @param[inout] channel Channel data (name, description...) - * @return false on error, true otherwise + * @param[in] name Name of the channel + * @param[in] description Description of the channel + * @param[in] thumbnail Optional image to show as channel thumbnail. + * @param[in] authorId Optional id of the author. Leave empty for an + * anonymous channel. + * @param[in] circleType Optional visibility rule, default public. + * @param[in] circleId If the channel is not public specify the id of the + * circle who can see the channel. Depending on the value you pass for + * circleType this should be be an external circle if EXTERNAL is passed, a + * local friend group id if NODES_GROUP is passed, empty otherwise. + * @param[out] channelId Optional storage for the id of the created channel, + * meaningful only if creations succeeds. + * @param[out] errorMessage Optional storage for error messsage, meaningful + * only if creation fail. + * @return False on error, true otherwise. */ - virtual bool createChannel(RsGxsChannelGroup& channel) = 0; -#endif - - /** - * @brief Create channel. Blocking API. - * @jsonapi{development} - * @param[in] name Name of the channel - * @param[in] description Description of the channel - * @param[in] image Thumbnail that is shown to advertise the channel. Possibly empty. - * @param[in] author_id GxsId of the contact author. For an anonymous channel, leave this to RsGxsId()="00000....0000" - * @param[in] circle_type Type of visibility restriction, among { GXS_CIRCLE_TYPE_PUBLIC, GXS_CIRCLE_TYPE_EXTERNAL, GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY, GXS_CIRCLE_TYPE_YOUR_EYES_ONLY } - * @param[in] circle_id Id of the circle (should be an external circle for GXS_CIRCLE_TYPE_EXTERNAL, a local friend group for GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY, GxsCircleId()="000....000" otherwise - * @param[out] channel_group_id Group id of the created channel, if command succeeds. - * @param[out] error_message Error messsage supplied when the channel creation fails. - * @return False on error, true otherwise. - */ - virtual bool createChannel(const std::string& name, - const std::string& description, - const RsGxsImage& image, - const RsGxsId& author_id, - uint32_t circle_type, - RsGxsCircleId& circle_id, - RsGxsGroupId& channel_group_id, - std::string& error_message )=0; + virtual bool createChannelV2( + const std::string& name, const std::string& description, + const RsGxsImage& thumbnail = RsGxsImage(), + const RsGxsId& authorId = RsGxsId(), + RsGxsCircleType circleType = RsGxsCircleType::PUBLIC, + const RsGxsCircleId& circleId = RsGxsCircleId(), + RsGxsGroupId& channelId = RS_DEFAULT_STORAGE_PARAM(RsGxsGroupId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) ) = 0; /** * @brief Add a comment on a post or on another comment * @jsonapi{development} - * @param[in] groupId Id of the channel in which the comment is to be posted - * @param[in] parentMsgId Id of the parent of the comment that is either a channel post Id or the Id of another comment. - * @param[in] comment UTF-8 string containing the comment - * @param[out] commentMessageId Id of the comment that was created - * @param[out] error_string Error message supplied when the comment creation fails. + * @param[in] channelId Id of the channel in which the comment is to be posted + * @param[in] parentId Id of the parent of the comment that is either a + * channel post Id or the Id of another comment. + * @param[in] comment UTF-8 string containing the comment + * @param[out] commentMessageId Optional storage for the id of the comment + * that was created, meaningful only on success. + * @param[out] errorMessage Optional storage for error message, meaningful + * only on failure. * @return false on error, true otherwise */ - virtual bool createComment(const RsGxsGroupId& groupId, - const RsGxsMessageId& parentMsgId, - const std::string& comment, - RsGxsMessageId& commentMessageId, - std::string& error_message )=0; + virtual bool createCommentV2( + const RsGxsGroupId& channelId, const RsGxsMessageId& parentId, + const std::string& comment, + RsGxsMessageId& commentMessageId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) )=0; /** * @brief Create channel post. Blocking API. * @jsonapi{development} - * @param[in] groupId Id of the channel where to put the post (publish rights needed!) - * @param[in] origMsgId Id of the post you are replacing. If left blank (RsGxsMssageId()="0000.....0000", a new post will be created - * @param[in] msgName Title of the post - * @param[in] msg Text content of the post - * @param[in] files List of attached files. These are supposed to be shared otherwise (use ExtraFileHash() below) - * @param[in] thumbnail Image displayed in the list of posts. Can be left blank. - * @param[out] messsageId Id of the message that was created - * @param[out] error_message Error text if anything bad happens + * @param[in] channelId Id of the channel where to put the post. Beware you + * need publish rights on that channel to post. + * @param[in] title Title of the post + * @param[in] mBody Text content of the post + * @param[in] files Optional list of attached files. These are supposed to + * be already shared, @see ExtraFileHash() below otherwise. + * @param[in] thumbnail Optional thumbnail image for the post. + * @param[in] origPostId If this is supposed to replace an already existent + * post, the id of the old post. If left blank a new post will be created. + * @param[out] postId Optional storage for the id of the created post, + * meaningful only on success. + * @param[out] errorMessage Optional storage for the error message, + * meaningful only on failure. * @return false on error, true otherwise */ - virtual bool createPost(const RsGxsGroupId& groupId, - const RsGxsMessageId& origMsgId, - const std::string& msgName, - const std::string& msg, - const std::list& files, - const RsGxsImage& thumbnail, - RsGxsMessageId& messageId, - std::string& error_message) = 0; + virtual bool createPostV2( + const RsGxsGroupId& channelId, const std::string& title, + const std::string& mBody, + const std::list& files = std::list(), + const RsGxsImage& thumbnail = RsGxsImage(), + const RsGxsMessageId& origPostId = RsGxsMessageId(), + RsGxsMessageId& postId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) ) = 0; + /** - * @brief createVote + * @brief Create a vote * @jsonapi{development} - * @param[in] groupId Id of the channel where to put the post (publish rights needed!) - * @param[in] threadId Id of the channel post in which a comment is voted - * @param[in] commentMesssageId Id of the comment that is voted - * @param[in] authorId Id of the author. Needs to be your identity. - * @param[in] voteType Type of vote (GXS_VOTE_NONE=0x00, GXS_VOTE_DOWN=0x01, GXS_VOTE_UP=0x02) - * @param[out] voteMessageId Id of the vote message produced - * @param[out] error_message Error text if anything bad happens + * @param[in] channelId Id of the channel where to vote + * @param[in] postId Id of the channel post of which a comment is voted + * @param[in] commentId Id of the comment that is voted + * @param[in] authorId Id of the author. Needs to be of an owned identity. + * @param[in] vote Vote value, either RsGxsVoteType::DOWN or + * RsGxsVoteType::UP + * @param[out] voteId Optional storage for the id of the created vote, + * meaningful only on success. + * @param[out] errorMessage Optional storage for error message, meaningful + * only on failure. * @return false on error, true otherwise */ - virtual bool createVote( const RsGxsGroupId& groupId, - const RsGxsMessageId& threadId, - const RsGxsMessageId& commentMessageId, - const RsGxsId& authorId, - uint32_t voteType, - RsGxsMessageId& voteMessageId, - std::string& error_message)=0; + virtual bool createVoteV2( + const RsGxsGroupId& channelId, const RsGxsMessageId& postId, + const RsGxsMessageId& commentId, const RsGxsId& authorId, + RsGxsVoteType vote, + RsGxsMessageId& voteId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) ) = 0; /** * @brief Edit channel details. @@ -372,6 +381,16 @@ public: /* Following functions are deprecated as they expose internal functioning * semantic, instead of a safe to use API */ + /** + * @brief Create channel. Blocking API. + * @jsonapi{development} + * @deprecated { substituted by createChannelV2 } + * @param[inout] channel Channel data (name, description...) + * @return false on error, true otherwise + */ + RS_DEPRECATED_FOR(createChannelV2) + virtual bool createChannel(RsGxsChannelGroup& channel) = 0; + RS_DEPRECATED_FOR(getChannelsInfo) virtual bool getGroupData(const uint32_t &token, std::vector &groups) = 0; @@ -429,9 +448,29 @@ public: * @param[in] group Channel data (name, description...) * @return false on error, true otherwise */ - RS_DEPRECATED_FOR(createChannel) + RS_DEPRECATED_FOR(createChannelV2) virtual bool createGroup(uint32_t& token, RsGxsChannelGroup& group) = 0; + /** + * @brief Add a comment on a post or on another comment + * @jsonapi{development} + * @deprecated + * @param[inout] comment + * @return false on error, true otherwise + */ + RS_DEPRECATED_FOR(createCommentV2) + virtual bool createComment(RsGxsComment& comment) = 0; + + /** + * @brief Create channel post. Blocking API. + * @jsonapi{development} + * @deprecated + * @param[inout] post + * @return false on error, true otherwise + */ + RS_DEPRECATED_FOR(createPostV2) + virtual bool createPost(RsGxsChannelPost& post) = 0; + /** * @brief Request post creation. * The action is performed asyncronously, so it could fail in a subsequent @@ -442,9 +481,19 @@ public: * @param[in] post * @return false on error, true otherwise */ - RS_DEPRECATED + RS_DEPRECATED_FOR(createPostV2) virtual bool createPost(uint32_t& token, RsGxsChannelPost& post) = 0; + /** + * @brief createVote + * @jsonapi{development} + * @deprecated + * @param[inout] vote + * @return false on error, true otherwise + */ + RS_DEPRECATED_FOR(createVoteV2) + virtual bool createVote(RsGxsVote& vote) = 0; + /** * @brief Request channel change. * The action is performed asyncronously, so it could fail in a subsequent diff --git a/libretroshare/src/retroshare/rsgxscircles.h b/libretroshare/src/retroshare/rsgxscircles.h index d5f3543d0..83f8e840c 100644 --- a/libretroshare/src/retroshare/rsgxscircles.h +++ b/libretroshare/src/retroshare/rsgxscircles.h @@ -42,24 +42,35 @@ class RsGxsCircles; */ extern RsGxsCircles* rsGxsCircles; +enum class RsGxsCircleType : uint32_t // 32 bit overkill, just for retrocompat +{ + UNKNOWN = 0, /// Used to detect uninizialized values. + PUBLIC = 1, /// Public distribution + EXTERNAL = 2, /// Restricted to an external circle -// TODO: convert to enum -/// The meaning of the different circle types is: -static const uint32_t GXS_CIRCLE_TYPE_UNKNOWN = 0x0000 ; /// Used to detect uninizialized values. -static const uint32_t GXS_CIRCLE_TYPE_PUBLIC = 0x0001 ; // not restricted to a circle -static const uint32_t GXS_CIRCLE_TYPE_EXTERNAL = 0x0002 ; // restricted to an external circle, made of RsGxsId -static const uint32_t GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY = 0x0003 ; // restricted to a subset of friend nodes of a given RS node given by a RsPgpId list -static const uint32_t GXS_CIRCLE_TYPE_LOCAL = 0x0004 ; // not distributed at all -static const uint32_t GXS_CIRCLE_TYPE_EXT_SELF = 0x0005 ; // self-restricted. Not used, except at creation time when the circle ID isn't known yet. Set to EXTERNAL afterwards. -static const uint32_t GXS_CIRCLE_TYPE_YOUR_EYES_ONLY = 0x0006 ; // distributed to nodes signed by your own PGP key only. + /** Restricted to a group of friend nodes, the administrator of the circle + * behave as a hub for them */ + NODES_GROUP = 3, + LOCAL = 4, /// not distributed at all + + /** Self-restricted. Used only at creation time of self-restricted circles + * when the circle id isn't known yet. Once the circle id is known the type + * is set to EXTERNAL, and the external circle id is set to the id of the + * circle itself. + */ + EXT_SELF = 5, + + /// distributed to nodes signed by your own PGP key only. + YOUR_EYES_ONLY = 6 +}; + +// TODO: convert to enum class static const uint32_t GXS_EXTERNAL_CIRCLE_FLAGS_IN_ADMIN_LIST = 0x0001 ;// user is validated by circle admin static const uint32_t GXS_EXTERNAL_CIRCLE_FLAGS_SUBSCRIBED = 0x0002 ;// user has subscribed the group static const uint32_t GXS_EXTERNAL_CIRCLE_FLAGS_KEY_AVAILABLE = 0x0004 ;// key is available, so we can encrypt for this circle static const uint32_t GXS_EXTERNAL_CIRCLE_FLAGS_ALLOWED = 0x0007 ;// user is allowed. Combines all flags above. -static const uint32_t GXS_CIRCLE_FLAGS_IS_EXTERNAL = 0x0008 ;// user is allowed - struct RsGxsCircleGroup : RsSerializable { @@ -110,8 +121,9 @@ struct RsGxsCircleMsg : RsSerializable struct RsGxsCircleDetails : RsSerializable { RsGxsCircleDetails() : - mCircleType(GXS_CIRCLE_TYPE_EXTERNAL), mAmIAllowed(false) {} - ~RsGxsCircleDetails() {} + mCircleType(static_cast(RsGxsCircleType::EXTERNAL)), + mAmIAllowed(false) {} + ~RsGxsCircleDetails() override {} RsGxsCircleId mCircleId; std::string mCircleName; @@ -264,3 +276,34 @@ public: RS_DEPRECATED_FOR("editCircle, inviteIdsToCircle") virtual void updateGroup(uint32_t &token, RsGxsCircleGroup &group) = 0; }; + + +/// @deprecated Used to detect uninizialized values. +RS_DEPRECATED_FOR("RsGxsCircleType::UNKNOWN") +static const uint32_t GXS_CIRCLE_TYPE_UNKNOWN = 0x0000; + +/// @deprecated not restricted to a circle +RS_DEPRECATED_FOR("RsGxsCircleType::PUBLIC") +static const uint32_t GXS_CIRCLE_TYPE_PUBLIC = 0x0001; + +/// @deprecated restricted to an external circle, made of RsGxsId +RS_DEPRECATED_FOR("RsGxsCircleType::EXTERNAL") +static const uint32_t GXS_CIRCLE_TYPE_EXTERNAL = 0x0002; + +/// @deprecated restricted to a subset of friend nodes of a given RS node given +/// by a RsPgpId list +RS_DEPRECATED_FOR("RsGxsCircleType::NODES_GROUP") +static const uint32_t GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY = 0x0003; + +/// @deprecated not distributed at all +RS_DEPRECATED_FOR("RsGxsCircleType::LOCAL") +static const uint32_t GXS_CIRCLE_TYPE_LOCAL = 0x0004; + +/// @deprecated self-restricted. Not used, except at creation time when the +/// circle ID isn't known yet. Set to EXTERNAL afterwards. +RS_DEPRECATED_FOR("RsGxsCircleType::EXT_SELF") +static const uint32_t GXS_CIRCLE_TYPE_EXT_SELF = 0x0005; + +/// @deprecated distributed to nodes signed by your own PGP key only. +RS_DEPRECATED_FOR("RsGxsCircleType::YOUR_EYES_ONLY") +static const uint32_t GXS_CIRCLE_TYPE_YOUR_EYES_ONLY = 0x0006; diff --git a/libretroshare/src/retroshare/rsgxscommon.h b/libretroshare/src/retroshare/rsgxscommon.h index c8b8ec7a4..aded69f83 100644 --- a/libretroshare/src/retroshare/rsgxscommon.h +++ b/libretroshare/src/retroshare/rsgxscommon.h @@ -19,11 +19,9 @@ * along with this program. If not, see . * * * *******************************************************************************/ +#pragma once -#ifndef RETROSHARE_GXS_COMMON_OBJS_INTERFACE_H -#define RETROSHARE_GXS_COMMON_OBJS_INTERFACE_H - -#include +#include #include #include @@ -79,10 +77,12 @@ struct RsGxsImage : RsSerializable } }; - -#define GXS_VOTE_NONE 0x0000 -#define GXS_VOTE_DOWN 0x0001 -#define GXS_VOTE_UP 0x0002 +enum class RsGxsVoteType : uint32_t +{ + NONE = 0, /// Used to detect unset vote? + DOWN = 1, /// Negative vote + UP = 2 /// Positive vote +}; // Status Flags to indicate Voting.... @@ -181,7 +181,11 @@ struct RsGxsCommentService std::pair& msgId ) = 0; }; +/// @deprecated use RsGxsVoteType::NONE instead @see RsGxsVoteType +#define GXS_VOTE_NONE 0x0000 +/// @deprecated use RsGxsVoteType::DOWN instead @see RsGxsVoteType +#define GXS_VOTE_DOWN 0x0001 -#endif - +/// @deprecated use RsGxsVoteType::UP instead @see RsGxsVoteType +#define GXS_VOTE_UP 0x0002 diff --git a/libretroshare/src/retroshare/rsgxsifacehelper.h b/libretroshare/src/retroshare/rsgxsifacehelper.h index 09cf40dbf..f19d8720c 100644 --- a/libretroshare/src/retroshare/rsgxsifacehelper.h +++ b/libretroshare/src/retroshare/rsgxsifacehelper.h @@ -4,7 +4,7 @@ * libretroshare: retroshare core library * * * * Copyright 2011 by Christopher Evi-Parker * - * Copyright (C) 2018 Gioacchino Mazzurco * + * Copyright (C) 2018-2019 Gioacchino Mazzurco * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * @@ -20,9 +20,7 @@ * along with this program. If not, see . * * * *******************************************************************************/ - -#ifndef RSGXSIFACEIMPL_H -#define RSGXSIFACEIMPL_H +#pragma once #include #include @@ -292,19 +290,51 @@ protected: * Useful for blocking API implementation. * @param[in] token token associated to the request caller is waiting for * @param[in] maxWait maximum waiting time in milliseconds + * @param[in] checkEvery time in millisecond between status checks */ RsTokenService::GxsRequestStatus waitToken( uint32_t token, - std::chrono::milliseconds maxWait = std::chrono::milliseconds(500) ) + std::chrono::milliseconds maxWait = std::chrono::milliseconds(500), + std::chrono::milliseconds checkEvery = std::chrono::milliseconds(2)) { +#if defined(__ANDROID__) && (__ANDROID_API__ < 24) + auto wkStartime = std::chrono::steady_clock::now(); + int maxWorkAroundCnt = 10; +LLwaitTokenBeginLabel: +#endif auto timeout = std::chrono::steady_clock::now() + maxWait; auto st = requestStatus(token); while( !(st == RsTokenService::FAILED || st >= RsTokenService::COMPLETE) && std::chrono::steady_clock::now() < timeout ) { - std::this_thread::sleep_for(std::chrono::milliseconds(2)); + std::this_thread::sleep_for(checkEvery); st = requestStatus(token); } + +#if defined(__ANDROID__) && (__ANDROID_API__ < 24) + /* Work around for very slow/old android devices, we don't expect this + * to be necessary on newer devices. If it take unreasonably long + * something worser is already happening elsewere amd we return anyway. + */ + if( st > RsTokenService::FAILED && st < RsTokenService::COMPLETE + && maxWorkAroundCnt-- > 0 ) + { + maxWait *= 10; + checkEvery *= 3; + std::cerr << __PRETTY_FUNCTION__ << " Slow Android device " + << " workaround st: " << st + << " maxWorkAroundCnt: " << maxWorkAroundCnt + << " maxWait: " << maxWait.count() + << " checkEvery: " << checkEvery.count() << std::endl; + goto LLwaitTokenBeginLabel; + } + std::cerr << __PRETTY_FUNCTION__ << " lasted: " + << std::chrono::duration_cast( + std::chrono::steady_clock::now() - wkStartime ).count() + << "ms" << std::endl; + +#endif + return st; } @@ -312,5 +342,3 @@ private: RsGxsIface& mGxs; RsTokenService& mTokenService; }; - -#endif // RSGXSIFACEIMPL_H diff --git a/libretroshare/src/retroshare/rstokenservice.h b/libretroshare/src/retroshare/rstokenservice.h index 58314c62f..515579a07 100644 --- a/libretroshare/src/retroshare/rstokenservice.h +++ b/libretroshare/src/retroshare/rstokenservice.h @@ -121,15 +121,14 @@ public: enum GxsRequestStatus : uint8_t { - FAILED, - PENDING, - PARTIAL, - COMPLETE, - DONE, /// Once all data has been retrived - CANCELLED + FAILED = 0, + PENDING = 1, + PARTIAL = 2, + COMPLETE = 3, + DONE = 4, /// Once all data has been retrived + CANCELLED = 5 }; - RsTokenService() {} virtual ~RsTokenService() {} diff --git a/libretroshare/src/services/p3gxschannels.cc b/libretroshare/src/services/p3gxschannels.cc index e1fdd9281..b3ff3f78e 100644 --- a/libretroshare/src/services/p3gxschannels.cc +++ b/libretroshare/src/services/p3gxschannels.cc @@ -4,7 +4,7 @@ * libretroshare: retroshare core library * * * * Copyright (C) 2012 Robert Fernie * - * Copyright (C) 2018 Gioacchino Mazzurco * + * Copyright (C) 2018-2019 Gioacchino Mazzurco * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * @@ -38,6 +38,7 @@ #include #include +#include // For Dummy Msgs. #include "util/rsrandom.h" @@ -1056,108 +1057,115 @@ bool p3GxsChannels::getChannelContent( const RsGxsGroupId& channelId, return getPostData(token, posts, comments); } -bool p3GxsChannels::createChannel(const std::string& name, - const std::string& description, - const RsGxsImage& image, - const RsGxsId& author_id, - uint32_t circle_type, - RsGxsCircleId& circle_id, - RsGxsGroupId& channel_group_id, - std::string& error_message) +bool p3GxsChannels::createChannelV2( + const std::string& name, const std::string& description, + const RsGxsImage& thumbnail, const RsGxsId& authorId, + RsGxsCircleType circleType, const RsGxsCircleId& circleId, + RsGxsGroupId& channelId, std::string& errorMessage ) { - // do some checks + // do some checks - if( circle_type != GXS_CIRCLE_TYPE_PUBLIC - && circle_type != GXS_CIRCLE_TYPE_EXTERNAL - && circle_type != GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY - && circle_type != GXS_CIRCLE_TYPE_LOCAL - && circle_type != GXS_CIRCLE_TYPE_YOUR_EYES_ONLY ) - { - error_message = std::string("circle_type has a non allowed value") ; - return false ; - } + if( circleType != RsGxsCircleType::PUBLIC + && circleType != RsGxsCircleType::EXTERNAL + && circleType != RsGxsCircleType::NODES_GROUP + && circleType != RsGxsCircleType::LOCAL + && circleType != RsGxsCircleType::YOUR_EYES_ONLY) + { + errorMessage = "circleType has invalid value"; + return false; + } - switch(circle_type) - { - case GXS_CIRCLE_TYPE_EXTERNAL: - if(circle_id.isNull()) - { - error_message = std::string("circle_type is GXS_CIRCLE_TYPE_EXTERNAL but circle_id is null"); - return false ; - } - break; - - case GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY: - { - RsGroupInfo ginfo; - - if(!rsPeers->getGroupInfo(RsNodeGroupId(circle_id),ginfo)) - { - error_message = std::string("circle_type is GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY but circle_id is not set or does not correspond to a actual group of friends"); - return false; - } + switch(circleType) + { + case RsGxsCircleType::EXTERNAL: + if(circleId.isNull()) + { + errorMessage = "circleType is EXTERNAL but circleId is null"; + return false; } break; - default: - if(!circle_id.isNull()) - { - error_message = std::string("circle_type requires a null circle id, but a non null circle id (" + circle_id.toStdString() + ") was supplied"); - return false; - } - } + case RsGxsCircleType::NODES_GROUP: + { + RsGroupInfo ginfo; - // Create a consistent channel group meta from the information supplied + if(!rsPeers->getGroupInfo(RsNodeGroupId(circleId), ginfo)) + { + errorMessage = "circleType is NODES_GROUP but circleId does not " + "correspond to an actual group of friends"; + return false; + } + break; + } + default: + if(!circleId.isNull()) + { + errorMessage = "circleType requires a null circleId, but a non " + "null circleId ("; + errorMessage += circleId.toStdString(); + errorMessage += ") was supplied"; + return false; + } + break; + } - RsGxsChannelGroup channel ; + // Create a consistent channel group meta from the information supplied + RsGxsChannelGroup channel; - channel.mMeta.mGroupName = name ; - channel.mMeta.mAuthorId = author_id ; - channel.mMeta.mCircleType = circle_type ; + channel.mMeta.mGroupName = name; + channel.mMeta.mAuthorId = authorId; + channel.mMeta.mCircleType = static_cast(circleType); - channel.mMeta.mSignFlags = GXS_SERV::FLAG_GROUP_SIGN_PUBLISH_NONEREQ - | GXS_SERV::FLAG_AUTHOR_AUTHENTICATION_REQUIRED; + channel.mMeta.mSignFlags = GXS_SERV::FLAG_GROUP_SIGN_PUBLISH_NONEREQ + | GXS_SERV::FLAG_AUTHOR_AUTHENTICATION_REQUIRED; - channel.mMeta.mGroupFlags = GXS_SERV::FLAG_PRIVACY_PUBLIC; + channel.mMeta.mGroupFlags = GXS_SERV::FLAG_PRIVACY_PUBLIC; channel.mMeta.mCircleId.clear(); channel.mMeta.mInternalCircle.clear(); - if(circle_type == GXS_CIRCLE_TYPE_YOUR_FRIENDS_ONLY) - channel.mMeta.mInternalCircle = circle_id; - else if(circle_type == GXS_CIRCLE_TYPE_EXTERNAL) - channel.mMeta.mCircleId = circle_id; + switch(circleType) + { + case RsGxsCircleType::NODES_GROUP: + channel.mMeta.mInternalCircle = circleId; break; + case RsGxsCircleType::EXTERNAL: + channel.mMeta.mCircleId = circleId; break; + default: break; + } - // Create the channel - - channel.mDescription = description ; - channel.mImage = image ; + // Create the channel + channel.mDescription = description; + channel.mImage = thumbnail; uint32_t token; if(!createGroup(token, channel)) { - std::cerr << __PRETTY_FUNCTION__ << "Error! Failed creating group." + errorMessage = "Failed creating GXS group."; + std::cerr << __PRETTY_FUNCTION__ << " Error! " << errorMessage << std::endl; return false; } - // wait for the group creation to complete. - - if(waitToken(token) != RsTokenService::COMPLETE) + // wait for the group creation to complete. + RsTokenService::GxsRequestStatus wSt = waitToken(token); + if(wSt != RsTokenService::COMPLETE) { - std::cerr << __PRETTY_FUNCTION__ << "Error! GXS operation failed." + errorMessage = "GXS operation waitToken failed with: " + + std::to_string(wSt); + std::cerr << __PRETTY_FUNCTION__ << " Error! " << errorMessage << std::endl; return false; } if(!RsGenExchange::getPublishedGroupMeta(token, channel.mMeta)) { - std::cerr << __PRETTY_FUNCTION__ << "Error! Failure getting updated " - << " group data." << std::endl; + errorMessage = "Failure getting updated group data."; + std::cerr << __PRETTY_FUNCTION__ << " Error! " << errorMessage + << std::endl; return false; } - channel_group_id = channel.mMeta.mGroupId; + channelId = channel.mMeta.mGroupId; #ifdef RS_DEEP_SEARCH DeepSearch::indexChannelGroup(channel); @@ -1166,27 +1174,26 @@ bool p3GxsChannels::createChannel(const std::string& name, return true; } -#ifdef REMOVED bool p3GxsChannels::createChannel(RsGxsChannelGroup& channel) { uint32_t token; if(!createGroup(token, channel)) { - std::cerr << __PRETTY_FUNCTION__ << "Error! Failed creating group." + std::cerr << __PRETTY_FUNCTION__ << " Error! Failed creating group." << std::endl; return false; } if(waitToken(token) != RsTokenService::COMPLETE) { - std::cerr << __PRETTY_FUNCTION__ << "Error! GXS operation failed." + std::cerr << __PRETTY_FUNCTION__ << " Error! GXS operation failed." << std::endl; return false; } if(!RsGenExchange::getPublishedGroupMeta(token, channel.mMeta)) { - std::cerr << __PRETTY_FUNCTION__ << "Error! Failure getting updated " + std::cerr << __PRETTY_FUNCTION__ << " Error! Failure getting updated " << " group data." << std::endl; return false; } @@ -1197,91 +1204,126 @@ bool p3GxsChannels::createChannel(RsGxsChannelGroup& channel) return true; } -#endif -bool p3GxsChannels::createVote( const RsGxsGroupId& groupId, - const RsGxsMessageId & threadId, - const RsGxsMessageId& commentMessageId, - const RsGxsId& authorId, - uint32_t voteType, - RsGxsMessageId& voteMessageId, - std::string& error_message) +bool p3GxsChannels::createVoteV2( + const RsGxsGroupId& channelId, const RsGxsMessageId& postId, + const RsGxsMessageId& commentId, const RsGxsId& authorId, + RsGxsVoteType tVote, RsGxsMessageId& voteId, std::string& errorMessage ) { - // Do some checks - std::vector channelsInfo; - - if(!getChannelsInfo(std::list({groupId}),channelsInfo)) // does the channel actually exist? - { - error_message = std::string("Channel with Id " + groupId.toStdString() + " does not exist."); - return false; - } - - if(commentMessageId.isNull()) // has a correct comment msg id been supplied? - { - error_message = std::string("You cannot vote on null comment " + commentMessageId.toStdString() + " of channel with Id " + groupId.toStdString() + ": please supply a non null comment Id!"); + if(!getChannelsInfo(std::list({channelId}),channelsInfo)) + { + errorMessage = "Channel with Id " + channelId.toStdString() + + " does not exist."; return false; - } + } - std::set s({commentMessageId}); + if(commentId.isNull()) + { + errorMessage = "You cannot vote on null comment " + + commentId.toStdString(); + return false; + } + + std::set s({commentId}); std::vector posts; std::vector comments; - if(!getChannelContent( groupId,s,posts,comments )) // does the comment to vote actually exist? + if(!getChannelContent(channelId, s, posts, comments)) { - error_message = std::string("You cannot vote on comment " + commentMessageId.toStdString() + " of channel with Id " + groupId.toStdString() + ": this comment does not locally exist!"); + errorMessage = "You cannot vote on comment " + + commentId.toStdString() + " of channel with Id " + + channelId.toStdString() + + ": this comment does not exists locally!"; return false; } - if(posts.front().mMeta.mParentId.isNull()) // is the ID a comment ID or a post ID? It should be comment => should have a parent ID + // is the ID a comment ID or a post ID? + // It should be comment => should have a parent ID + if(posts.front().mMeta.mParentId.isNull()) { - error_message = std::string("You cannot vote on channel message " + commentMessageId.toStdString() + " of channel with Id " + groupId.toStdString() + ": this ID refers to a post, not a comment!"); + errorMessage = "You cannot vote on channel message " + + commentId.toStdString() + " of channel with Id " + + channelId.toStdString() + + ": given id refers to a post, not a comment!"; return false; } - if(voteType != GXS_VOTE_NONE && voteType != GXS_VOTE_UP && voteType != GXS_VOTE_DOWN) // is voteType consistent? - { - error_message = std::string("Your vote to channel with Id " + groupId.toStdString() + " has wrong vote type. Only GXS_VOTE_NONE, GXS_VOTE_UP, GXS_VOTE_DOWN accepted."); + if( tVote != RsGxsVoteType::NONE + && tVote != RsGxsVoteType::UP + && tVote != RsGxsVoteType::DOWN ) + { + errorMessage = "Your vote to channel with Id " + + channelId.toStdString() + " has wrong vote type. " + + " Only RsGxsVoteType::NONE, RsGxsVoteType::UP, " + + "RsGxsVoteType::DOWN are accepted."; return false; - } + } - if(!rsIdentity->isOwnId(authorId)) // is the voter ID actually ours? - { - error_message = std::string("You cannot vote to channel with Id " + groupId.toStdString() + " with identity " + authorId.toStdString() + " because it is not yours."); + if(!rsIdentity->isOwnId(authorId)) + { + errorMessage = "You cannot vote to channel with Id " + + channelId.toStdString() + " with identity " + + authorId.toStdString() + " because it is not yours."; return false; - } - - // Create the vote + } + // Create the vote RsGxsVote vote; - - vote.mMeta.mGroupId = groupId; - vote.mMeta.mThreadId = threadId; - vote.mMeta.mParentId = commentMessageId; + vote.mMeta.mGroupId = channelId; + vote.mMeta.mThreadId = postId; + vote.mMeta.mParentId = commentId; vote.mMeta.mAuthorId = authorId; - - vote.mVoteType = voteType; + vote.mVoteType = static_cast(tVote); uint32_t token; if(!createNewVote(token, vote)) { - error_message = std::string("Error! Failed creating vote."); + errorMessage = "Error! Failed creating vote."; return false; } if(waitToken(token) != RsTokenService::COMPLETE) { - error_message = std::string("Error! GXS operation failed."); + errorMessage = "GXS operation failed."; return false; } if(!RsGenExchange::getPublishedMsgMeta(token, vote.mMeta)) { - error_message = std::string("Error! Failure getting generated vote data."); + errorMessage = "Failure getting generated vote data."; + return false; + } + + voteId = vote.mMeta.mMsgId; + return true; +} + +/// @deprecated use createVoteV2 instead +bool p3GxsChannels::createVote(RsGxsVote& vote) +{ + uint32_t token; + if(!createNewVote(token, vote)) + { + std::cerr << __PRETTY_FUNCTION__ << " Error! Failed creating vote." + << std::endl; + return false; + } + + if(waitToken(token) != RsTokenService::COMPLETE) + { + std::cerr << __PRETTY_FUNCTION__ << " Error! GXS operation failed." + << std::endl; + return false; + } + + if(!RsGenExchange::getPublishedMsgMeta(token, vote.mMeta)) + { + std::cerr << __PRETTY_FUNCTION__ << " Error! Failure getting generated " + << " vote data." << std::endl; return false; } - voteMessageId = vote.mMeta.mMsgId; return true; } @@ -1290,21 +1332,21 @@ bool p3GxsChannels::editChannel(RsGxsChannelGroup& channel) uint32_t token; if(!updateGroup(token, channel)) { - std::cerr << __PRETTY_FUNCTION__ << "Error! Failed updating group." + std::cerr << __PRETTY_FUNCTION__ << " Error! Failed updating group." << std::endl; return false; } if(waitToken(token) != RsTokenService::COMPLETE) { - std::cerr << __PRETTY_FUNCTION__ << "Error! GXS operation failed." + std::cerr << __PRETTY_FUNCTION__ << " Error! GXS operation failed." << std::endl; return false; } if(!RsGenExchange::getPublishedGroupMeta(token, channel.mMeta)) { - std::cerr << __PRETTY_FUNCTION__ << "Error! Failure getting updated " + std::cerr << __PRETTY_FUNCTION__ << " Error! Failure getting updated " << " group data." << std::endl; return false; } @@ -1316,60 +1358,64 @@ bool p3GxsChannels::editChannel(RsGxsChannelGroup& channel) return true; } -bool p3GxsChannels::createPost(const RsGxsGroupId& groupId, - const RsGxsMessageId &origMsgId, - const std::string& msgName, - const std::string& msg, - const std::list& files, - const RsGxsImage& thumbnail, - RsGxsMessageId &message_id, - std::string& error_message) +bool p3GxsChannels::createPostV2( + const RsGxsGroupId& channelId, const std::string& title, + const std::string& body, const std::list& files, + const RsGxsImage& thumbnail, const RsGxsMessageId& origPostId, + RsGxsMessageId& postId, std::string& errorMessage ) { // Do some checks std::vector channelsInfo; - if(!getChannelsInfo(std::list({groupId}),channelsInfo)) - { - error_message = std::string("Channel with Id " + groupId.toStdString() + " does not exist."); - return false; - } - - const RsGxsChannelGroup& cg(*channelsInfo.begin()); - - if(!(cg.mMeta.mSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_PUBLISH)) - { - error_message = std::string("You cannot post to channel with Id " + groupId.toStdString() + ": missing publish rights!"); - return false; - } - - if(!origMsgId.isNull()) + if(!getChannelsInfo(std::list({channelId}),channelsInfo)) { - std::set s({origMsgId}); + errorMessage = "Channel with Id " + channelId.toStdString() + + " does not exist."; + return false; + } + + const RsGxsChannelGroup& cg(*channelsInfo.begin()); + + if(!(cg.mMeta.mSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_PUBLISH)) + { + errorMessage = "You cannot post to channel with Id " + + channelId.toStdString() + ": missing publish rights!"; + return false; + } + + if(!origPostId.isNull()) + { + std::set s({origPostId}); std::vector posts; std::vector comments; - if(!getChannelContent( groupId,s,posts,comments )) - { - error_message = std::string("You cannot edit post " + origMsgId.toStdString() + " of channel with Id " + groupId.toStdString() + ": this post does not locally exist!"); + if(!getChannelContent(channelId,s,posts,comments)) + { + errorMessage = "You cannot edit post " + origPostId.toStdString() + + " of channel with Id " + channelId.toStdString() + + ": this post does not exist locally!"; return false; - } + } } // Create the post RsGxsChannelPost post; - post.mMeta.mGroupId = groupId; - post.mMeta.mOrigMsgId = origMsgId; - post.mMeta.mMsgName = msgName; + post.mMeta.mGroupId = channelId; + post.mMeta.mOrigMsgId = origPostId; + post.mMeta.mMsgName = title; - post.mMsg = msg; - post.mFiles = files; - post.mThumbnail = thumbnail; + post.mMsg = body; + post.mFiles = files; + post.mThumbnail = thumbnail; uint32_t token; - if( !createPost(token, post) || waitToken(token) != RsTokenService::COMPLETE ) - return false; + if(!createPost(token, post) || waitToken(token) != RsTokenService::COMPLETE) + { + errorMessage = "GXS operation failed"; + return false; + } if(RsGenExchange::getPublishedMsgMeta(token,post.mMeta)) { @@ -1377,74 +1423,101 @@ bool p3GxsChannels::createPost(const RsGxsGroupId& groupId, DeepSearch::indexChannelPost(post); #endif // RS_DEEP_SEARCH - message_id = post.mMeta.mMsgId; + postId = post.mMeta.mMsgId; return true; } - error_message = std::string("cannot publish message. Check that you have publish rights on this channel?"); + errorMessage = "Failed to retrive created post metadata"; return false; } -bool p3GxsChannels::createComment(const RsGxsGroupId& groupId, - const RsGxsMessageId& parentMsgId, - const std::string& comment, - RsGxsMessageId& commentMessageId, - std::string& error_message) +bool p3GxsChannels::createCommentV2( + const RsGxsGroupId& channelId, const RsGxsMessageId& parentId, + const std::string& comment, RsGxsMessageId& commentMessageId, + std::string& errorMessage ) { - // Do some checks - std::vector channelsInfo; - - if(!getChannelsInfo(std::list({groupId}),channelsInfo)) - { - error_message = std::string("Channel with Id " + groupId.toStdString() + " does not exist."); - return false; - } - - if(parentMsgId.isNull()) - { - error_message = std::string("You cannot comment post " + parentMsgId.toStdString() + " of channel with Id " + groupId.toStdString() + ": please supply a non null post Id!"); - return false; - } - - std::set s({parentMsgId}); - std::vector posts; - std::vector comments; - - if(!getChannelContent( groupId,s,posts,comments )) + if(!getChannelsInfo(std::list({channelId}),channelsInfo)) { - error_message = std::string("You cannot comment post " + parentMsgId.toStdString() + " of channel with Id " + groupId.toStdString() + ": this post does not locally exist!"); + errorMessage = "Channel with Id " + channelId.toStdString() + + " does not exist."; return false; } - // Now create the comment + if(parentId.isNull()) + { + errorMessage = "You cannot comment post " + parentId.toStdString() + + " of channel with Id " + channelId.toStdString() + + ": please supply a non null post Id!"; + return false; + } + std::set s({parentId}); + std::vector posts; + std::vector comments; + + if(!getChannelContent(channelId,s,posts,comments)) + { + errorMessage = "You cannot comment post " + parentId.toStdString() + + " of channel with Id " + channelId.toStdString() + + ": this post does not exists locally!"; + return false; + } + + // Now create the comment RsGxsComment cmt; - cmt.mComment = comment; - cmt.mMeta.mGroupId = groupId; - cmt.mMeta.mParentId = parentMsgId; + cmt.mComment = comment; + cmt.mMeta.mGroupId = channelId; + cmt.mMeta.mParentId = parentId; uint32_t token; if(!createNewComment(token, cmt)) { - error_message = std::string("Error! Failed creating comment."); + errorMessage = "Failed creating comment."; return false; } if(waitToken(token) != RsTokenService::COMPLETE) { - error_message = std::string("Error! GXS operation failed."); + errorMessage = "GXS operation failed."; return false; } if(!RsGenExchange::getPublishedMsgMeta(token, cmt.mMeta)) { - error_message = std::string("Error! Failure getting generated comment data."); + errorMessage = "Failure getting generated comment data."; + return false; + } + + commentMessageId = cmt.mMeta.mMsgId; + return true; +} + +bool p3GxsChannels::createComment(RsGxsComment& comment) // deprecated +{ + uint32_t token; + if(!createNewComment(token, comment)) + { + std::cerr << __PRETTY_FUNCTION__ << " Error! Failed creating comment." + << std::endl; + return false; + } + + if(waitToken(token) != RsTokenService::COMPLETE) + { + std::cerr << __PRETTY_FUNCTION__ << " Error! GXS operation failed." + << std::endl; + return false; + } + + if(!RsGenExchange::getPublishedMsgMeta(token, comment.mMeta)) + { + std::cerr << __PRETTY_FUNCTION__ << " Error! Failure getting generated " + << " comment data." << std::endl; return false; } - commentMessageId = cmt.mMeta.mMsgId; return true; } @@ -1687,13 +1760,31 @@ bool p3GxsChannels::updateGroup(uint32_t &token, RsGxsChannelGroup &group) return true; } +/// @deprecated use createPostV2 instead +bool p3GxsChannels::createPost(RsGxsChannelPost& post) +{ + uint32_t token; + if( !createPost(token, post) + || waitToken(token) != RsTokenService::COMPLETE ) return false; + + if(RsGenExchange::getPublishedMsgMeta(token,post.mMeta)) + { +#ifdef RS_DEEP_SEARCH + DeepSearch::indexChannelPost(post); +#endif // RS_DEEP_SEARCH + + return true; + } + + return false; +} bool p3GxsChannels::createPost(uint32_t &token, RsGxsChannelPost &msg) { #ifdef GXSCHANNELS_DEBUG - std::cerr << "p3GxsChannels::createChannelPost() GroupId: " << msg.mMeta.mGroupId; - std::cerr << std::endl; + std::cerr << __PRETTY_FUNCTION__ << " GroupId: " << msg.mMeta.mGroupId + << std::endl; #endif RsGxsChannelPostItem* msgItem = new RsGxsChannelPostItem(); @@ -2235,7 +2326,7 @@ bool p3GxsChannels::turtleChannelRequest( { if(channelId.isNull()) { - std::cerr << __PRETTY_FUNCTION__ << "Error! channelId can't be null!" + std::cerr << __PRETTY_FUNCTION__ << " Error! channelId can't be null!" << std::endl; return false; } diff --git a/libretroshare/src/services/p3gxschannels.h b/libretroshare/src/services/p3gxschannels.h index 3203be1dd..0261d7bb6 100644 --- a/libretroshare/src/services/p3gxschannels.h +++ b/libretroshare/src/services/p3gxschannels.h @@ -4,7 +4,7 @@ * libretroshare: retroshare core library * * * * Copyright (C) 2012 Robert Fernie * - * Copyright (C) 2018 Gioacchino Mazzurco * + * Copyright (C) 2018-2019 Gioacchino Mazzurco * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * @@ -20,14 +20,14 @@ * along with this program. If not, see . * * * *******************************************************************************/ -#ifndef P3_GXSCHANNELS_SERVICE_HEADER -#define P3_GXSCHANNELS_SERVICE_HEADER +#pragma once #include "retroshare/rsgxschannels.h" #include "services/p3gxscommon.h" #include "gxs/rsgenexchange.h" #include "gxs/gxstokenqueue.h" +#include "util/rsmemory.h" #include "util/rstickevent.h" @@ -35,6 +35,7 @@ #include + class SSGxsChannelGroup { public: @@ -191,66 +192,63 @@ virtual bool ExtraFileRemove(const RsFileHash &hash); std::vector& comments ); /// Implementation of @see RsGxsChannels::getContentSummaries - virtual bool getContentSummaries( const RsGxsGroupId& channelId, - std::vector& summaries ); + virtual bool getContentSummaries( + const RsGxsGroupId& channelId, + std::vector& summaries ) override; -#ifdef REMOVED - /// Implementation of @see RsGxsChannels::createChannel - virtual bool createChannel(RsGxsChannelGroup& channel); -#endif + /// Implementation of @see RsGxsChannels::createChannelV2 + virtual bool createChannelV2( + const std::string& name, const std::string& description, + const RsGxsImage& thumbnail = RsGxsImage(), + const RsGxsId& authorId = RsGxsId(), + RsGxsCircleType circleType = RsGxsCircleType::PUBLIC, + const RsGxsCircleId& circleId = RsGxsCircleId(), + RsGxsGroupId& channelId = RS_DEFAULT_STORAGE_PARAM(RsGxsGroupId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) + ) override; - /// Implementation of @see RsGxsChannels::createChannel - virtual bool createChannel(const std::string& name, - const std::string& description, - const RsGxsImage& image, - const RsGxsId& author_id, - uint32_t circle_type, - RsGxsCircleId& circle_id, - RsGxsGroupId& channel_group_id, - std::string& error_message); - -#ifdef REMOVED - /// Implementation of @see RsGxsChannels::createComment - virtual bool createComment(RsGxsComment& comment); -#endif + /// @deprecated Implementation of @see RsGxsChannels::createComment + RS_DEPRECATED_FOR(createCommentV2) + virtual bool createComment(RsGxsComment& comment) override; /// Implementation of @see RsGxsChannels::createComment - virtual bool createComment(const RsGxsGroupId& groupId, - const RsGxsMessageId& parentMsgId, - const std::string& comment, - RsGxsMessageId& commentMessageId, - std::string& error_message); + virtual bool createCommentV2( + const RsGxsGroupId& channelId, const RsGxsMessageId& parentId, + const std::string& comment, + RsGxsMessageId& commentMessageId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) + ) override; /// Implementation of @see RsGxsChannels::editChannel - virtual bool editChannel(RsGxsChannelGroup& channel); + virtual bool editChannel(RsGxsChannelGroup& channel) override; -#ifdef REMOVED - /// Implementation of @see RsGxsChannels::createPost - virtual bool createPost(RsGxsChannelPost& post); -#endif - /// Implementation of @see RsGxsChannels::createPost - virtual bool createPost(const RsGxsGroupId& groupId, - const RsGxsMessageId& origMsgId, - const std::string& msgName, - const std::string& msg, - const std::list& files, - const RsGxsImage& thumbnail, - RsGxsMessageId &message_id, - std::string& error_message) ; + /// @deprecated Implementation of @see RsGxsChannels::createPost + RS_DEPRECATED_FOR(createPostV2) + virtual bool createPost(RsGxsChannelPost& post) override; -#ifdef REMOVED - /// Implementation of @see RsGxsChannels::createVote - virtual bool createVote(RsGxsVote& vote); -#endif + /// Implementation of @see RsGxsChannels::createPostV2 + bool createPostV2( + const RsGxsGroupId& channelId, const std::string& title, + const std::string& body, + const std::list& files = std::list(), + const RsGxsImage& thumbnail = RsGxsImage(), + const RsGxsMessageId& origPostId = RsGxsMessageId(), + RsGxsMessageId& postId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) + ) override; - /// Implementation of @see RsGxsChannels::createVote - virtual bool createVote(const RsGxsGroupId& groupId, - const RsGxsMessageId& threadId, - const RsGxsMessageId& commentMessageId, - const RsGxsId& authorId, - uint32_t voteType, - RsGxsMessageId& voteMessageId, - std::string& error_message); + /// @deprecated Implementation of @see RsGxsChannels::createVote + RS_DEPRECATED_FOR(createVoteV2) + virtual bool createVote(RsGxsVote& vote) override; + + /// Implementation of @see RsGxsChannels::createVoteV2 + virtual bool createVoteV2( + const RsGxsGroupId& channelId, const RsGxsMessageId& postId, + const RsGxsMessageId& commentId, const RsGxsId& authorId, + RsGxsVoteType vote, + RsGxsMessageId& voteId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) + ) override; /// Implementation of @see RsGxsChannels::subscribeToChannel virtual bool subscribeToChannel( const RsGxsGroupId &groupId, @@ -262,6 +260,10 @@ virtual bool ExtraFileRemove(const RsFileHash &hash); virtual bool shareChannelKeys( const RsGxsGroupId& channelId, const std::set& peers ); + /// Implementation of @see RsGxsChannels::createChannel + RS_DEPRECATED_FOR(createChannelV2) + virtual bool createChannel(RsGxsChannelGroup& channel) override; + protected: // Overloaded from GxsTokenQueue for Request callbacks. virtual void handleResponse(uint32_t token, uint32_t req_type); @@ -306,9 +308,11 @@ bool generateGroup(uint32_t &token, std::string groupName); class ChannelDummyRef { public: - ChannelDummyRef() { return; } - ChannelDummyRef(const RsGxsGroupId &grpId, const RsGxsMessageId &threadId, const RsGxsMessageId &msgId) - :mGroupId(grpId), mThreadId(threadId), mMsgId(msgId) { return; } + ChannelDummyRef() {} + ChannelDummyRef( + const RsGxsGroupId &grpId, const RsGxsMessageId &threadId, + const RsGxsMessageId &msgId ) : + mGroupId(grpId), mThreadId(threadId), mMsgId(msgId) {} RsGxsGroupId mGroupId; RsGxsMessageId mThreadId; @@ -352,5 +356,3 @@ bool generateGroup(uint32_t &token, std::string groupName); /// Cleanup mSearchCallbacksMap and mDistantChannelsCallbacksMap void cleanTimedOutCallbacks(); }; - -#endif diff --git a/libretroshare/src/util/rsmemory.h b/libretroshare/src/util/rsmemory.h index b46e12ad1..d37984262 100644 --- a/libretroshare/src/util/rsmemory.h +++ b/libretroshare/src/util/rsmemory.h @@ -23,8 +23,11 @@ #include #include +#include #include +#define RS_DEFAULT_STORAGE_PARAM(Type) *std::unique_ptr(new Type) + void *rs_malloc(size_t size) ; // This is a scope guard to release the memory block when going of of the current scope. From 617b924e1f276086fc5792c566afd14a810e2eca Mon Sep 17 00:00:00 2001 From: Pooh Date: Fri, 5 Apr 2019 10:48:00 +0300 Subject: [PATCH 66/81] Update rsconfig.h --- libretroshare/src/retroshare/rsconfig.h | 1 + 1 file changed, 1 insertion(+) diff --git a/libretroshare/src/retroshare/rsconfig.h b/libretroshare/src/retroshare/rsconfig.h index e3b74aa4b..385ab2f58 100644 --- a/libretroshare/src/retroshare/rsconfig.h +++ b/libretroshare/src/retroshare/rsconfig.h @@ -296,6 +296,7 @@ public: virtual int GetMaxDataRates( int &inKb, int &outKb ) = 0; virtual int GetCurrentDataRates( float &inKb, float &outKb ) = 0; + virtual int GetTrafficSum( uint64_t &inb, uint64_t &outb ) = 0; }; #endif From 3f8611f40ffded18581fbddd7707ebf4062afd3e Mon Sep 17 00:00:00 2001 From: zapek Date: Sat, 6 Apr 2019 00:15:01 +0200 Subject: [PATCH 67/81] the cache is corrected and saved --- libretroshare/src/file_sharing/hash_cache.cc | 39 ++++++++++++++++---- libretroshare/src/file_sharing/hash_cache.h | 3 ++ libretroshare/src/util/rsthreads.cc | 2 +- 3 files changed, 35 insertions(+), 9 deletions(-) diff --git a/libretroshare/src/file_sharing/hash_cache.cc b/libretroshare/src/file_sharing/hash_cache.cc index fcb20c540..340391f03 100644 --- a/libretroshare/src/file_sharing/hash_cache.cc +++ b/libretroshare/src/file_sharing/hash_cache.cc @@ -133,12 +133,7 @@ void HashStorage::data_tick() if(!mChanged) // otherwise it might prevent from saving the hash cache { - std::cerr << "Stopping hashing thread." << std::endl; - shutdown(); - mRunning = false ; - mTotalSizeToHash = 0; - mTotalFilesToHash = 0; - std::cerr << "done." << std::endl; + stopHashThread(); } RsServer::notify()->notifyHashingInfo(NOTIFY_HASHTYPE_FINISH, "") ; @@ -261,6 +256,16 @@ bool HashStorage::requestHash(const std::string& full_path,uint64_t size,rstime_ { it->second.time_stamp = now ; +#ifdef WINDOWS_SYS + if(it->second.modf_stamp != (uint64_t)mod_time) + { + std::cerr << "(WW) detected a 1 hour shift in file modification time. This normally happens to many files at once, when daylight saving time shifts (file=\"" << full_path << "\")." << std::endl; + it->second.modf_stamp = (uint64_t)mod_time; + mChanged = true; + startHashThread(); + } +#endif + known_hash = it->second.hash; #ifdef HASHSTORAGE_DEBUG std::cerr << "Found in cache." << std::endl ; @@ -293,6 +298,13 @@ bool HashStorage::requestHash(const std::string& full_path,uint64_t size,rstime_ mTotalSizeToHash += size ; ++mTotalFilesToHash; + startHashThread(); + + return false; +} + +void HashStorage::startHashThread() +{ if(!mRunning) { mRunning = true ; @@ -300,10 +312,21 @@ bool HashStorage::requestHash(const std::string& full_path,uint64_t size,rstime_ mHashCounter = 0; mTotalHashedSize = 0; - start("fs hash cache") ; + start("fs hash cache") ; } +} - return false; +void HashStorage::stopHashThread() +{ + if (mRunning) + { + std::cerr << "Stopping hashing thread." << std::endl; + shutdown(); + mRunning = false ; + mTotalSizeToHash = 0; + mTotalFilesToHash = 0; + std::cerr << "done." << std::endl; + } } void HashStorage::clean() diff --git a/libretroshare/src/file_sharing/hash_cache.h b/libretroshare/src/file_sharing/hash_cache.h index 3cf8f6c3a..ecf19802a 100644 --- a/libretroshare/src/file_sharing/hash_cache.h +++ b/libretroshare/src/file_sharing/hash_cache.h @@ -97,6 +97,9 @@ private: */ void clean() ; + void startHashThread(); + void stopHashThread(); + // loading/saving the entire hash database to a file void locked_save() ; diff --git a/libretroshare/src/util/rsthreads.cc b/libretroshare/src/util/rsthreads.cc index 1e3196036..4d6189d12 100644 --- a/libretroshare/src/util/rsthreads.cc +++ b/libretroshare/src/util/rsthreads.cc @@ -201,7 +201,7 @@ void RsThread::start(const std::string &threadName) if(threadName.length() > 15) { #ifdef DEBUG_THREADS - THREAD_DEBUG << "RsThread::start called with to long name '" << name << "' truncating..." << std::endl; + THREAD_DEBUG << "RsThread::start called with to long name '" << threadName << "' truncating..." << std::endl; #endif RS_pthread_setname_np(mTid, threadName.substr(0, 15).c_str()); } else { From c872044c83a004458d5f2538493be7160c5cf84c Mon Sep 17 00:00:00 2001 From: Piraty Date: Sat, 6 Apr 2019 14:43:04 +0200 Subject: [PATCH 68/81] add AGPL license text Many source files mention the `AGPL-3.0-or-later` license in their header, but there is no license file for AGPL in the project. Text is used as shown at https://www.gnu.org/licenses/agpl.txt Also see: https://spdx.org/licenses/AGPL-3.0-or-later.html --- LICENSE.AGPL.txt | 661 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 661 insertions(+) create mode 100644 LICENSE.AGPL.txt diff --git a/LICENSE.AGPL.txt b/LICENSE.AGPL.txt new file mode 100644 index 000000000..be3f7b28e --- /dev/null +++ b/LICENSE.AGPL.txt @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. From b12840715938e9a18eaa563b1eb096ad63705bee Mon Sep 17 00:00:00 2001 From: csoler Date: Mon, 8 Apr 2019 14:32:13 +0200 Subject: [PATCH 69/81] fixed rare bug in chat notify that appeared when your nickname is happenned at the end of the text --- retroshare-gui/src/gui/chat/ChatLobbyUserNotify.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/retroshare-gui/src/gui/chat/ChatLobbyUserNotify.cpp b/retroshare-gui/src/gui/chat/ChatLobbyUserNotify.cpp index 0b989ee2c..81cb47846 100644 --- a/retroshare-gui/src/gui/chat/ChatLobbyUserNotify.cpp +++ b/retroshare-gui/src/gui/chat/ChatLobbyUserNotify.cpp @@ -291,7 +291,7 @@ bool ChatLobbyUserNotify::checkWord(QString message, QString word) && (!word.isEmpty())) { QString eow=" ~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="; // end of word bool bFirstCharEOW = (nFound==0)?true:(eow.indexOf(message.at(nFound-1)) != -1); - bool bLastCharEOW = ((nFound+word.length()-1) < message.length()) + bool bLastCharEOW = (nFound+word.length() < message.length()) ?(eow.indexOf(message.at(nFound+word.length())) != -1) :true; bFound = (bFirstCharEOW && bLastCharEOW); From 9ad79f0c89fe860d5624281cf52bea6944773bbb Mon Sep 17 00:00:00 2001 From: Gioacchino Mazzurco Date: Wed, 10 Apr 2019 21:10:21 +0200 Subject: [PATCH 70/81] Improve documentation --- .../src/retroshare/rsgxsifacehelper.h | 2 +- libretroshare/src/util/rsmemory.h | 40 +++++++++++++++++-- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/libretroshare/src/retroshare/rsgxsifacehelper.h b/libretroshare/src/retroshare/rsgxsifacehelper.h index f19d8720c..fce16d8f7 100644 --- a/libretroshare/src/retroshare/rsgxsifacehelper.h +++ b/libretroshare/src/retroshare/rsgxsifacehelper.h @@ -314,7 +314,7 @@ LLwaitTokenBeginLabel: #if defined(__ANDROID__) && (__ANDROID_API__ < 24) /* Work around for very slow/old android devices, we don't expect this * to be necessary on newer devices. If it take unreasonably long - * something worser is already happening elsewere amd we return anyway. + * something worser is already happening elsewere and we return anyway. */ if( st > RsTokenService::FAILED && st < RsTokenService::COMPLETE && maxWorkAroundCnt-- > 0 ) diff --git a/libretroshare/src/util/rsmemory.h b/libretroshare/src/util/rsmemory.h index d37984262..7b475bcaf 100644 --- a/libretroshare/src/util/rsmemory.h +++ b/libretroshare/src/util/rsmemory.h @@ -3,7 +3,8 @@ * * * libretroshare: retroshare core library * * * - * Copyright 2012-2012 by Cyril Soler * + * Copyright 2012 Cyril Soler * + * Copyright 2019 Gioacchino Mazzurco * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * @@ -21,11 +22,44 @@ *******************************************************************************/ #pragma once -#include +#include #include #include -#include +#include "util/stacktrace.h" + +/** + * @brief Shorthand macro to declare optional functions output parameters + * To define an optional output paramether use the following syntax + * +\code{.cpp} +bool myFunnyFunction( + int mandatoryParamether, + BigType& myOptionalOutput = RS_DEFAULT_STORAGE_PARAM(BigType) ) +\endcode + * + * The function caller then can call myFunnyFunction either passing + * myOptionalOutput parameter or not. + * @see RsGxsChannels methods for real usage examples. + * + * @details + * When const references are used to pass function parameters it is easy do make + * those params optional by defining a default value in the function + * declaration, because a temp is accepted as default parameter in those cases. + * It is not as simple when one want to make optional a non-const reference + * parameter that is usually used as output, in that case as a temp is in theory + * not acceptable. + * Yet it is possible to overcome that limitation with the following trick: + * If not passed as parameter the storage for the output parameter can be + * dinamically allocated directly by the function call, to avoid leaking memory + * on each function call the pointer to that storage is made unique so once the + * function returns it goes out of scope and is automatically deleted. + * About performance overhead: std::unique_ptr have very good performance and + * modern compilers may be even able to avoid the dynamic allocation in this + * case, any way the allocation would only happen if the parameter is not + * passed, so any effect on performace would happen only in case where the + * function is called without the parameter. + */ #define RS_DEFAULT_STORAGE_PARAM(Type) *std::unique_ptr(new Type) void *rs_malloc(size_t size) ; From e9f341908aeb9fe583bcd5dc296933856842ac20 Mon Sep 17 00:00:00 2001 From: zapek Date: Thu, 11 Apr 2019 11:27:43 +0200 Subject: [PATCH 71/81] Moved the 'Mark as bad' entry in the search result files context menu further down away from 'Download' to avoid accidental clicks --- retroshare-gui/src/gui/FileTransfer/SearchDialog.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/retroshare-gui/src/gui/FileTransfer/SearchDialog.cpp b/retroshare-gui/src/gui/FileTransfer/SearchDialog.cpp index b94dc2b6e..eba42e4ff 100644 --- a/retroshare-gui/src/gui/FileTransfer/SearchDialog.cpp +++ b/retroshare-gui/src/gui/FileTransfer/SearchDialog.cpp @@ -329,13 +329,15 @@ void SearchDialog::searchResultWidgetCustomPopupMenu( QPoint /*point*/ ) QMenu contextMnu(this) ; contextMnu.addAction(QIcon(IMAGE_START), tr("Download"), this, SLOT(download())) ; - contextMnu.addAction(QIcon(IMAGE_BANFILE), tr("Mark as bad"), this, SLOT(ban())) ; contextMnu.addSeparator();//-------------------------------------- contextMnu.addAction(QIcon(IMAGE_COPYLINK), tr("Copy RetroShare Link"), this, SLOT(copyResultLink())) ; contextMnu.addAction(QIcon(IMAGE_COPYLINK), tr("Send RetroShare Link"), this, SLOT(sendLinkTo())) ; contextMnu.addSeparator();//-------------------------------------- + contextMnu.addAction(QIcon(IMAGE_BANFILE), tr("Mark as bad"), this, SLOT(ban())) ; + contextMnu.addSeparator();//-------------------------------------- + QMenu collectionMenu(tr("Collection"), this); collectionMenu.setIcon(QIcon(IMAGE_LIBRARY)); collectionMenu.addAction(collCreateAct); From 4c8851801f25ff5988a15463c3b2b46d03414637 Mon Sep 17 00:00:00 2001 From: csoler Date: Thu, 11 Apr 2019 21:04:13 +0200 Subject: [PATCH 72/81] fixed merging with pending modifications --- libretroshare/src/retroshare/rsgxschannels.h | 104 +++++++++---------- libretroshare/src/services/p3gxschannels.cc | 60 +++++++---- libretroshare/src/services/p3gxschannels.h | 13 +-- 3 files changed, 94 insertions(+), 83 deletions(-) diff --git a/libretroshare/src/retroshare/rsgxschannels.h b/libretroshare/src/retroshare/rsgxschannels.h index b341a4448..9fd2cd28e 100644 --- a/libretroshare/src/retroshare/rsgxschannels.h +++ b/libretroshare/src/retroshare/rsgxschannels.h @@ -104,66 +104,58 @@ public: /** * @brief Create channel. Blocking API. * @jsonapi{development} - * @param[in] name Name of the channel - * @param[in] description Description of the channel - * @param[in] thumbnail Optional image to show as channel thumbnail. - * @param[in] authorId Optional id of the author. Leave empty for an - * anonymous channel. - * @param[in] circleType Optional visibility rule, default public. - * @param[in] circleId If the channel is not public specify the id of the - * circle who can see the channel. Depending on the value you pass for - * circleType this should be be an external circle if EXTERNAL is passed, a - * local friend group id if NODES_GROUP is passed, empty otherwise. - * @param[out] channelId Optional storage for the id of the created channel, - * meaningful only if creations succeeds. - * @param[out] errorMessage Optional storage for error messsage, meaningful - * only if creation fail. + * @param[in] name Name of the channel + * @param[in] description Description of the channel + * @param[in] thumbnail Optional image to show as channel thumbnail. + * @param[in] authorId Optional id of the author. Leave empty for an anonymous channel. + * @param[in] circleType Optional visibility rule, default public. + * @param[in] circleId If the channel is not public specify the id of the circle who can see the channel. Depending on the value you pass for + * circleType this should be be an external circle if EXTERNAL is passed, a + * local friend group id if NODES_GROUP is passed, empty otherwise. + * @param[out] channelId Optional storage for the id of the created channel, meaningful only if creations succeeds. + * @param[out] errorMessage Optional storage for error messsage, meaningful only if creation fail. * @return False on error, true otherwise. */ - virtual bool createChannelV2( - const std::string& name, const std::string& description, - const RsGxsImage& thumbnail = RsGxsImage(), - const RsGxsId& authorId = RsGxsId(), - RsGxsCircleType circleType = RsGxsCircleType::PUBLIC, - const RsGxsCircleId& circleId = RsGxsCircleId(), - RsGxsGroupId& channelId = RS_DEFAULT_STORAGE_PARAM(RsGxsGroupId), - std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) ) = 0; + virtual bool createChannelV2(const std::string& name, + const std::string& description, + const RsGxsImage& thumbnail = RsGxsImage(), + const RsGxsId& authorId = RsGxsId(), + RsGxsCircleType circleType = RsGxsCircleType::PUBLIC, + const RsGxsCircleId& circleId = RsGxsCircleId(), + RsGxsGroupId& channelGroupId = RS_DEFAULT_STORAGE_PARAM(RsGxsGroupId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) ) = 0; /** - * @brief Add a comment on a post or on another comment + * @brief Add a comment on a post or on another comment. Blocking API. * @jsonapi{development} - * @param[in] channelId Id of the channel in which the comment is to be posted - * @param[in] parentId Id of the parent of the comment that is either a - * channel post Id or the Id of another comment. - * @param[in] comment UTF-8 string containing the comment - * @param[out] commentMessageId Optional storage for the id of the comment - * that was created, meaningful only on success. - * @param[out] errorMessage Optional storage for error message, meaningful - * only on failure. + * @param[in] channelId Id of the channel in which the comment is to be posted + * @param[in] threadId Id of the post (that is a thread) in the channel where the comment is placed + * @param[in] parentId Id of the parent of the comment that is either a channel post Id or the Id of another comment. + * @param[in] authorId Id of the author of the comment + * @param[in] comment UTF-8 string containing the comment itself + * @param[out] commentMessageId Optional storage for the id of the comment that was created, meaningful only on success. + * @param[out] errorMessage Optional storage for error message, meaningful only on failure. * @return false on error, true otherwise */ - virtual bool createCommentV2( - const RsGxsGroupId& channelId, const RsGxsMessageId& parentId, - const std::string& comment, - RsGxsMessageId& commentMessageId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), - std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) )=0; + virtual bool createCommentV2(const RsGxsGroupId& channelId, + const RsGxsMessageId& threadId, + const RsGxsMessageId& parentId, + const RsGxsId& authorId, + const std::string& comment, + RsGxsMessageId& commentMessageId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) )=0; /** * @brief Create channel post. Blocking API. * @jsonapi{development} - * @param[in] channelId Id of the channel where to put the post. Beware you - * need publish rights on that channel to post. - * @param[in] title Title of the post - * @param[in] mBody Text content of the post - * @param[in] files Optional list of attached files. These are supposed to - * be already shared, @see ExtraFileHash() below otherwise. - * @param[in] thumbnail Optional thumbnail image for the post. - * @param[in] origPostId If this is supposed to replace an already existent - * post, the id of the old post. If left blank a new post will be created. - * @param[out] postId Optional storage for the id of the created post, - * meaningful only on success. - * @param[out] errorMessage Optional storage for the error message, - * meaningful only on failure. + * @param[in] channelId Id of the channel where to put the post. Beware you need publish rights on that channel to post. + * @param[in] title Title of the post + * @param[in] mBody Text content of the post + * @param[in] files Optional list of attached files. These are supposed to be already shared, @see ExtraFileHash() below otherwise. + * @param[in] thumbnail Optional thumbnail image for the post. + * @param[in] origPostId If this is supposed to replace an already existent post, the id of the old post. If left blank a new post will be created. + * @param[out] postId Optional storage for the id of the created post, meaningful only on success. + * @param[out] errorMessage Optional storage for the error message, meaningful only on failure. * @return false on error, true otherwise */ virtual bool createPostV2( @@ -178,14 +170,12 @@ public: /** * @brief Create a vote * @jsonapi{development} - * @param[in] channelId Id of the channel where to vote - * @param[in] postId Id of the channel post of which a comment is voted - * @param[in] commentId Id of the comment that is voted - * @param[in] authorId Id of the author. Needs to be of an owned identity. - * @param[in] vote Vote value, either RsGxsVoteType::DOWN or - * RsGxsVoteType::UP - * @param[out] voteId Optional storage for the id of the created vote, - * meaningful only on success. + * @param[in] channelId Id of the channel where to vote + * @param[in] postId Id of the channel post of which a comment is voted + * @param[in] commentId Id of the comment that is voted + * @param[in] authorId Id of the author. Needs to be of an owned identity. + * @param[in] vote Vote value, either RsGxsVoteType::DOWN or RsGxsVoteType::UP + * @param[out] voteId Optional storage for the id of the created vote, meaningful only on success. * @param[out] errorMessage Optional storage for error message, meaningful * only on failure. * @return false on error, true otherwise diff --git a/libretroshare/src/services/p3gxschannels.cc b/libretroshare/src/services/p3gxschannels.cc index b3ff3f78e..bcf0ad3b3 100644 --- a/libretroshare/src/services/p3gxschannels.cc +++ b/libretroshare/src/services/p3gxschannels.cc @@ -1431,45 +1431,65 @@ bool p3GxsChannels::createPostV2( return false; } -bool p3GxsChannels::createCommentV2( - const RsGxsGroupId& channelId, const RsGxsMessageId& parentId, - const std::string& comment, RsGxsMessageId& commentMessageId, - std::string& errorMessage ) +bool p3GxsChannels::createCommentV2(const RsGxsGroupId& channelId, + const RsGxsMessageId& threadId, + const RsGxsMessageId& parentId, + const RsGxsId& authorId, + const std::string& comment, + RsGxsMessageId& commentMessageId, + std::string& errorMessage) { std::vector channelsInfo; if(!getChannelsInfo(std::list({channelId}),channelsInfo)) { errorMessage = "Channel with Id " + channelId.toStdString() - + " does not exist."; + + " does not exist."; return false; } - if(parentId.isNull()) - { - errorMessage = "You cannot comment post " + parentId.toStdString() - + " of channel with Id " + channelId.toStdString() - + ": please supply a non null post Id!"; - return false; - } - - std::set s({parentId}); std::vector posts; std::vector comments; - if(!getChannelContent(channelId,s,posts,comments)) + if(!getChannelContent( channelId,std::set({threadId}),posts,comments )) // does the post thread exist? { - errorMessage = "You cannot comment post " + parentId.toStdString() - + " of channel with Id " + channelId.toStdString() - + ": this post does not exists locally!"; + errorMessage = "You cannot comment post " + threadId.toStdString() + " of channel with Id " + channelId.toStdString() + ": this post does not exists locally!"; + return false; + } + + if(posts.size() != 1 || !posts[0].mMeta.mParentId.isNull()) // check that the post thread Id is actually that of a post thread + { + errorMessage = std::string("You cannot comment post " + threadId.toStdString() + " of channel with Id " + channelId.toStdString() + ": supplied threadId is not a thread, or parentMsgId is not a comment!"); + return false; + } + + if(!parentId.isNull()) + if(!getChannelContent( channelId,std::set({parentId}),posts,comments )) // does the post thread exist? + { + errorMessage = std::string("You cannot comment post " + parentId.toStdString() + ": supplied parent comment Id is not a comment!"); + return false; + } + else if(comments.size() != 1 || comments[0].mMeta.mParentId.isNull()) // is the comment parent actually a comment? + { + errorMessage = std::string("You cannot comment post " + parentId.toStdString() + " of channel with Id " + channelId.toStdString() + ": supplied mParentMsgId is not a comment Id!"); + return false; + } + + if(!rsIdentity->isOwnId(authorId)) // is the voter ID actually ours? + { + errorMessage = std::string("You cannot comment to channel with Id " + channelId.toStdString() + " with identity " + authorId.toStdString() + " because it is not yours."); return false; } // Now create the comment + RsGxsComment cmt; - cmt.mComment = comment; - cmt.mMeta.mGroupId = channelId; + cmt.mMeta.mGroupId = channelId; + cmt.mMeta.mThreadId = threadId; cmt.mMeta.mParentId = parentId; + cmt.mMeta.mAuthorId = authorId; + + cmt.mComment = comment; uint32_t token; if(!createNewComment(token, cmt)) diff --git a/libretroshare/src/services/p3gxschannels.h b/libretroshare/src/services/p3gxschannels.h index 0261d7bb6..a038904b4 100644 --- a/libretroshare/src/services/p3gxschannels.h +++ b/libretroshare/src/services/p3gxschannels.h @@ -212,12 +212,13 @@ virtual bool ExtraFileRemove(const RsFileHash &hash); virtual bool createComment(RsGxsComment& comment) override; /// Implementation of @see RsGxsChannels::createComment - virtual bool createCommentV2( - const RsGxsGroupId& channelId, const RsGxsMessageId& parentId, - const std::string& comment, - RsGxsMessageId& commentMessageId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), - std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) - ) override; + virtual bool createCommentV2(const RsGxsGroupId& channelId, + const RsGxsMessageId& threadId, + const RsGxsMessageId& parentId, + const RsGxsId& authorId, + const std::string& comment, + RsGxsMessageId& commentMessageId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string)) override; /// Implementation of @see RsGxsChannels::editChannel virtual bool editChannel(RsGxsChannelGroup& channel) override; From 322334b076eb2eac9ee51bf4eec8e4801129896d Mon Sep 17 00:00:00 2001 From: csoler Date: Thu, 11 Apr 2019 21:04:29 +0200 Subject: [PATCH 73/81] fixed compilation warning --- libretroshare/src/pqi/pqi_base.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libretroshare/src/pqi/pqi_base.h b/libretroshare/src/pqi/pqi_base.h index 209489363..7d284818b 100644 --- a/libretroshare/src/pqi/pqi_base.h +++ b/libretroshare/src/pqi/pqi_base.h @@ -186,7 +186,7 @@ class NetInterface; class PQInterface: public RateInterface { public: - explicit PQInterface(const RsPeerId &id) :peerId(id), traf_in(0), traf_out(0) { return; } + explicit PQInterface(const RsPeerId &id) :traf_in(0), traf_out(0),peerId(id) { return; } virtual ~PQInterface() { return; } /*! From 3f75bff48b183ecbbc6b43e237408e4665f90414 Mon Sep 17 00:00:00 2001 From: csoler Date: Thu, 11 Apr 2019 23:57:18 +0200 Subject: [PATCH 74/81] first branch of faster turtle track for distant chat --- libretroshare/src/gxstunnel/p3gxstunnel.cc | 94 ++++++++++++++++------ libretroshare/src/gxstunnel/p3gxstunnel.h | 42 +++++----- libretroshare/src/rsitems/itempriorities.h | 15 ++-- libretroshare/src/turtle/p3turtle.cc | 24 +++--- libretroshare/src/turtle/rsturtleitem.cc | 9 ++- libretroshare/src/turtle/rsturtleitem.h | 23 ++++++ 6 files changed, 140 insertions(+), 67 deletions(-) diff --git a/libretroshare/src/gxstunnel/p3gxstunnel.cc b/libretroshare/src/gxstunnel/p3gxstunnel.cc index 3c92bb312..a66170270 100644 --- a/libretroshare/src/gxstunnel/p3gxstunnel.cc +++ b/libretroshare/src/gxstunnel/p3gxstunnel.cc @@ -692,22 +692,40 @@ void p3GxsTunnelService::receiveTurtleData(const RsTurtleGenericTunnelItem *gite (void) direction; #endif - const RsTurtleGenericDataItem *item = dynamic_cast(gitem) ; + void *data_bytes; + uint32_t data_size ; + bool accept_fast_items = false; - if(item == NULL) + const RsTurtleGenericFastDataItem *fitem = dynamic_cast(gitem) ; + + if(fitem != NULL) { - std::cerr << "(EE) item is not a data item. That is an error." << std::endl; - return ; + data_bytes = fitem->data_bytes ; + data_size = fitem->data_size ; + accept_fast_items = true; } - // Call the AES crypto module + else + { + const RsTurtleGenericDataItem *item = dynamic_cast(gitem) ; + + if(item == NULL) + { + std::cerr << "(EE) item is not a data item. That is an error." << std::endl; + return ; + } + data_bytes = item->data_bytes ; + data_size = item->data_size ; + } + + // Call the AES crypto module // - the IV is the first 8 bytes of item->data_bytes - if(item->data_size < 8) + if(data_size < 8) { - std::cerr << "(EE) item encrypted data stream is too small: size = " << item->data_size << std::endl; + std::cerr << "(EE) item encrypted data stream is too small: size = " << data_size << std::endl; return ; } - if(*((uint64_t*)item->data_bytes) != 0) // WTF?? we should use flags + if(*((uint64_t*)data_bytes) != 0) // WTF?? we should use flags { #ifdef DEBUG_GXS_TUNNEL std::cerr << " Item is encrypted." << std::endl; @@ -715,7 +733,7 @@ void p3GxsTunnelService::receiveTurtleData(const RsTurtleGenericTunnelItem *gite // if cannot decrypt, it means the key is wrong. We need to re-negociate a new key. - handleEncryptedData((uint8_t*)item->data_bytes,item->data_size,hash,virtual_peer_id) ; + handleEncryptedData((uint8_t*)data_bytes,data_size,hash,virtual_peer_id,accept_fast_items) ; } else { @@ -725,8 +743,8 @@ void p3GxsTunnelService::receiveTurtleData(const RsTurtleGenericTunnelItem *gite // Now try deserialise the decrypted data to make an RsItem out of it. // - uint32_t pktsize = item->data_size-8; - RsItem *citem = RsGxsTunnelSerialiser().deserialise(&((uint8_t*)item->data_bytes)[8],&pktsize) ; + uint32_t pktsize = data_size-8; + RsItem *citem = RsGxsTunnelSerialiser().deserialise(&((uint8_t*)data_bytes)[8],&pktsize) ; if(citem == NULL) { @@ -752,7 +770,7 @@ void p3GxsTunnelService::receiveTurtleData(const RsTurtleGenericTunnelItem *gite // This function encrypts the given data and adds a MAC and an IV into a serialised memory chunk that is then sent through the tunnel. -bool p3GxsTunnelService::handleEncryptedData(const uint8_t *data_bytes,uint32_t data_size,const TurtleFileHash& hash,const RsPeerId& virtual_peer_id) +bool p3GxsTunnelService::handleEncryptedData(const uint8_t *data_bytes,uint32_t data_size,const TurtleFileHash& hash,const RsPeerId& virtual_peer_id,bool accepts_fast_items) { #ifdef DEBUG_GXS_TUNNEL std::cerr << "p3GxsTunnelService::handleEncryptedDataItem()" << std::endl; @@ -795,6 +813,10 @@ bool p3GxsTunnelService::handleEncryptedData(const uint8_t *data_bytes,uint32_t std::cerr << "(EE) no tunnel data for tunnel ID=" << tunnel_id << ". This is a bug." << std::endl; return false ; } + + if(accepts_fast_items) + it2->second.accepts_fast_turtle_items = accepts_fast_items; + memcpy(aes_key,it2->second.aes_key,GXS_TUNNEL_AES_KEY_SIZE) ; #ifdef DEBUG_GXS_TUNNEL @@ -1291,36 +1313,58 @@ bool p3GxsTunnelService::locked_sendEncryptedTunnelData(RsGxsTunnelItem *item) // make a TurtleGenericData item out of it: // - RsTurtleGenericDataItem *gitem = new RsTurtleGenericDataItem ; - gitem->data_size = encrypted_size + GXS_TUNNEL_ENCRYPTION_IV_SIZE + GXS_TUNNEL_ENCRYPTION_HMAC_SIZE ; - gitem->data_bytes = rs_malloc(gitem->data_size) ; + uint32_t data_size = encrypted_size + GXS_TUNNEL_ENCRYPTION_IV_SIZE + GXS_TUNNEL_ENCRYPTION_HMAC_SIZE ; + void *data_bytes = rs_malloc(data_size) ; - if(gitem->data_bytes == NULL) + if(data_bytes == NULL) return false ; - memcpy(& ((uint8_t*)gitem->data_bytes)[0] ,&IV,8) ; + memcpy(& ((uint8_t*)data_bytes)[0] ,&IV,8) ; unsigned int md_len = GXS_TUNNEL_ENCRYPTION_HMAC_SIZE ; - HMAC(EVP_sha1(),aes_key,GXS_TUNNEL_AES_KEY_SIZE,encrypted_data,encrypted_size,&(((uint8_t*)gitem->data_bytes)[GXS_TUNNEL_ENCRYPTION_IV_SIZE]),&md_len) ; + HMAC(EVP_sha1(),aes_key,GXS_TUNNEL_AES_KEY_SIZE,encrypted_data,encrypted_size,&(((uint8_t*)data_bytes)[GXS_TUNNEL_ENCRYPTION_IV_SIZE]),&md_len) ; - memcpy(& (((uint8_t*)gitem->data_bytes)[GXS_TUNNEL_ENCRYPTION_HMAC_SIZE+GXS_TUNNEL_ENCRYPTION_IV_SIZE]),encrypted_data,encrypted_size) ; + memcpy(& (((uint8_t*)data_bytes)[GXS_TUNNEL_ENCRYPTION_HMAC_SIZE+GXS_TUNNEL_ENCRYPTION_IV_SIZE]),encrypted_data,encrypted_size) ; #ifdef DEBUG_GXS_TUNNEL std::cerr << " Using IV: " << std::hex << IV << std::dec << std::endl; std::cerr << " Using Key: " << RsUtil::BinToHex((char*)aes_key,GXS_TUNNEL_AES_KEY_SIZE) ; std::cerr << std::endl; - std::cerr << " hmac: " << RsUtil::BinToHex((char*)gitem->data_bytes,GXS_TUNNEL_ENCRYPTION_HMAC_SIZE) << std::endl; + std::cerr << " hmac: " << RsUtil::BinToHex((char*)data_bytes,GXS_TUNNEL_ENCRYPTION_HMAC_SIZE) << std::endl; #endif #ifdef DEBUG_GXS_TUNNEL std::cerr << "GxsTunnelService::sendEncryptedTunnelData(): Sending encrypted data to virtual peer: " << virtual_peer_id << std::endl; - std::cerr << " gitem->data_size = " << gitem->data_size << std::endl; - std::cerr << " serialised data = " << RsUtil::BinToHex((unsigned char*)gitem->data_bytes,gitem->data_size,100) ; + std::cerr << " data_size = " << data_size << std::endl; + std::cerr << " serialised data = " << RsUtil::BinToHex((unsigned char*)data_bytes,data_size,100) ; std::cerr << std::endl; #endif - mTurtle->sendTurtleData(virtual_peer_id,gitem) ; - - return true ; + // We send the item through the turtle tunnel. We do that using the new 'fast' item type if the tunnel accepts it, and using the old slow one otherwise. + // Still if the tunnel hasn't been probed, we duplicate the packet using the new fast item format. The packet being received twice on the other side will + // be discarded with a warning. + + if(!it->second.accepts_fast_turtle_items) + { + RsTurtleGenericDataItem *gitem = new RsTurtleGenericDataItem ; + + gitem->data_bytes = data_bytes; + gitem->data_size = data_size ; + + mTurtle->sendTurtleData(virtual_peer_id,gitem) ; + } + + if(it->second.accepts_fast_turtle_items || !it->second.already_probed_for_fast_items) + { + RsTurtleGenericFastDataItem *gitem = new RsTurtleGenericFastDataItem ; +#warning we should duplicate the data here, otherwise it's gonna crash + gitem->data_bytes = data_bytes; + gitem->data_size = data_size ; + + it->second.already_probed_for_fast_items = true; + mTurtle->sendTurtleData(virtual_peer_id,gitem) ; + } + + return true ; } bool p3GxsTunnelService::requestSecuredTunnel(const RsGxsId& to_gxs_id, const RsGxsId& from_gxs_id, RsGxsTunnelId &tunnel_id, uint32_t service_id, uint32_t& error_code) diff --git a/libretroshare/src/gxstunnel/p3gxstunnel.h b/libretroshare/src/gxstunnel/p3gxstunnel.h index bcbce734a..98b68f161 100644 --- a/libretroshare/src/gxstunnel/p3gxstunnel.h +++ b/libretroshare/src/gxstunnel/p3gxstunnel.h @@ -128,14 +128,12 @@ public: // Creates the invite if the public key of the distant peer is available. // Om success, stores the invite in the map above, so that we can respond to tunnel requests. // - virtual bool requestSecuredTunnel(const RsGxsId& to_id,const RsGxsId& from_id,RsGxsTunnelId& tunnel_id,uint32_t service_id,uint32_t& error_code) ; - - virtual bool closeExistingTunnel(const RsGxsTunnelId &tunnel_id,uint32_t service_id) ; - virtual bool getTunnelsInfo(std::vector& infos); - virtual bool getTunnelInfo(const RsGxsTunnelId& tunnel_id,GxsTunnelInfo& info); - virtual bool sendData(const RsGxsTunnelId& tunnel_id,uint32_t service_id,const uint8_t *data,uint32_t size) ; - - virtual bool registerClientService(uint32_t service_id,RsGxsTunnelClientService *service) ; + virtual bool requestSecuredTunnel(const RsGxsId& to_id,const RsGxsId& from_id,RsGxsTunnelId& tunnel_id,uint32_t service_id,uint32_t& error_code) override ; + virtual bool closeExistingTunnel(const RsGxsTunnelId &tunnel_id,uint32_t service_id) override ; + virtual bool getTunnelsInfo(std::vector& infos) override ; + virtual bool getTunnelInfo(const RsGxsTunnelId& tunnel_id,GxsTunnelInfo& info) override ; + virtual bool sendData(const RsGxsTunnelId& tunnel_id,uint32_t service_id,const uint8_t *data,uint32_t size) override ; + virtual bool registerClientService(uint32_t service_id,RsGxsTunnelClientService *service) override ; // derived from p3service @@ -149,7 +147,7 @@ private: class GxsTunnelPeerInfo { public: - GxsTunnelPeerInfo() : last_contact(0), last_keep_alive_sent(0), status(0), direction(0) + GxsTunnelPeerInfo() : last_contact(0), last_keep_alive_sent(0), status(0), direction(0),accepts_fast_turtle_items(false) { memset(aes_key, 0, GXS_TUNNEL_AES_KEY_SIZE); @@ -158,20 +156,22 @@ private: } rstime_t last_contact ; // used to keep track of working connexion - rstime_t last_keep_alive_sent ; // last time we sent a keep alive packet. + rstime_t last_keep_alive_sent ; // last time we sent a keep alive packet. unsigned char aes_key[GXS_TUNNEL_AES_KEY_SIZE] ; - uint32_t status ; // info: do we have a tunnel ? - RsPeerId virtual_peer_id; // given by the turtle router. Identifies the tunnel. - RsGxsId to_gxs_id; // gxs id we're talking to - RsGxsId own_gxs_id ; // gxs id we're using to talk. - RsTurtleGenericTunnelItem::Direction direction ; // specifiec wether we are client(managing the tunnel) or server. - TurtleFileHash hash ; // hash that is last used. This is necessary for handling tunnel establishment - std::set client_services ;// services that used this tunnel - std::map received_data_prints ; // list of recently received messages, to avoid duplicates. Kept for 20 mins at most. - uint32_t total_sent ; - uint32_t total_received ; + uint32_t status ; // info: do we have a tunnel ? + RsPeerId virtual_peer_id; // given by the turtle router. Identifies the tunnel. + RsGxsId to_gxs_id; // gxs id we're talking to + RsGxsId own_gxs_id ; // gxs id we're using to talk. + RsTurtleGenericTunnelItem::Direction direction ; // specifiec wether we are client(managing the tunnel) or server. + TurtleFileHash hash ; // hash that is last used. This is necessary for handling tunnel establishment + std::set client_services ; // services that used this tunnel + std::map received_data_prints ; // list of recently received messages, to avoid duplicates. Kept for 20 mins at most. + uint32_t total_sent ; // total data sent to this peer + uint32_t total_received ; // total data received by this peer + bool accepts_fast_turtle_items; // does the tunnel accept RsTurtleGenericFastDataItem type? + bool already_probed_for_fast_items; // has the tunnel been probed already? If not, a fast item will be sent }; class GxsTunnelDHInfo @@ -243,7 +243,7 @@ private: bool locked_sendEncryptedTunnelData(RsGxsTunnelItem *item) ; bool locked_sendClearTunnelData(RsGxsTunnelDHPublicKeyItem *item); // this limits the usage to DH items. Others should be encrypted! - bool handleEncryptedData(const uint8_t *data_bytes,uint32_t data_size,const TurtleFileHash& hash,const RsPeerId& virtual_peer_id) ; + bool handleEncryptedData(const uint8_t *data_bytes, uint32_t data_size, const TurtleFileHash& hash, const RsPeerId& virtual_peer_id, bool accepts_fast_items) ; // local data diff --git a/libretroshare/src/rsitems/itempriorities.h b/libretroshare/src/rsitems/itempriorities.h index dc346b7c3..b7f29babc 100644 --- a/libretroshare/src/rsitems/itempriorities.h +++ b/libretroshare/src/rsitems/itempriorities.h @@ -31,21 +31,22 @@ const uint8_t QOS_PRIORITY_TOP = 9 ; // Turtle traffic // -const uint8_t QOS_PRIORITY_RS_TURTLE_OPEN_TUNNEL = 6 ; -const uint8_t QOS_PRIORITY_RS_TURTLE_TUNNEL_OK = 6 ; +const uint8_t QOS_PRIORITY_RS_TURTLE_OPEN_TUNNEL = 6 ; +const uint8_t QOS_PRIORITY_RS_TURTLE_TUNNEL_OK = 6 ; const uint8_t QOS_PRIORITY_RS_TURTLE_SEARCH_REQUEST = 6 ; -const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_REQUEST = 5 ; -const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_CRC_REQUEST = 5 ; -const uint8_t QOS_PRIORITY_RS_TURTLE_CHUNK_CRC_REQUEST= 5 ; +const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_REQUEST = 5 ; +const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_CRC_REQUEST = 5 ; +const uint8_t QOS_PRIORITY_RS_TURTLE_CHUNK_CRC_REQUEST= 5 ; const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_MAP_REQUEST = 5 ; -const uint8_t QOS_PRIORITY_RS_TURTLE_SEARCH_RESULT = 3 ; -const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_DATA = 3 ; +const uint8_t QOS_PRIORITY_RS_TURTLE_SEARCH_RESULT = 3 ; +const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_DATA = 3 ; const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_CRC = 3 ; const uint8_t QOS_PRIORITY_RS_TURTLE_CHUNK_CRC = 5 ; const uint8_t QOS_PRIORITY_RS_TURTLE_FILE_MAP = 3 ; const uint8_t QOS_PRIORITY_RS_TURTLE_GENERIC_ITEM = 3 ; const uint8_t QOS_PRIORITY_RS_TURTLE_FORWARD_FILE_DATA= 3 ; const uint8_t QOS_PRIORITY_RS_TURTLE_GENERIC_DATA = 5 ; +const uint8_t QOS_PRIORITY_RS_TURTLE_GENERIC_FAST_DATA= 7 ; // File transfer // diff --git a/libretroshare/src/turtle/p3turtle.cc b/libretroshare/src/turtle/p3turtle.cc index 3abc216dc..f1e96a8a4 100644 --- a/libretroshare/src/turtle/p3turtle.cc +++ b/libretroshare/src/turtle/p3turtle.cc @@ -77,18 +77,18 @@ void TS_dumpState() ; // - The total number of TR per second emmited from self will be MAX_TUNNEL_REQS_PER_SECOND / TIME_BETWEEN_TUNNEL_MANAGEMENT_CALLS = 0.5 // - I updated forward probabilities to higher values, and min them to 1/nb_connected_friends to prevent blocking tunnels. // -static const rstime_t TUNNEL_REQUESTS_LIFE_TIME = 240 ; /// life time for tunnel requests in the cache. -static const rstime_t SEARCH_REQUESTS_LIFE_TIME = 240 ; /// life time for search requests in the cache -static const rstime_t REGULAR_TUNNEL_DIGGING_TIME = 300 ; /// maximum interval between two tunnel digging campaigns. -static const rstime_t MAXIMUM_TUNNEL_IDLE_TIME = 60 ; /// maximum life time of an unused tunnel. -static const rstime_t EMPTY_TUNNELS_DIGGING_TIME = 50 ; /// look into tunnels regularly every 50 sec. -static const rstime_t TUNNEL_SPEED_ESTIMATE_LAPSE = 5 ; /// estimate tunnel speed every 5 seconds -static const rstime_t TUNNEL_CLEANING_LAPS_TIME = 10 ; /// clean tunnels every 10 secs -static const rstime_t TIME_BETWEEN_TUNNEL_MANAGEMENT_CALLS = 2 ; /// Tunnel management calls every 2 secs. -static const uint32_t MAX_TUNNEL_REQS_PER_SECOND = 1 ; /// maximum number of tunnel requests issued per second. Was 0.5 before -static const uint32_t MAX_ALLOWED_SR_IN_CACHE = 120 ; /// maximum number of search requests allowed in cache. That makes 2 per sec. -static const uint32_t TURTLE_SEARCH_RESULT_MAX_HITS_FILES =5000 ; /// maximum number of search results forwarded back to the source. -static const uint32_t TURTLE_SEARCH_RESULT_MAX_HITS_DEFAULT= 100 ; /// default maximum number of search results forwarded back source. +static const rstime_t TUNNEL_REQUESTS_LIFE_TIME = 240 ; /// life time for tunnel requests in the cache. +static const rstime_t SEARCH_REQUESTS_LIFE_TIME = 240 ; /// life time for search requests in the cache +static const rstime_t REGULAR_TUNNEL_DIGGING_TIME = 300 ; /// maximum interval between two tunnel digging campaigns. +static const rstime_t MAXIMUM_TUNNEL_IDLE_TIME = 60 ; /// maximum life time of an unused tunnel. +static const rstime_t EMPTY_TUNNELS_DIGGING_TIME = 50 ; /// look into tunnels regularly every 50 sec. +static const rstime_t TUNNEL_SPEED_ESTIMATE_LAPSE = 5 ; /// estimate tunnel speed every 5 seconds +static const rstime_t TUNNEL_CLEANING_LAPS_TIME = 10 ; /// clean tunnels every 10 secs +static const rstime_t TIME_BETWEEN_TUNNEL_MANAGEMENT_CALLS = 2 ; /// Tunnel management calls every 2 secs. +static const uint32_t MAX_TUNNEL_REQS_PER_SECOND = 1 ; /// maximum number of tunnel requests issued per second. Was 0.5 before +static const uint32_t MAX_ALLOWED_SR_IN_CACHE = 120 ; /// maximum number of search requests allowed in cache. That makes 2 per sec. +static const uint32_t TURTLE_SEARCH_RESULT_MAX_HITS_FILES =5000 ; /// maximum number of search results forwarded back to the source. +static const uint32_t TURTLE_SEARCH_RESULT_MAX_HITS_DEFAULT = 100 ; /// default maximum number of search results forwarded back source. static const float depth_peer_probability[7] = { 1.0f,0.99f,0.9f,0.7f,0.6f,0.5,0.4f } ; diff --git a/libretroshare/src/turtle/rsturtleitem.cc b/libretroshare/src/turtle/rsturtleitem.cc index be9a38ce2..f0128d04a 100644 --- a/libretroshare/src/turtle/rsturtleitem.cc +++ b/libretroshare/src/turtle/rsturtleitem.cc @@ -53,6 +53,7 @@ RsItem *RsTurtleSerialiser::create_item(uint16_t service,uint8_t item_subtype) c case RS_TURTLE_SUBTYPE_OPEN_TUNNEL : return new RsTurtleOpenTunnelItem(); case RS_TURTLE_SUBTYPE_TUNNEL_OK : return new RsTurtleTunnelOkItem(); case RS_TURTLE_SUBTYPE_GENERIC_DATA : return new RsTurtleGenericDataItem(); + case RS_TURTLE_SUBTYPE_GENERIC_FAST_DATA : return new RsTurtleGenericFastDataItem(); case RS_TURTLE_SUBTYPE_GENERIC_SEARCH_REQUEST : return new RsTurtleGenericSearchRequestItem(); case RS_TURTLE_SUBTYPE_GENERIC_SEARCH_RESULT : return new RsTurtleGenericSearchResultItem(); @@ -244,8 +245,12 @@ void RsTurtleTunnelOkItem::serial_process(RsGenericSerializer::SerializeJob j,Rs void RsTurtleGenericDataItem::serial_process(RsGenericSerializer::SerializeJob j,RsGenericSerializer::SerializeContext& ctx) { RsTypeSerializer::serial_process(j,ctx,tunnel_id ,"tunnel_id") ; - RsTypeSerializer::TlvMemBlock_proxy prox(data_bytes,data_size) ; - + RsTypeSerializer::serial_process(j,ctx,prox,"data bytes") ; +} +void RsTurtleGenericFastDataItem::serial_process(RsGenericSerializer::SerializeJob j,RsGenericSerializer::SerializeContext& ctx) +{ + RsTypeSerializer::serial_process(j,ctx,tunnel_id ,"tunnel_id") ; + RsTypeSerializer::TlvMemBlock_proxy prox(data_bytes,data_size) ; RsTypeSerializer::serial_process(j,ctx,prox,"data bytes") ; } diff --git a/libretroshare/src/turtle/rsturtleitem.h b/libretroshare/src/turtle/rsturtleitem.h index 5f29ca0ea..842a32aa9 100644 --- a/libretroshare/src/turtle/rsturtleitem.h +++ b/libretroshare/src/turtle/rsturtleitem.h @@ -52,6 +52,7 @@ const uint8_t RS_TURTLE_SUBTYPE_FILE_MAP_REQUEST = 0x11 ; // const uint8_t RS_TURTLE_SUBTYPE_FILE_CRC_REQUEST = 0x13 ; const uint8_t RS_TURTLE_SUBTYPE_CHUNK_CRC = 0x14 ; const uint8_t RS_TURTLE_SUBTYPE_CHUNK_CRC_REQUEST = 0x15 ; +const uint8_t RS_TURTLE_SUBTYPE_GENERIC_FAST_DATA = 0x16 ; class TurtleSearchRequestInfo ; @@ -331,6 +332,28 @@ class RsTurtleGenericDataItem: public RsTurtleGenericTunnelItem void serial_process(RsGenericSerializer::SerializeJob j,RsGenericSerializer::SerializeContext& ctx); }; +// Same, but with a fact priority. Can rather be used for e.g. distant chat. +// +class RsTurtleGenericFastDataItem: public RsTurtleGenericTunnelItem +{ + public: + RsTurtleGenericFastDataItem() : RsTurtleGenericTunnelItem(RS_TURTLE_SUBTYPE_GENERIC_FAST_DATA), data_size(0), data_bytes(0) { setPriorityLevel(QOS_PRIORITY_RS_TURTLE_GENERIC_FAST_DATA);} + virtual ~RsTurtleGenericFastDataItem() { if(data_bytes != NULL) free(data_bytes) ; } + + virtual bool shouldStampTunnel() const { return true ; } + + uint32_t data_size ; + void *data_bytes ; + + void clear() + { + free(data_bytes) ; + data_bytes = NULL ; + data_size = 0; + } + protected: + void serial_process(RsGenericSerializer::SerializeJob j,RsGenericSerializer::SerializeContext& ctx); +}; /***********************************************************************************/ /* Turtle Serialiser class */ /***********************************************************************************/ From 4ac6d7b7d1c83d10fdd54a5b4fdda8fa467d8ae4 Mon Sep 17 00:00:00 2001 From: Gioacchino Mazzurco Date: Fri, 12 Apr 2019 11:49:42 +0200 Subject: [PATCH 75/81] Fix appveyor badge link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3d98c2312..2619312a8 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Build Status | Platform | Build Status | | :------------- | :------------- | | GNU/Linux, MacOS, (via travis-ci) | [![Build Status](https://travis-ci.org/RetroShare/RetroShare.svg?branch=master)](https://travis-ci.org/RetroShare/RetroShare) | -| Windows, `MSys2` (via appveyor) | [![Build status](https://ci.appveyor.com/api/projects/status/github/RetroShare/RetroShare?svg=true)](https://ci.appveyor.com/project/G10h4ck/retroshare-u4lmn) | +| Windows, `MSys2` (via appveyor) | [![Build status](https://ci.appveyor.com/api/projects/status/github/RetroShare/RetroShare?svg=true)](https://ci.appveyor.com/project/RetroShare58622/retroshare) | Compilation on Windows ---------------------------- From 44d0cbe2959b52cbcd0be7ad98aba798d3c12f83 Mon Sep 17 00:00:00 2001 From: csoler Date: Fri, 12 Apr 2019 21:29:49 +0200 Subject: [PATCH 76/81] finished fast track turtle items for distant chat --- libretroshare/src/gxstunnel/p3gxstunnel.cc | 51 +++++++++++++++++----- libretroshare/src/gxstunnel/p3gxstunnel.h | 11 ++++- retroshare.pri | 10 ++++- 3 files changed, 60 insertions(+), 12 deletions(-) diff --git a/libretroshare/src/gxstunnel/p3gxstunnel.cc b/libretroshare/src/gxstunnel/p3gxstunnel.cc index a66170270..d5e3b3a90 100644 --- a/libretroshare/src/gxstunnel/p3gxstunnel.cc +++ b/libretroshare/src/gxstunnel/p3gxstunnel.cc @@ -770,7 +770,11 @@ void p3GxsTunnelService::receiveTurtleData(const RsTurtleGenericTunnelItem *gite // This function encrypts the given data and adds a MAC and an IV into a serialised memory chunk that is then sent through the tunnel. +#ifndef V07_NON_BACKWARD_COMPATIBLE_CHANGE_004 bool p3GxsTunnelService::handleEncryptedData(const uint8_t *data_bytes,uint32_t data_size,const TurtleFileHash& hash,const RsPeerId& virtual_peer_id,bool accepts_fast_items) +#else +bool p3GxsTunnelService::handleEncryptedData(const uint8_t *data_bytes,uint32_t data_size,const TurtleFileHash& hash,const RsPeerId& virtual_peer_id) +#endif { #ifdef DEBUG_GXS_TUNNEL std::cerr << "p3GxsTunnelService::handleEncryptedDataItem()" << std::endl; @@ -813,9 +817,15 @@ bool p3GxsTunnelService::handleEncryptedData(const uint8_t *data_bytes,uint32_t std::cerr << "(EE) no tunnel data for tunnel ID=" << tunnel_id << ". This is a bug." << std::endl; return false ; } - +#ifndef V07_NON_BACKWARD_COMPATIBLE_CHANGE_004 if(accepts_fast_items) - it2->second.accepts_fast_turtle_items = accepts_fast_items; + { + if(!it2->second.accepts_fast_turtle_items) + std::cerr << "(II) received probe for Fast track turtle items for tunnel VPID " << it2->second.virtual_peer_id << ": switching to Fast items mode." << std::endl; + + it2->second.accepts_fast_turtle_items = true; + } +#endif memcpy(aes_key,it2->second.aes_key,GXS_TUNNEL_AES_KEY_SIZE) ; @@ -1342,27 +1352,48 @@ bool p3GxsTunnelService::locked_sendEncryptedTunnelData(RsGxsTunnelItem *item) // We send the item through the turtle tunnel. We do that using the new 'fast' item type if the tunnel accepts it, and using the old slow one otherwise. // Still if the tunnel hasn't been probed, we duplicate the packet using the new fast item format. The packet being received twice on the other side will // be discarded with a warning. + // Note that because the data is deleted by sendTurtleData(), we need to send all packets at the end, and properly duplicate the data when needed. + +#ifdef V07_NON_BACKWARD_COMPATIBLE_CHANGE_004 + RsTurtleGenericFastDataItem *gitem = new RsTurtleGenericFastDataItem; + gitem->data_bytes = data_bytes; + gitem->data_size = data_size ; +#else + RsTurtleGenericDataItem *gitem = NULL; + RsTurtleGenericFastDataItem *gitem2 = NULL; if(!it->second.accepts_fast_turtle_items) { - RsTurtleGenericDataItem *gitem = new RsTurtleGenericDataItem ; + std::cerr << "Sending old format (slow) item for packet IV=" << std::hex << IV << std::dec << " in tunnel VPID=" << it->second.virtual_peer_id << std::endl; + gitem = new RsTurtleGenericDataItem ; gitem->data_bytes = data_bytes; gitem->data_size = data_size ; - - mTurtle->sendTurtleData(virtual_peer_id,gitem) ; } if(it->second.accepts_fast_turtle_items || !it->second.already_probed_for_fast_items) { - RsTurtleGenericFastDataItem *gitem = new RsTurtleGenericFastDataItem ; -#warning we should duplicate the data here, otherwise it's gonna crash - gitem->data_bytes = data_bytes; - gitem->data_size = data_size ; + std::cerr << "Sending new format (fast) item for packet IV=" << std::hex << IV << std::dec << " in tunnel VPID=" << it->second.virtual_peer_id << std::endl; + gitem2 = new RsTurtleGenericFastDataItem ; + + if(gitem != NULL) // duplicate the data because it was already sent in gitem. + { + gitem2->data_bytes = rs_malloc(data_size); + gitem2->data_size = data_size ; + memcpy(gitem2->data_bytes,data_bytes,data_size); + } + else + { + gitem2->data_bytes = data_bytes; + gitem2->data_size = data_size ; + } it->second.already_probed_for_fast_items = true; - mTurtle->sendTurtleData(virtual_peer_id,gitem) ; + } + if(gitem2) mTurtle->sendTurtleData(virtual_peer_id,gitem2) ; +#endif + if(gitem) mTurtle->sendTurtleData(virtual_peer_id,gitem) ; return true ; } diff --git a/libretroshare/src/gxstunnel/p3gxstunnel.h b/libretroshare/src/gxstunnel/p3gxstunnel.h index 98b68f161..00bd6d65a 100644 --- a/libretroshare/src/gxstunnel/p3gxstunnel.h +++ b/libretroshare/src/gxstunnel/p3gxstunnel.h @@ -147,7 +147,10 @@ private: class GxsTunnelPeerInfo { public: - GxsTunnelPeerInfo() : last_contact(0), last_keep_alive_sent(0), status(0), direction(0),accepts_fast_turtle_items(false) + GxsTunnelPeerInfo() : last_contact(0), last_keep_alive_sent(0), status(0), direction(0) +#ifndef V07_NON_BACKWARD_COMPATIBLE_CHANGE_004 + ,accepts_fast_turtle_items(false) +#endif { memset(aes_key, 0, GXS_TUNNEL_AES_KEY_SIZE); @@ -170,8 +173,10 @@ private: std::map received_data_prints ; // list of recently received messages, to avoid duplicates. Kept for 20 mins at most. uint32_t total_sent ; // total data sent to this peer uint32_t total_received ; // total data received by this peer +#ifndef V07_NON_BACKWARD_COMPATIBLE_CHANGE_004 bool accepts_fast_turtle_items; // does the tunnel accept RsTurtleGenericFastDataItem type? bool already_probed_for_fast_items; // has the tunnel been probed already? If not, a fast item will be sent +#endif }; class GxsTunnelDHInfo @@ -243,7 +248,11 @@ private: bool locked_sendEncryptedTunnelData(RsGxsTunnelItem *item) ; bool locked_sendClearTunnelData(RsGxsTunnelDHPublicKeyItem *item); // this limits the usage to DH items. Others should be encrypted! +#ifndef V07_NON_BACKWARD_COMPATIBLE_CHANGE_004 bool handleEncryptedData(const uint8_t *data_bytes, uint32_t data_size, const TurtleFileHash& hash, const RsPeerId& virtual_peer_id, bool accepts_fast_items) ; +#else + bool handleEncryptedData(const uint8_t *data_bytes, uint32_t data_size, const TurtleFileHash& hash, const RsPeerId& virtual_peer_id) ; +#endif // local data diff --git a/retroshare.pri b/retroshare.pri index 7f687d766..2f2dac230 100644 --- a/retroshare.pri +++ b/retroshare.pri @@ -230,11 +230,18 @@ isEmpty(RS_UPNP_LIB):RS_UPNP_LIB = upnp ixml threadutil # # V07_NON_BACKWARD_COMPATIBLE_CHANGE_003: # -# What: Do not hash PGP certificate twice when signing +# What: Do not hash PGP certificate twice when signing # # Why: hasing twice is not per se a security issue, but it makes it harder to change the settings for hashing. # # Backward compat: patched peers cannot connect to non patched peers older than Nov 2017. +# +# V07_NON_BACKWARD_COMPATIBLE_CHANGE_004: +# +# What: Do not probe that GXS tunnels accept fast items. Just assume they do. +# Why: Avoids sending probe packets +# BackwardCompat: old RS before Mai 2019 will not be able to distant chat. +# ########################################################################################################################################################### #CONFIG += rs_v07_changes @@ -242,6 +249,7 @@ rs_v07_changes { DEFINES += V07_NON_BACKWARD_COMPATIBLE_CHANGE_001 DEFINES += V07_NON_BACKWARD_COMPATIBLE_CHANGE_002 DEFINES += V07_NON_BACKWARD_COMPATIBLE_CHANGE_003 + DEFINES += V07_NON_BACKWARD_COMPATIBLE_CHANGE_004 DEFINES += V07_NON_BACKWARD_COMPATIBLE_CHANGE_UNNAMED } From 4d703b9df95c6a5c29b892b9b0c25c392d0088ad Mon Sep 17 00:00:00 2001 From: Gioacchino Mazzurco Date: Fri, 12 Apr 2019 22:14:16 +0200 Subject: [PATCH 77/81] Increase waitToken interval for channel creation Creating GXS groups imply a bunch of crypto operations that require lot of time expecially on embedded device, channel creation was reported as failed while it was still pending. Reduce too long lines. Print API error messages also on std::cerr. --- libretroshare/src/pqi/pqi_base.h | 7 +- libretroshare/src/retroshare/rsgxschannels.h | 108 ++++++++++++------- libretroshare/src/services/p3gxschannels.cc | 58 +++++++--- libretroshare/src/services/p3gxschannels.h | 14 +-- 4 files changed, 121 insertions(+), 66 deletions(-) diff --git a/libretroshare/src/pqi/pqi_base.h b/libretroshare/src/pqi/pqi_base.h index 7d284818b..e220a376d 100644 --- a/libretroshare/src/pqi/pqi_base.h +++ b/libretroshare/src/pqi/pqi_base.h @@ -185,9 +185,10 @@ class NetInterface; **/ class PQInterface: public RateInterface { - public: - explicit PQInterface(const RsPeerId &id) :traf_in(0), traf_out(0),peerId(id) { return; } - virtual ~PQInterface() { return; } +public: + explicit PQInterface(const RsPeerId &id) : + traf_in(0), traf_out(0), peerId(id) {} + virtual ~PQInterface() {} /*! * allows user to send RsItems to a particular facility (file, network) diff --git a/libretroshare/src/retroshare/rsgxschannels.h b/libretroshare/src/retroshare/rsgxschannels.h index 9fd2cd28e..a78a86ce1 100644 --- a/libretroshare/src/retroshare/rsgxschannels.h +++ b/libretroshare/src/retroshare/rsgxschannels.h @@ -104,58 +104,80 @@ public: /** * @brief Create channel. Blocking API. * @jsonapi{development} - * @param[in] name Name of the channel - * @param[in] description Description of the channel - * @param[in] thumbnail Optional image to show as channel thumbnail. - * @param[in] authorId Optional id of the author. Leave empty for an anonymous channel. - * @param[in] circleType Optional visibility rule, default public. - * @param[in] circleId If the channel is not public specify the id of the circle who can see the channel. Depending on the value you pass for - * circleType this should be be an external circle if EXTERNAL is passed, a - * local friend group id if NODES_GROUP is passed, empty otherwise. - * @param[out] channelId Optional storage for the id of the created channel, meaningful only if creations succeeds. - * @param[out] errorMessage Optional storage for error messsage, meaningful only if creation fail. + * @param[in] name Name of the channel + * @param[in] description Description of the channel + * @param[in] thumbnail Optional image to show as channel thumbnail. + * @param[in] authorId Optional id of the author. Leave empty for an + * anonymous channel. + * @param[in] circleType Optional visibility rule, default public. + * @param[in] circleId If the channel is not public specify the id of + * the circle who can see the channel. Depending on + * the value you pass for + * circleType this should be be an external circle + * if EXTERNAL is passed, a local friend group id + * if NODES_GROUP is passed, empty otherwise. + * @param[out] channelId Optional storage for the id of the created + * channel, meaningful only if creations succeeds. + * @param[out] errorMessage Optional storage for error messsage, meaningful + * only if creation fail. * @return False on error, true otherwise. */ - virtual bool createChannelV2(const std::string& name, - const std::string& description, - const RsGxsImage& thumbnail = RsGxsImage(), - const RsGxsId& authorId = RsGxsId(), - RsGxsCircleType circleType = RsGxsCircleType::PUBLIC, - const RsGxsCircleId& circleId = RsGxsCircleId(), - RsGxsGroupId& channelGroupId = RS_DEFAULT_STORAGE_PARAM(RsGxsGroupId), - std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) ) = 0; + virtual bool createChannelV2( + const std::string& name, + const std::string& description, + const RsGxsImage& thumbnail = RsGxsImage(), + const RsGxsId& authorId = RsGxsId(), + RsGxsCircleType circleType = RsGxsCircleType::PUBLIC, + const RsGxsCircleId& circleId = RsGxsCircleId(), + RsGxsGroupId& channelGroupId = RS_DEFAULT_STORAGE_PARAM(RsGxsGroupId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) + ) = 0; /** * @brief Add a comment on a post or on another comment. Blocking API. * @jsonapi{development} - * @param[in] channelId Id of the channel in which the comment is to be posted - * @param[in] threadId Id of the post (that is a thread) in the channel where the comment is placed - * @param[in] parentId Id of the parent of the comment that is either a channel post Id or the Id of another comment. + * @param[in] channelId Id of the channel in which the comment is to be + * posted + * @param[in] threadId Id of the post (that is a thread) in the channel + * where the comment is placed + * @param[in] parentId Id of the parent of the comment that is either a + * channel post Id or the Id of another comment. * @param[in] authorId Id of the author of the comment - * @param[in] comment UTF-8 string containing the comment itself - * @param[out] commentMessageId Optional storage for the id of the comment that was created, meaningful only on success. - * @param[out] errorMessage Optional storage for error message, meaningful only on failure. + * @param[in] comment UTF-8 string containing the comment itself + * @param[out] commentMessageId Optional storage for the id of the comment + * that was created, meaningful only on success. + * @param[out] errorMessage Optional storage for error message, meaningful + * only on failure. * @return false on error, true otherwise */ - virtual bool createCommentV2(const RsGxsGroupId& channelId, - const RsGxsMessageId& threadId, - const RsGxsMessageId& parentId, - const RsGxsId& authorId, - const std::string& comment, - RsGxsMessageId& commentMessageId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), - std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) )=0; + virtual bool createCommentV2( + const RsGxsGroupId& channelId, + const RsGxsMessageId& threadId, + const RsGxsMessageId& parentId, + const RsGxsId& authorId, + const std::string& comment, + RsGxsMessageId& commentMessageId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) + ) = 0; /** * @brief Create channel post. Blocking API. * @jsonapi{development} - * @param[in] channelId Id of the channel where to put the post. Beware you need publish rights on that channel to post. + * @param[in] channelId Id of the channel where to put the post. Beware + * you need publish rights on that channel to post. * @param[in] title Title of the post * @param[in] mBody Text content of the post - * @param[in] files Optional list of attached files. These are supposed to be already shared, @see ExtraFileHash() below otherwise. + * @param[in] files Optional list of attached files. These are + * supposed to be already shared, + * @see ExtraFileHash() below otherwise. * @param[in] thumbnail Optional thumbnail image for the post. - * @param[in] origPostId If this is supposed to replace an already existent post, the id of the old post. If left blank a new post will be created. - * @param[out] postId Optional storage for the id of the created post, meaningful only on success. - * @param[out] errorMessage Optional storage for the error message, meaningful only on failure. + * @param[in] origPostId If this is supposed to replace an already + * existent post, the id of the old post. If left + * blank a new post will be created. + * @param[out] postId Optional storage for the id of the created post, + * meaningful only on success. + * @param[out] errorMessage Optional storage for the error message, + * meaningful only on failure. * @return false on error, true otherwise */ virtual bool createPostV2( @@ -171,13 +193,17 @@ public: * @brief Create a vote * @jsonapi{development} * @param[in] channelId Id of the channel where to vote - * @param[in] postId Id of the channel post of which a comment is voted + * @param[in] postId Id of the channel post of which a comment is + * voted. * @param[in] commentId Id of the comment that is voted - * @param[in] authorId Id of the author. Needs to be of an owned identity. - * @param[in] vote Vote value, either RsGxsVoteType::DOWN or RsGxsVoteType::UP - * @param[out] voteId Optional storage for the id of the created vote, meaningful only on success. + * @param[in] authorId Id of the author. Needs to be of an owned + * identity. + * @param[in] vote Vote value, either RsGxsVoteType::DOWN or + * RsGxsVoteType::UP + * @param[out] voteId Optional storage for the id of the created vote, + * meaningful only on success. * @param[out] errorMessage Optional storage for error message, meaningful - * only on failure. + * only on failure. * @return false on error, true otherwise */ virtual bool createVoteV2( diff --git a/libretroshare/src/services/p3gxschannels.cc b/libretroshare/src/services/p3gxschannels.cc index bcf0ad3b3..367023cad 100644 --- a/libretroshare/src/services/p3gxschannels.cc +++ b/libretroshare/src/services/p3gxschannels.cc @@ -1147,7 +1147,9 @@ bool p3GxsChannels::createChannelV2( } // wait for the group creation to complete. - RsTokenService::GxsRequestStatus wSt = waitToken(token); + RsTokenService::GxsRequestStatus wSt = + waitToken( token, std::chrono::milliseconds(5000), + std::chrono::milliseconds(20) ); if(wSt != RsTokenService::COMPLETE) { errorMessage = "GXS operation waitToken failed with: " @@ -1450,63 +1452,89 @@ bool p3GxsChannels::createCommentV2(const RsGxsGroupId& channelId, std::vector posts; std::vector comments; - if(!getChannelContent( channelId,std::set({threadId}),posts,comments )) // does the post thread exist? + if(!getChannelContent( // does the post thread exist? + channelId,std::set({threadId}), posts, comments )) { - errorMessage = "You cannot comment post " + threadId.toStdString() + " of channel with Id " + channelId.toStdString() + ": this post does not exists locally!"; + errorMessage = "You cannot comment post " + threadId.toStdString() + + " of channel with Id " + channelId.toStdString() + + ": this post does not exists locally!"; + std::cerr << __PRETTY_FUNCTION__ << " Error: " << errorMessage + << std::endl; return false; } - if(posts.size() != 1 || !posts[0].mMeta.mParentId.isNull()) // check that the post thread Id is actually that of a post thread + // check that the post thread Id is actually that of a post thread + if(posts.size() != 1 || !posts[0].mMeta.mParentId.isNull()) { - errorMessage = std::string("You cannot comment post " + threadId.toStdString() + " of channel with Id " + channelId.toStdString() + ": supplied threadId is not a thread, or parentMsgId is not a comment!"); + errorMessage = "You cannot comment post " + threadId.toStdString() + + " of channel with Id " + channelId.toStdString() + + ": supplied threadId is not a thread, or parentMsgId is not a" + + " comment!"; + std::cerr << __PRETTY_FUNCTION__ << " Error: " << errorMessage + << std::endl; return false; } if(!parentId.isNull()) - if(!getChannelContent( channelId,std::set({parentId}),posts,comments )) // does the post thread exist? + if(!getChannelContent( // does the post thread exist? + channelId,std::set({parentId}),posts,comments )) { - errorMessage = std::string("You cannot comment post " + parentId.toStdString() + ": supplied parent comment Id is not a comment!"); + errorMessage = "You cannot comment post " + parentId.toStdString() + + ": supplied parent comment Id is not a comment!"; + std::cerr << __PRETTY_FUNCTION__ << " Error: " << errorMessage + << std::endl; return false; } - else if(comments.size() != 1 || comments[0].mMeta.mParentId.isNull()) // is the comment parent actually a comment? - { - errorMessage = std::string("You cannot comment post " + parentId.toStdString() + " of channel with Id " + channelId.toStdString() + ": supplied mParentMsgId is not a comment Id!"); + else if(comments.size() != 1 || comments[0].mMeta.mParentId.isNull()) + { // is the comment parent actually a comment? + errorMessage = "You cannot comment post " + parentId.toStdString() + + " of channel with Id " + channelId.toStdString() + + ": supplied mParentMsgId is not a comment Id!"; + std::cerr << __PRETTY_FUNCTION__ << " Error: " << errorMessage + << std::endl; return false; } if(!rsIdentity->isOwnId(authorId)) // is the voter ID actually ours? { - errorMessage = std::string("You cannot comment to channel with Id " + channelId.toStdString() + " with identity " + authorId.toStdString() + " because it is not yours."); + errorMessage = "You cannot comment to channel with Id " + + channelId.toStdString() + " with identity " + + authorId.toStdString() + " because it is not yours."; + std::cerr << __PRETTY_FUNCTION__ << " Error: " << errorMessage + << std::endl; return false; } // Now create the comment - RsGxsComment cmt; - cmt.mMeta.mGroupId = channelId; cmt.mMeta.mThreadId = threadId; cmt.mMeta.mParentId = parentId; cmt.mMeta.mAuthorId = authorId; - cmt.mComment = comment; uint32_t token; if(!createNewComment(token, cmt)) { errorMessage = "Failed creating comment."; + std::cerr << __PRETTY_FUNCTION__ << " Error: " << errorMessage + << std::endl; return false; } if(waitToken(token) != RsTokenService::COMPLETE) { errorMessage = "GXS operation failed."; + std::cerr << __PRETTY_FUNCTION__ << " Error: " << errorMessage + << std::endl; return false; } if(!RsGenExchange::getPublishedMsgMeta(token, cmt.mMeta)) { - errorMessage = "Failure getting generated comment data."; + errorMessage = "Failure getting created comment data."; + std::cerr << __PRETTY_FUNCTION__ << " Error: " << errorMessage + << std::endl; return false; } diff --git a/libretroshare/src/services/p3gxschannels.h b/libretroshare/src/services/p3gxschannels.h index a038904b4..dffc73c32 100644 --- a/libretroshare/src/services/p3gxschannels.h +++ b/libretroshare/src/services/p3gxschannels.h @@ -212,13 +212,13 @@ virtual bool ExtraFileRemove(const RsFileHash &hash); virtual bool createComment(RsGxsComment& comment) override; /// Implementation of @see RsGxsChannels::createComment - virtual bool createCommentV2(const RsGxsGroupId& channelId, - const RsGxsMessageId& threadId, - const RsGxsMessageId& parentId, - const RsGxsId& authorId, - const std::string& comment, - RsGxsMessageId& commentMessageId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), - std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string)) override; + virtual bool createCommentV2( + const RsGxsGroupId& channelId, const RsGxsMessageId& threadId, + const RsGxsMessageId& parentId, const RsGxsId& authorId, + const std::string& comment, + RsGxsMessageId& commentMessageId = RS_DEFAULT_STORAGE_PARAM(RsGxsMessageId), + std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) + ) override; /// Implementation of @see RsGxsChannels::editChannel virtual bool editChannel(RsGxsChannelGroup& channel) override; From b25c4ecb7766fbebfee77a1416f16876010e8c70 Mon Sep 17 00:00:00 2001 From: Gioacchino Mazzurco Date: Fri, 12 Apr 2019 23:10:09 +0200 Subject: [PATCH 78/81] Fix channels JSON API --- libretroshare/src/retroshare/rsgxschannels.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libretroshare/src/retroshare/rsgxschannels.h b/libretroshare/src/retroshare/rsgxschannels.h index a78a86ce1..9ff20cd11 100644 --- a/libretroshare/src/retroshare/rsgxschannels.h +++ b/libretroshare/src/retroshare/rsgxschannels.h @@ -129,7 +129,7 @@ public: const RsGxsId& authorId = RsGxsId(), RsGxsCircleType circleType = RsGxsCircleType::PUBLIC, const RsGxsCircleId& circleId = RsGxsCircleId(), - RsGxsGroupId& channelGroupId = RS_DEFAULT_STORAGE_PARAM(RsGxsGroupId), + RsGxsGroupId& channelId = RS_DEFAULT_STORAGE_PARAM(RsGxsGroupId), std::string& errorMessage = RS_DEFAULT_STORAGE_PARAM(std::string) ) = 0; From 64fecf42f426d32c88d917129ee91e7602f62ef1 Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 14 Apr 2019 15:50:25 +0200 Subject: [PATCH 79/81] moved MessagesDialog.* to msgs/ --- retroshare-gui/src/gui/{ => msgs}/MessagesDialog.cpp | 0 retroshare-gui/src/gui/{ => msgs}/MessagesDialog.h | 0 retroshare-gui/src/gui/{ => msgs}/MessagesDialog.ui | 0 retroshare-gui/src/retroshare-gui.pro | 6 +++--- 4 files changed, 3 insertions(+), 3 deletions(-) rename retroshare-gui/src/gui/{ => msgs}/MessagesDialog.cpp (100%) rename retroshare-gui/src/gui/{ => msgs}/MessagesDialog.h (100%) rename retroshare-gui/src/gui/{ => msgs}/MessagesDialog.ui (100%) diff --git a/retroshare-gui/src/gui/MessagesDialog.cpp b/retroshare-gui/src/gui/msgs/MessagesDialog.cpp similarity index 100% rename from retroshare-gui/src/gui/MessagesDialog.cpp rename to retroshare-gui/src/gui/msgs/MessagesDialog.cpp diff --git a/retroshare-gui/src/gui/MessagesDialog.h b/retroshare-gui/src/gui/msgs/MessagesDialog.h similarity index 100% rename from retroshare-gui/src/gui/MessagesDialog.h rename to retroshare-gui/src/gui/msgs/MessagesDialog.h diff --git a/retroshare-gui/src/gui/MessagesDialog.ui b/retroshare-gui/src/gui/msgs/MessagesDialog.ui similarity index 100% rename from retroshare-gui/src/gui/MessagesDialog.ui rename to retroshare-gui/src/gui/msgs/MessagesDialog.ui diff --git a/retroshare-gui/src/retroshare-gui.pro b/retroshare-gui/src/retroshare-gui.pro index 5769274b8..70050a727 100644 --- a/retroshare-gui/src/retroshare-gui.pro +++ b/retroshare-gui/src/retroshare-gui.pro @@ -443,6 +443,7 @@ HEADERS += rshare.h \ gui/connect/ConfCertDialog.h \ gui/connect/PGPKeyDialog.h \ gui/connect/FriendRecommendDialog.h \ + gui/msgs/MessagesDialog.h \ gui/msgs/MessageInterface.h \ gui/msgs/MessageComposer.h \ gui/msgs/MessageWindow.h \ @@ -541,7 +542,6 @@ HEADERS += rshare.h \ gui/common/ToasterNotify.h \ gui/style/RSStyle.h \ gui/style/StyleDialog.h \ - gui/MessagesDialog.h \ gui/help/browser/helpbrowser.h \ gui/help/browser/helptextbrowser.h \ gui/statusbar/peerstatus.h \ @@ -621,7 +621,6 @@ FORMS += gui/StartDialog.ui \ gui/FriendsDialog.ui \ gui/ShareManager.ui \ # gui/ShareDialog.ui \ - gui/MessagesDialog.ui \ gui/help/browser/helpbrowser.ui \ gui/HelpDialog.ui \ gui/ServicePermissionDialog.ui \ @@ -640,6 +639,7 @@ FORMS += gui/StartDialog.ui \ gui/connect/ConnectFriendWizard.ui \ gui/connect/ConnectProgressDialog.ui \ gui/connect/FriendRecommendDialog.ui \ + gui/msgs/MessagesDialog.ui \ gui/msgs/MessageComposer.ui \ gui/msgs/MessageWindow.ui\ gui/msgs/MessageWidget.ui\ @@ -745,7 +745,6 @@ SOURCES += main.cpp \ # gui/ShareDialog.cpp \ # gui/SFListDelegate.cpp \ gui/SoundManager.cpp \ - gui/MessagesDialog.cpp \ gui/im_history/ImHistoryBrowser.cpp \ gui/im_history/IMHistoryItemDelegate.cpp \ gui/im_history/IMHistoryItemPainter.cpp \ @@ -800,6 +799,7 @@ SOURCES += main.cpp \ gui/chat/ChatLobbyUserNotify.cpp \ gui/connect/ConfCertDialog.cpp \ gui/connect/PGPKeyDialog.cpp \ + gui/msgs/MessagesDialog.cpp \ gui/msgs/MessageComposer.cpp \ gui/msgs/MessageWidget.cpp \ gui/msgs/MessageWindow.cpp \ From 0bcbe14b2c7cf37cc3419bc1550609a7f46731ca Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 14 Apr 2019 16:25:26 +0200 Subject: [PATCH 80/81] fixed wrong display of trash messages in inbox --- libretroshare/src/retroshare/rsmsgs.h | 4 +-- retroshare-gui/src/gui/MainWindow.cpp | 2 +- retroshare-gui/src/gui/msgs/MessageModel.cpp | 14 +++++----- .../src/gui/msgs/MessagesDialog.cpp | 26 +++++++++---------- 4 files changed, 23 insertions(+), 23 deletions(-) diff --git a/libretroshare/src/retroshare/rsmsgs.h b/libretroshare/src/retroshare/rsmsgs.h index 6658a53bc..f1e42c4c3 100644 --- a/libretroshare/src/retroshare/rsmsgs.h +++ b/libretroshare/src/retroshare/rsmsgs.h @@ -563,8 +563,8 @@ public: /** * @brief MessageToTrash * @jsonapi{development} - * @param[in] msgId - * @param[in] bTrash + * @param[in] msgId Id of the message to mode to trash box + * @param[in] bTrash Move to trash if true, otherwise remove from trash * @return true on success */ virtual bool MessageToTrash(const std::string &msgId, bool bTrash) = 0; diff --git a/retroshare-gui/src/gui/MainWindow.cpp b/retroshare-gui/src/gui/MainWindow.cpp index c9e2e9c0b..3a81877ce 100644 --- a/retroshare-gui/src/gui/MainWindow.cpp +++ b/retroshare-gui/src/gui/MainWindow.cpp @@ -40,7 +40,7 @@ #include "gui/FileTransfer/SearchDialog.h" #include "gui/FileTransfer/SharedFilesDialog.h" #include "gui/FileTransfer/TransfersDialog.h" -#include "MessagesDialog.h" +#include "gui/msgs/MessagesDialog.h" #include "PluginsPage.h" #include "NewsFeed.h" #include "ShareManager.h" diff --git a/retroshare-gui/src/gui/msgs/MessageModel.cpp b/retroshare-gui/src/gui/msgs/MessageModel.cpp index 3f30b2342..441b02bbc 100644 --- a/retroshare-gui/src/gui/msgs/MessageModel.cpp +++ b/retroshare-gui/src/gui/msgs/MessageModel.cpp @@ -336,11 +336,11 @@ bool RsMessageModel::passesFilter(const Rs::Msgs::MsgInfoSummary& fmpe,int colum || (std::find(fmpe.msgtags.begin(),fmpe.msgtags.end(),mQuickViewFilter) != fmpe.msgtags.end()) || (mQuickViewFilter==QUICK_VIEW_STARRED && (fmpe.msgflags & RS_MSG_STAR)) || (mQuickViewFilter==QUICK_VIEW_SYSTEM && (fmpe.msgflags & RS_MSG_SYSTEM)); - - std::cerr << "Passes filter: type=" << mFilterType << " s=\"" << s.toStdString() - << "MsgFlags=" << fmpe.msgflags << " msgtags=" ; +#ifdef DEBUG_MESSAGE_MODEL + std::cerr << "Passes filter: type=" << mFilterType << " s=\"" << s.toStdString() << "MsgFlags=" << fmpe.msgflags << " msgtags=" ; foreach(uint32_t i,fmpe.msgtags) std::cerr << i << " " ; std::cerr << "\" strings:" << passes_strings << " quick_view:" << passes_quick_view << std::endl; +#endif return passes_quick_view && passes_strings; } @@ -621,10 +621,10 @@ void RsMessageModel::getMessageSummaries(BoxName box,std::listmsgflags & RS_MSG_BOXMASK) == RS_MSG_INBOX ; break ; - case BOX_SENT : ok = (it->msgflags & RS_MSG_BOXMASK) == RS_MSG_SENTBOX; break ; - case BOX_OUTBOX : ok = (it->msgflags & RS_MSG_BOXMASK) == RS_MSG_OUTBOX ; break ; - case BOX_DRAFTS : ok = (it->msgflags & RS_MSG_BOXMASK) == RS_MSG_DRAFTBOX ; break ; + case BOX_INBOX : ok = (it->msgflags & RS_MSG_BOXMASK) == RS_MSG_INBOX && !(it->msgflags & RS_MSG_TRASH); break ; + case BOX_SENT : ok = (it->msgflags & RS_MSG_BOXMASK) == RS_MSG_SENTBOX && !(it->msgflags & RS_MSG_TRASH); break ; + case BOX_OUTBOX : ok = (it->msgflags & RS_MSG_BOXMASK) == RS_MSG_OUTBOX && !(it->msgflags & RS_MSG_TRASH); break ; + case BOX_DRAFTS : ok = (it->msgflags & RS_MSG_BOXMASK) == RS_MSG_DRAFTBOX && !(it->msgflags & RS_MSG_TRASH); break ; case BOX_TRASH : ok = (it->msgflags & RS_MSG_TRASH) ; break ; default: ++it; diff --git a/retroshare-gui/src/gui/msgs/MessagesDialog.cpp b/retroshare-gui/src/gui/msgs/MessagesDialog.cpp index e8c130e88..2837b5b3a 100644 --- a/retroshare-gui/src/gui/msgs/MessagesDialog.cpp +++ b/retroshare-gui/src/gui/msgs/MessagesDialog.cpp @@ -27,21 +27,21 @@ #include "MessagesDialog.h" -#include "notifyqt.h" -#include "common/TagDefs.h" -#include "common/PeerDefs.h" -#include "common/RSElidedItemDelegate.h" -#include "gxs/GxsIdTreeWidgetItem.h" -#include "gxs/GxsIdDetails.h" +#include "gui/notifyqt.h" +#include "gui/common/TagDefs.h" +#include "gui/common/PeerDefs.h" +#include "gui/common/RSElidedItemDelegate.h" +#include "gui/gxs/GxsIdTreeWidgetItem.h" +#include "gui/gxs/GxsIdDetails.h" #include "gui/Identity/IdDialog.h" #include "gui/MainWindow.h" -#include "msgs/MessageComposer.h" -#include "msgs/MessageInterface.h" -#include "msgs/MessageUserNotify.h" -#include "msgs/MessageWidget.h" -#include "msgs/TagsMenu.h" -#include "msgs/MessageModel.h" -#include "settings/rsharesettings.h" +#include "gui/msgs/MessageComposer.h" +#include "gui/msgs/MessageInterface.h" +#include "gui/msgs/MessageUserNotify.h" +#include "gui/msgs/MessageWidget.h" +#include "gui/msgs/TagsMenu.h" +#include "gui/msgs/MessageModel.h" +#include "gui/settings/rsharesettings.h" #include "util/DateTime.h" #include "util/RsProtectedTimer.h" From 7c534d50eaecefe318056f7625290ced368b168d Mon Sep 17 00:00:00 2001 From: defnax Date: Tue, 16 Apr 2019 19:38:13 +0200 Subject: [PATCH 81/81] removed posted links related font-size from qss file removed posted links related font-size from qss file --- retroshare-gui/src/gui/qss/stylesheet/Standard.qss | 5 ----- 1 file changed, 5 deletions(-) diff --git a/retroshare-gui/src/gui/qss/stylesheet/Standard.qss b/retroshare-gui/src/gui/qss/stylesheet/Standard.qss index 0c858f972..f1420a0a3 100644 --- a/retroshare-gui/src/gui/qss/stylesheet/Standard.qss +++ b/retroshare-gui/src/gui/qss/stylesheet/Standard.qss @@ -786,13 +786,11 @@ GenCertDialog QFrame#profileframe{ PostedListWidget QComboBox#comboBox { font: bold; - font-size: 15px; color: #0099cc; } PostedListWidget QToolButton#submitPostButton { font: bold; - font-size: 15px; } PostedListWidget QToolButton#subscribeToolButton { @@ -907,10 +905,7 @@ PostedItem QLabel#fromBoldLabel, QLabel#fromLabel, QLabel#dateLabel, QLabel#site color: #787c7e; } - - GxsCommentDialog QComboBox#sortBox { font: bold; - font-size: 12px; color: #0099cc; }