From 43d64bf0c5aa76a3726310b3598880eeca6de2d2 Mon Sep 17 00:00:00 2001 From: csoler Date: Sun, 9 Feb 2025 21:05:11 +0100 Subject: [PATCH] added abstract item model for identity --- retroshare-gui/src/gui/Identity/IdDialog.cpp | 222 +++-- retroshare-gui/src/gui/Identity/IdDialog.h | 11 +- retroshare-gui/src/gui/Identity/IdDialog.ui | 46 +- .../src/gui/Identity/IdentityListModel.cpp | 814 ++++++++++++++++++ .../src/gui/Identity/IdentityListModel.h | 219 +++++ retroshare-gui/src/retroshare-gui.pro | 2 + 6 files changed, 1142 insertions(+), 172 deletions(-) create mode 100644 retroshare-gui/src/gui/Identity/IdentityListModel.cpp create mode 100644 retroshare-gui/src/gui/Identity/IdentityListModel.h diff --git a/retroshare-gui/src/gui/Identity/IdDialog.cpp b/retroshare-gui/src/gui/Identity/IdDialog.cpp index 032acaa2d..23556d3ad 100644 --- a/retroshare-gui/src/gui/Identity/IdDialog.cpp +++ b/retroshare-gui/src/gui/Identity/IdDialog.cpp @@ -31,6 +31,8 @@ #include "IdDialog.h" #include "ui_IdDialog.h" #include "IdEditDialog.h" +#include "IdentityListModel.h" + #include "gui/RetroShareLink.h" #include "gui/chat/ChatDialog.h" #include "gui/Circles/CreateCircleDialog.h" @@ -92,11 +94,6 @@ /**************************************************************** */ -#define RSID_COL_NICKNAME 0 -#define RSID_COL_KEYID 1 -#define RSID_COL_IDTYPE 2 -#define RSID_COL_VOTES 3 - #define RSIDREP_COL_NAME 0 #define RSIDREP_COL_OPINION 1 #define RSIDREP_COL_COMMENT 2 @@ -168,37 +165,16 @@ IdDialog::IdDialog(QWidget *parent) //mCirclesBroadcastBase = new RsGxsUpdateBroadcastBase(rsGxsCircles, this); //connect(mCirclesBroadcastBase, SIGNAL(fillDisplay(bool)), this, SLOT(updateCirclesDisplay(bool))); - ownItem = new QTreeWidgetItem(); - ownItem->setText(RSID_COL_NICKNAME, tr("My own identities")); - ownItem->setFont(RSID_COL_NICKNAME, ui->idTreeWidget->font()); - ownItem->setData(RSID_COL_VOTES, Qt::DecorationRole,0xff); // this is in order to prevent displaying a reputaiton icon next to these items. + mIdListModel = new RsIdentityListModel(this); - allItem = new QTreeWidgetItem(); - allItem->setText(RSID_COL_NICKNAME, tr("All")); - allItem->setFont(RSID_COL_NICKNAME, ui->idTreeWidget->font()); - allItem->setData(RSID_COL_VOTES, Qt::DecorationRole,0xff); - - contactsItem = new QTreeWidgetItem(); - contactsItem->setText(RSID_COL_NICKNAME, tr("My contacts")); - contactsItem->setFont(RSID_COL_NICKNAME, ui->idTreeWidget->font()); - contactsItem->setData(RSID_COL_VOTES, Qt::DecorationRole,0xff); - - - ui->idTreeWidget->insertTopLevelItem(0, ownItem); - ui->idTreeWidget->insertTopLevelItem(0, allItem); - ui->idTreeWidget->insertTopLevelItem(0, contactsItem ); + ui->idTreeWidget->setModel(mIdListModel); ui->treeWidget_membership->clear(); ui->treeWidget_membership->setItemDelegateForColumn(CIRCLEGROUP_CIRCLE_COL_GROUPNAME,new GxsIdTreeItemDelegate()); - /* Setup UI helper */ mStateHelper = new UIStateHelper(this); -// mStateHelper->addWidget(IDDIALOG_IDLIST, ui->idTreeWidget); - mStateHelper->addLoadPlaceholder(IDDIALOG_IDLIST, ui->idTreeWidget, false); - mStateHelper->addClear(IDDIALOG_IDLIST, ui->idTreeWidget); - //mStateHelper->addWidget(IDDIALOG_IDDETAILS, ui->lineEdit_Nickname); mStateHelper->addWidget(IDDIALOG_IDDETAILS, ui->lineEdit_PublishTS); mStateHelper->addWidget(IDDIALOG_IDDETAILS, ui->lineEdit_KeyId); mStateHelper->addWidget(IDDIALOG_IDDETAILS, ui->lineEdit_Type); @@ -257,8 +233,7 @@ IdDialog::IdDialog(QWidget *parent) connect(ui->inviteButton, SIGNAL(clicked()), this, SLOT(sendInvite())); connect(ui->editButton, SIGNAL(clicked()), this, SLOT(editIdentity())); - connect( ui->idTreeWidget, &RSTreeWidget::itemDoubleClicked, - this, &IdDialog::chatIdentityItem ); + connect( ui->idTreeWidget, &RSTreeWidget::itemDoubleClicked, this, &IdDialog::chatIdentityItem ); ui->editButton->hide(); @@ -340,46 +315,27 @@ IdDialog::IdDialog(QWidget *parent) ui->toolButton_New->setMenu(menu); /* Add filter actions */ - QTreeWidgetItem *headerItem = ui->idTreeWidget->headerItem(); - QString headerText = headerItem->text(RSID_COL_NICKNAME); - ui->filterLineEdit->addFilter(QIcon(), headerText, RSID_COL_NICKNAME, QString("%1 %2").arg(tr("Search"), headerText)); - - headerItem->setData(RSID_COL_VOTES,Qt::UserRole,tr("Reputation")); + ui->filterLineEdit->addFilter(QIcon(), tr("Name"), RsIdentityListModel::COLUMN_THREAD_NAME, QString("%1 %2").arg(tr("Search"), tr("Search name"))); + ui->filterLineEdit->addFilter(QIcon(), tr("ID"), RsIdentityListModel::COLUMN_THREAD_ID, tr("Search ID")); /* Set initial section sizes */ - QHeaderView * circlesheader = ui->treeWidget_membership->header () ; - circlesheader->resizeSection (CIRCLEGROUP_CIRCLE_COL_GROUPNAME, QFontMetricsF(ui->idTreeWidget->font()).width("Circle name")*1.5) ; - ui->treeWidget_membership->setColumnWidth(CIRCLEGROUP_CIRCLE_COL_GROUPNAME, 270); - - ui->filterLineEdit->addFilter(QIcon(), tr("ID"), RSID_COL_KEYID, tr("Search ID")); + QHeaderView * circlesheader = ui->treeWidget_membership->header () ; + circlesheader->resizeSection (CIRCLEGROUP_CIRCLE_COL_GROUPNAME, QFontMetricsF(ui->idTreeWidget->font()).width("Circle name")*1.5) ; + ui->treeWidget_membership->setColumnWidth(CIRCLEGROUP_CIRCLE_COL_GROUPNAME, 270); /* Setup tree */ - ui->idTreeWidget->sortByColumn(RSID_COL_NICKNAME, Qt::AscendingOrder); + ui->idTreeWidget->sortByColumn(RsIdentityListModel::COLUMN_THREAD_NAME, Qt::AscendingOrder); - ui->idTreeWidget->enableColumnCustomize(true); - ui->idTreeWidget->setColumnCustomizable(RSID_COL_NICKNAME, false); - - ui->idTreeWidget->setColumnHidden(RSID_COL_IDTYPE, true); - ui->idTreeWidget->setColumnHidden(RSID_COL_KEYID, true); - - /* Set initial column width */ - int fontWidth = QFontMetricsF(ui->idTreeWidget->font()).width("W"); - ui->idTreeWidget->setColumnWidth(RSID_COL_NICKNAME, 14 * fontWidth); - ui->idTreeWidget->setColumnWidth(RSID_COL_KEYID, 20 * fontWidth); - ui->idTreeWidget->setColumnWidth(RSID_COL_IDTYPE, 18 * fontWidth); - ui->idTreeWidget->setColumnWidth(RSID_COL_VOTES, 2 * fontWidth); + ui->idTreeWidget->setColumnHidden(RsIdentityListModel::COLUMN_THREAD_OWNER, true); + ui->idTreeWidget->setColumnHidden(RsIdentityListModel::COLUMN_THREAD_ID, true); ui->idTreeWidget->setItemDelegate(new RSElidedItemDelegate()); - ui->idTreeWidget->setItemDelegateForColumn( - RSID_COL_NICKNAME, - new GxsIdTreeItemDelegate()); - ui->idTreeWidget->setItemDelegateForColumn( - RSID_COL_VOTES, - new ReputationItemDelegate(RsReputationLevel(0xff))); + ui->idTreeWidget->setItemDelegateForColumn( RsIdentityListModel::COLUMN_THREAD_NAME, new GxsIdTreeItemDelegate()); + ui->idTreeWidget->setItemDelegateForColumn( RsIdentityListModel::COLUMN_THREAD_REPUTATION, new ReputationItemDelegate(RsReputationLevel(0xff))); /* Set header resize modes and initial section sizes */ QHeaderView * idheader = ui->idTreeWidget->header(); - QHeaderView_setSectionResizeModeColumn(idheader, RSID_COL_VOTES, QHeaderView::ResizeToContents); + QHeaderView_setSectionResizeModeColumn(idheader, RsIdentityListModel::COLUMN_THREAD_REPUTATION, QHeaderView::ResizeToContents); idheader->setStretchLastSection(true); mStateHelper->setActive(IDDIALOG_IDDETAILS, false); @@ -1266,40 +1222,41 @@ static QString getHumanReadableDuration(uint32_t seconds) void IdDialog::processSettings(bool load) { - Settings->beginGroup("IdDialog"); - - // state of peer tree - ui->idTreeWidget->processSettings(load); - - if (load) { - // load settings - - // filterColumn - ui->filterLineEdit->setCurrentFilter(Settings->value("filterColumn", RSID_COL_NICKNAME).toInt()); - - // state of splitter - ui->mainSplitter->restoreState(Settings->value("splitter").toByteArray()); - - //Restore expanding - allItem->setExpanded(Settings->value("ExpandAll", QVariant(true)).toBool()); - ownItem->setExpanded(Settings->value("ExpandOwn", QVariant(true)).toBool()); - contactsItem->setExpanded(Settings->value("ExpandContacts", QVariant(true)).toBool()); - } else { - // save settings - - // filterColumn - Settings->setValue("filterColumn", ui->filterLineEdit->currentFilter()); - - // state of splitter - Settings->setValue("splitter", ui->mainSplitter->saveState()); - - //save expanding - Settings->setValue("ExpandAll", allItem->isExpanded()); - Settings->setValue("ExpandContacts", contactsItem->isExpanded()); - Settings->setValue("ExpandOwn", ownItem->isExpanded()); - } - - Settings->endGroup(); +#warning TODO +// Settings->beginGroup("IdDialog"); +// +// // state of peer tree +// ui->idTreeWidget->processSettings(load); +// +// if (load) { +// // load settings +// +// // filterColumn +// ui->filterLineEdit->setCurrentFilter(Settings->value("filterColumn", RSID_COL_NICKNAME).toInt()); +// +// // state of splitter +// ui->mainSplitter->restoreState(Settings->value("splitter").toByteArray()); +// +// //Restore expanding +// allItem->setExpanded(Settings->value("ExpandAll", QVariant(true)).toBool()); +// ownItem->setExpanded(Settings->value("ExpandOwn", QVariant(true)).toBool()); +// contactsItem->setExpanded(Settings->value("ExpandContacts", QVariant(true)).toBool()); +// } else { +// // save settings +// +// // filterColumn +// Settings->setValue("filterColumn", ui->filterLineEdit->currentFilter()); +// +// // state of splitter +// Settings->setValue("splitter", ui->mainSplitter->saveState()); +// +// //save expanding +// Settings->setValue("ExpandAll", allItem->isExpanded()); +// Settings->setValue("ExpandContacts", contactsItem->isExpanded()); +// Settings->setValue("ExpandOwn", ownItem->isExpanded()); +// } +// +// Settings->endGroup(); } void IdDialog::filterChanged(const QString& /*text*/) @@ -2076,6 +2033,28 @@ void IdDialog::updateDisplay(bool complete) } } +std::list IdDialog::getSelectedIdentities() const +{ + QModelIndexList selectedIndexes = ui->idTreeWidget->selectionModel()->selectedIndexes(); + std::list res; + + for(auto indx:selectedIndexes) + if(indx.column() == RsIdentityListModel::COLUMN_THREAD_NAME) // this removes duplicates + res.push_back(mIdListModel->getIdentity(indx)); + + return res; +} + +RsGxsId IdDialog::getSelectedIdentity() const +{ + auto lst = getSelectedIdentities(); + + if(lst.size() != 1) + return RsGxsId(); + else + return lst.front(); +} + void IdDialog::addIdentity() { IdEditDialog dlg(this); @@ -2085,45 +2064,25 @@ void IdDialog::addIdentity() void IdDialog::removeIdentity() { - QTreeWidgetItem *item = ui->idTreeWidget->currentItem(); - if (!item) - { -#ifdef ID_DEBUG - std::cerr << "IdDialog::editIdentity() Invalid item"; - std::cerr << std::endl; -#endif - return; - } + RsGxsId id = getSelectedIdentity(); + + if(id.isNull()) + return; if ((QMessageBox::question(this, tr("Really delete?"), tr("Do you really want to delete this identity?\nThis cannot be undone."), QMessageBox::Yes|QMessageBox::No, QMessageBox::No))== QMessageBox::Yes) - { - std::string keyId = item->text(RSID_COL_KEYID).toStdString(); - RsGxsId kid(keyId); - - rsIdentity->deleteIdentity(kid); - } + rsIdentity->deleteIdentity(id); } void IdDialog::editIdentity() { - QTreeWidgetItem *item = ui->idTreeWidget->currentItem(); - if (!item) - { -#ifdef ID_DEBUG - std::cerr << "IdDialog::editIdentity() Invalid item"; - std::cerr << std::endl; -#endif - return; - } + RsGxsId id = getSelectedIdentity(); - RsGxsGroupId keyId = RsGxsGroupId(item->text(RSID_COL_KEYID).toStdString()); - if (keyId.isNull()) { - return; - } + if(id.isNull()) + return; - IdEditDialog dlg(this); - dlg.setupExistingId(keyId); - dlg.exec(); + IdEditDialog dlg(this); + dlg.setupExistingId(RsGxsGroupId(id)); + dlg.exec(); } void IdDialog::filterIds() @@ -2131,7 +2090,18 @@ void IdDialog::filterIds() int filterColumn = ui->filterLineEdit->currentFilter(); QString text = ui->filterLineEdit->text(); - ui->idTreeWidget->filterItems(filterColumn, text); + RsIdentityListModel::FilterType ft; + + switch(filterColumn) + { + case RsIdentityListModel::COLUMN_THREAD_ID: ft = RsIdentityListModel::FILTER_TYPE_ID; + break; + default: + case RsIdentityListModel::COLUMN_THREAD_NAME: ft = RsIdentityListModel::FILTER_TYPE_NAME; + break; + + } + mIdListModel->setFilter(ft,{ text }); } void IdDialog::IdListCustomPopupMenu( QPoint ) diff --git a/retroshare-gui/src/gui/Identity/IdDialog.h b/retroshare-gui/src/gui/Identity/IdDialog.h index 403b3a437..e8d0c52df 100644 --- a/retroshare-gui/src/gui/Identity/IdDialog.h +++ b/retroshare-gui/src/gui/Identity/IdDialog.h @@ -35,6 +35,7 @@ class IdDialog; class UIStateHelper; class QTreeWidgetItem; +class RsIdentityListModel; class IdDialog : public MainPage { @@ -134,9 +135,6 @@ private: private: UIStateHelper *mStateHelper; - QTreeWidgetItem *contactsItem; - QTreeWidgetItem *allItem; - QTreeWidgetItem *ownItem; QTreeWidgetItem *mExternalBelongingCircleItem; QTreeWidgetItem *mExternalOtherCircleItem; QTreeWidgetItem *mMyCircleItem; @@ -145,10 +143,15 @@ private: void saveExpandedCircleItems(std::vector &expanded_root_items, std::set& expanded_circle_items) const; void restoreExpandedCircleItems(const std::vector& expanded_root_items,const std::set& expanded_circle_items); - RsGxsGroupId mId; + RsGxsId getSelectedIdentity() const; + std::list getSelectedIdentities() const; + + RsGxsGroupId mId; RsGxsGroupId mIdToNavigate; int filter; + RsIdentityListModel *mIdListModel; + void handleEvent_main_thread(std::shared_ptr event); RsEventsHandlerId_t mEventHandlerId_identity; RsEventsHandlerId_t mEventHandlerId_circles; diff --git a/retroshare-gui/src/gui/Identity/IdDialog.ui b/retroshare-gui/src/gui/Identity/IdDialog.ui index 69d1cd8fd..faab8a48b 100644 --- a/retroshare-gui/src/gui/Identity/IdDialog.ui +++ b/retroshare-gui/src/gui/Identity/IdDialog.ui @@ -91,7 +91,7 @@ - 12 + 12 75 true @@ -211,7 +211,7 @@ - + 0 @@ -236,39 +236,6 @@ true - - false - - - - Persons - - - - - Identity ID - - - - - Owned by - - - - - - - - Votes - - - AlignLeading|AlignVCenter - - - - :/icons/flag-green.png:/icons/flag-green.png - - @@ -296,8 +263,8 @@ 0 0 - 513 - 764 + 535 + 784 @@ -1080,11 +1047,6 @@ border-image: url(:/images/closepressed.png) QComboBox
gui/common/RSComboBox.h
- - RSTreeWidget - QTreeWidget -
gui/common/RSTreeWidget.h
-
ElidedLabel QLabel diff --git a/retroshare-gui/src/gui/Identity/IdentityListModel.cpp b/retroshare-gui/src/gui/Identity/IdentityListModel.cpp new file mode 100644 index 000000000..d7b5f2449 --- /dev/null +++ b/retroshare-gui/src/gui/Identity/IdentityListModel.cpp @@ -0,0 +1,814 @@ +/******************************************************************************* + * retroshare-gui/src/gui/msgs/RsFriendListModel.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 +#include + +#include "gui/common/AvatarDefs.h" +#include "util/qtthreadsutils.h" +#include "util/HandleRichText.h" +#include "util/DateTime.h" +#include "gui/gxs/GxsIdDetails.h" +#include "retroshare/rsexpr.h" + +#include "IdentityListModel.h" + +//#define DEBUG_MODEL +//#define DEBUG_MODEL_INDEX + +std::ostream& operator<<(std::ostream& o, const QModelIndex& i);// defined elsewhere + +static const uint16_t UNDEFINED_GROUP_INDEX_VALUE = (sizeof(uintptr_t)==4)?0x1ff:0xffff; // max value for 9 bits +static const uint16_t UNDEFINED_NODE_INDEX_VALUE = (sizeof(uintptr_t)==4)?0x1ff:0xffff; // max value for 9 bits +static const uint16_t UNDEFINED_PROFILE_INDEX_VALUE = (sizeof(uintptr_t)==4)?0xfff:0xffff; // max value for 12 bits + +const QString RsIdentityListModel::FilterString("filtered"); + +const uint32_t MAX_INTERNAL_DATA_UPDATE_DELAY = 300 ; // re-update the internal data every 5 mins. Should properly cover sleep/wake-up changes. +const uint32_t MAX_NODE_UPDATE_DELAY = 10 ; // re-update the internal data every 5 mins. Should properly cover sleep/wake-up changes. + +static const uint32_t NODE_DETAILS_UPDATE_DELAY = 5; // update each node every 5 secs. + +RsIdentityListModel::RsIdentityListModel(QObject *parent) + : QAbstractItemModel(parent) + , mLastInternalDataUpdate(0), mLastNodeUpdate(0) +{ + mFilterStrings.clear(); +} + +RsIdentityListModel::EntryIndex::EntryIndex() + : type(ENTRY_TYPE_UNKNOWN),category_index(UNDEFINED_GROUP_INDEX_VALUE),identity_index(UNDEFINED_NODE_INDEX_VALUE) +{ +} + +// The index encodes the whole hierarchy of parents. This allows to very efficiently compute indices of the parent of an index. +// +// On 32 bits and 64 bits architectures the format is the following: +// +// 0x [2 bits] [30 bits] +// | | +// | | +// | | +// | +----------------------- identity index +// +-------------------------------- category +// +// Only valid indexes a 0x00->UNDEFINED_INDEX_VALUE-1. + +bool RsIdentityListModel::convertIndexToInternalId(const EntryIndex& e,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 = (((uint32_t)e.type) << 30) + ((uint32_t)e.identity_index); + return true; +} +bool RsIdentityListModel::convertInternalIdToIndex(quintptr ref,EntryIndex& e) +{ + if(ref == 0) + return false ; + + e.category_index = (ref >> 30) & 0x3;// 2 bits + e.identity_index = (ref >> 0) & 0x3fffffff;// 30 bits + + return true; +} + +static QIcon createAvatar(const QPixmap &avatar, const QPixmap &overlay) +{ + int avatarWidth = avatar.width(); + int avatarHeight = avatar.height(); + + QPixmap pixmap(avatar); + + int overlaySize = (avatarWidth > avatarHeight) ? (avatarWidth/2.5) : (avatarHeight/2.5); + int overlayX = avatarWidth - overlaySize; + int overlayY = avatarHeight - overlaySize; + + QPainter painter(&pixmap); + painter.drawPixmap(overlayX, overlayY, overlaySize, overlaySize, overlay); + + QIcon icon; + icon.addPixmap(pixmap); + return icon; +} + +void RsIdentityListModel::preMods() +{ + emit layoutAboutToBeChanged(); +} +void RsIdentityListModel::postMods() +{ + emit dataChanged(createIndex(0,0,(void*)NULL), createIndex(rowCount()-1,columnCount()-1,(void*)NULL)); + emit layoutChanged(); +} + +int RsIdentityListModel::rowCount(const QModelIndex& parent) const +{ + if(parent.column() >= COLUMN_THREAD_NB_COLUMNS) + return 0; + + if(parent.internalId() == 0) + return mTopLevel.size(); + + EntryIndex index; + if(!convertInternalIdToIndex(parent.internalId(),index)) + return 0; + + if(index.type == ENTRY_TYPE_CATEGORY) + return mCategories[index.category_index].child_identity_indices.size(); + else + return 0; +} + +int RsIdentityListModel::columnCount(const QModelIndex &/*parent*/) const +{ + return COLUMN_THREAD_NB_COLUMNS ; +} + +bool RsIdentityListModel::hasChildren(const QModelIndex &parent) const +{ + if(!parent.isValid()) + return true; + + EntryIndex parent_index ; + convertInternalIdToIndex(parent.internalId(),parent_index); + + if(parent_index.type == ENTRY_TYPE_IDENTITY) + return false; + + if(parent_index.type == ENTRY_TYPE_CATEGORY) + return !mCategories[parent_index.category_index].child_identity_indices.empty(); + + return false; +} + +RsIdentityListModel::EntryIndex RsIdentityListModel::EntryIndex::parent() const +{ + EntryIndex i(*this); + + switch(type) + { + case ENTRY_TYPE_CATEGORY: return EntryIndex(); + + case ENTRY_TYPE_IDENTITY: i.type = ENTRY_TYPE_CATEGORY; + i.identity_index = UNDEFINED_NODE_INDEX_VALUE; + break; + case ENTRY_TYPE_UNKNOWN: + //Can be when request root index. + break; + } + + return i; +} + +RsIdentityListModel::EntryIndex RsIdentityListModel::EntryIndex::child(int row,const std::vector& top_level) const +{ + EntryIndex i(*this); + + switch(type) + { + case ENTRY_TYPE_UNKNOWN: + i = top_level[row]; + break; + + case ENTRY_TYPE_CATEGORY: i.type = ENTRY_TYPE_IDENTITY; + i.identity_index = row; + break; + + case ENTRY_TYPE_IDENTITY: i = EntryIndex(); + break; + } + + return i; + +} +uint32_t RsIdentityListModel::EntryIndex::parentRow(int /* nb_groups */) const +{ + switch(type) + { + default: + case ENTRY_TYPE_UNKNOWN : return 0; + case ENTRY_TYPE_CATEGORY : return category_index; + case ENTRY_TYPE_IDENTITY : return identity_index; + } +} + +QModelIndex RsIdentityListModel::index(int row, int column, const QModelIndex& parent) const +{ + if(row < 0 || column < 0 || column >= columnCount(parent) || row >= rowCount(parent)) + return QModelIndex(); + + if(parent.internalId() == 0) + { + quintptr ref ; + + convertIndexToInternalId(mTopLevel[row],ref); + return createIndex(row,column,ref) ; + } + + EntryIndex parent_index ; + convertInternalIdToIndex(parent.internalId(),parent_index); +#ifdef DEBUG_MODEL_INDEX + RsDbg() << "Index row=" << row << " col=" << column << " parent=" << parent << std::endl; +#endif + + quintptr ref; + EntryIndex new_index = parent_index.child(row,mTopLevel); + convertIndexToInternalId(new_index,ref); + +#ifdef DEBUG_MODEL_INDEX + RsDbg() << " returning " << createIndex(row,column,ref) << std::endl; +#endif + + return createIndex(row,column,ref); +} + +QModelIndex RsIdentityListModel::parent(const QModelIndex& index) const +{ + if(!index.isValid()) + return QModelIndex(); + + EntryIndex I ; + convertInternalIdToIndex(index.internalId(),I); + + EntryIndex p = I.parent(); + + if(p.type == ENTRY_TYPE_UNKNOWN) + return QModelIndex(); + + quintptr i; + convertIndexToInternalId(p,i); + + return createIndex(I.parentRow(mCategories.size()),0,i); +} + +Qt::ItemFlags RsIdentityListModel::flags(const QModelIndex& index) const +{ + if (!index.isValid()) + return Qt::ItemFlags(); + + return QAbstractItemModel::flags(index); +} + +QVariant RsIdentityListModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const +{ + if(role == Qt::DisplayRole) + switch(section) + { + case COLUMN_THREAD_NAME: return tr("Name"); + case COLUMN_THREAD_ID: return tr("Id"); + case COLUMN_THREAD_REPUTATION: return tr("Reputation"); + case COLUMN_THREAD_OWNER: return tr("Owner"); + default: + return QVariant(); + } + + return QVariant(); +} + +QVariant RsIdentityListModel::data(const QModelIndex &index, int role) const +{ +#ifdef DEBUG_MESSAGE_MODEL + std::cerr << "calling data(" << index << ") role=" << role << std::endl; +#endif + + if(!index.isValid()) + return QVariant(); + + quintptr ref = (index.isValid())?index.internalId():0 ; + +#ifdef DEBUG_MESSAGE_MODEL + std::cerr << "data(" << index << ")" ; +#endif + + if(!ref) + { +#ifdef DEBUG_MESSAGE_MODEL + std::cerr << " [empty]" << std::endl; +#endif + return QVariant() ; + } + + EntryIndex entry; + + if(!convertInternalIdToIndex(ref,entry)) + { +#ifdef DEBUG_MESSAGE_MODEL + std::cerr << "Bad pointer: " << (void*)ref << std::endl; +#endif + return QVariant() ; + } + + switch(role) + { + case Qt::SizeHintRole: return sizeHintRole(entry,index.column()) ; + case Qt::DisplayRole: return displayRole(entry,index.column()) ; + case Qt::FontRole: return fontRole(entry,index.column()) ; + case Qt::DecorationRole: return decorationRole(entry,index.column()) ; + + case FilterRole: return filterRole(entry,index.column()) ; + case SortRole: return sortRole(entry,index.column()) ; + + default: + return QVariant(); + } +} + +bool RsIdentityListModel::passesFilter(const EntryIndex& e,int /*column*/) const +{ + QString s ; + bool passes_strings = true ; + + if(e.type == ENTRY_TYPE_IDENTITY && !mFilterStrings.empty()) + { + switch(mFilterType) + { + case FILTER_TYPE_ID: s = displayRole(e,COLUMN_THREAD_ID).toString(); + break; + + case FILTER_TYPE_NAME: s = displayRole(e,COLUMN_THREAD_NAME).toString(); + if(s.isNull()) + passes_strings = false; + break; + case FILTER_TYPE_NONE: + RS_ERR("None Type for Filter."); + }; + } + + if(!s.isNull()) + for(auto iter(mFilterStrings.begin()); iter != mFilterStrings.end(); ++iter) + passes_strings = passes_strings && s.contains(*iter,Qt::CaseInsensitive); + + return passes_strings; +} + +QVariant RsIdentityListModel::filterRole(const EntryIndex& e,int column) const +{ + if(passesFilter(e,column)) + return QVariant(FilterString); + + return QVariant(QString()); +} + +uint32_t RsIdentityListModel::updateFilterStatus(ForumModelIndex /*i*/,int /*column*/,const QStringList& /*strings*/) +{ + return 0; +} + + +void RsIdentityListModel::setFilter(FilterType filter_type, const QStringList& strings) +{ +#ifdef DEBUG_MODEL + 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; +#endif + + preMods(); + + mFilterType = filter_type; + mFilterStrings = strings; + + postMods(); +} + +QVariant RsIdentityListModel::toolTipRole(const EntryIndex& /*fmpe*/,int /*column*/) const +{ + return QVariant(); +} + +QVariant RsIdentityListModel::sizeHintRole(const EntryIndex& e,int col) const +{ + float x_factor = QFontMetricsF(QApplication::font()).height()/14.0f ; + float y_factor = QFontMetricsF(QApplication::font()).height()/14.0f ; + + if(e.type == ENTRY_TYPE_IDENTITY) + y_factor *= 3.0; + + if(e.type == ENTRY_TYPE_CATEGORY) + y_factor *= 1.5; + + switch(col) + { + default: + case COLUMN_THREAD_NAME: return QVariant( QSize(x_factor * 70 , y_factor*14*1.1f )); + case COLUMN_THREAD_ID: return QVariant( QSize(x_factor * 175, y_factor*14*1.1f )); + case COLUMN_THREAD_REPUTATION: return QVariant( QSize(x_factor * 20 , y_factor*14*1.1f )); + case COLUMN_THREAD_OWNER: return QVariant( QSize(x_factor * 70 , y_factor*14*1.1f )); + } +} + +QVariant RsIdentityListModel::sortRole(const EntryIndex& entry,int column) const +{ + switch(column) + { +#warning TODO +// case COLUMN_THREAD_LAST_CONTACT: +// { +// switch(entry.type) +// { +// case ENTRY_TYPE_PROFILE: +// { +// const HierarchicalProfileInformation *prof = getProfileInfo(entry); +// +// if(!prof) +// return QVariant(); +// +// uint32_t last_contact = 0; +// +// for(uint32_t i=0;ichild_node_indices.size();++i) +// last_contact = std::max(last_contact, mLocations[prof->child_node_indices[i]].node_info.lastConnect); +// +// return QVariant(last_contact); +// } +// break; +// default: +// return QVariant(); +// } +// } +// break; + + default: + return displayRole(entry,column); + } +} + +QVariant RsIdentityListModel::fontRole(const EntryIndex& e, int col) const +{ +#ifdef DEBUG_MODEL_INDEX + std::cerr << " font role " << e.type << ", (" << (int)e.group_index << ","<< (int)e.profile_index << ","<< (int)e.node_index << ") col="<< col<<": " << std::endl; +#endif + + int status = onlineRole(e,col).toInt(); + + switch (status) + { + case RS_STATUS_INACTIVE: + { + QFont font ; + QTreeView* myParent = dynamic_cast(QAbstractItemModel::parent()); + if (myParent) + font = myParent->font(); + + font.setBold(true); + + return QVariant(font); + } + default: + return QVariant(); + } +} + +QVariant RsIdentityListModel::displayRole(const EntryIndex& e, int col) const +{ +#ifdef DEBUG_MODEL_INDEX + std::cerr << " Display role " << e.type << ", (" << (int)e.group_index << ","<< (int)e.profile_index << ","<< (int)e.node_index << ") col="<< col<<": "; +#endif + + switch(e.type) + { + case ENTRY_TYPE_CATEGORY: + { + const HierarchicalCategoryInformation *cat = getCategoryInfo(e); + + if(!cat) + return QVariant(); + + switch(col) + { + case COLUMN_THREAD_NAME: +#ifdef DEBUG_MODEL_INDEX + std::cerr << group->group_info.name.c_str() ; +#endif + + if(!cat->child_identity_indices.empty()) + return QVariant(cat->category_name+" (" + QString::number(cat->child_identity_indices.size()) + ")"); + else + return QVariant(cat->category_name); + + default: + return QVariant(); + } + } + break; + + case ENTRY_TYPE_IDENTITY: + { + const HierarchicalIdentityInformation *idinfo = getIdentityInfo(e); + + if(!idinfo) + return QVariant(); + + RsIdentityDetails det; + + if(!rsIdentity->getIdDetails(idinfo->id,det)) + return QVariant(); + +#ifdef DEBUG_MODEL_INDEX + std::cerr << profile->profile_info.name.c_str() ; +#endif + switch(col) + { + case COLUMN_THREAD_NAME: return QVariant(QString::fromUtf8(det.mNickname.c_str())); + case COLUMN_THREAD_ID: return QVariant(QString::fromStdString(det.mId.toStdString()) ); + case COLUMN_THREAD_OWNER: return QVariant(QString::fromStdString(det.mPgpId.toStdString()) ); + case COLUMN_THREAD_REPUTATION: return QVariant(QString::number((uint8_t)det.mReputation.mOverallReputationLevel)); + default: + return QVariant(); + } + } + break; + + default: //ENTRY_TYPE + return QVariant(); + } +} + +// This function makes sure that the internal data gets updated. They are situations where the otification system cannot +// send the information about changes, such as when the computer is put on sleep. + +void RsIdentityListModel::checkInternalData(bool force) +{ + rstime_t now = time(NULL); + + if( (mLastInternalDataUpdate + MAX_INTERNAL_DATA_UPDATE_DELAY < now) || force) + updateInternalData(); +} + +const RsIdentityListModel::HierarchicalCategoryInformation *RsIdentityListModel::getCategoryInfo(const EntryIndex& e) const +{ + if(e.category_index >= mCategories.size()) + return NULL ; + else + return &mCategories[e.category_index]; +} + +const RsIdentityListModel::HierarchicalIdentityInformation *RsIdentityListModel::getIdentityInfo(const EntryIndex& e) const +{ + // First look into the relevant group, then for the correct profile in this group. + + if(e.type != ENTRY_TYPE_IDENTITY) + return NULL ; + + if(e.category_index >= mCategories.size()) + return NULL ; + + if(e.identity_index < mCategories[e.category_index].child_identity_indices.size()) + return &mIdentities[mCategories[e.category_index].child_identity_indices[e.identity_index]]; + else + return &mIdentities[e.identity_index]; +} + +QVariant RsIdentityListModel::decorationRole(const EntryIndex& entry,int col) const +{ + if(col > 0) + return QVariant(); + + switch(entry.type) + { + + case ENTRY_TYPE_CATEGORY: + return QVariant(); + + case ENTRY_TYPE_IDENTITY: + { + const HierarchicalIdentityInformation *hn = getIdentityInfo(entry); + + if(!hn) + return QVariant(); + + QPixmap sslAvatar; + AvatarDefs::getAvatarFromGxsId(hn->id, sslAvatar); + + return QVariant(QIcon(sslAvatar)); + } + default: return QVariant(); + } +} + +void RsIdentityListModel::clear() +{ + preMods(); + + mIdentities.clear(); + mTopLevel.clear(); + + mCategories.clear(); + mCategories.resize(3); + mCategories[0].category_name = tr("My own identities"); + mCategories[1].category_name = tr("My contacts"); + mCategories[2].category_name = tr("All"); + + postMods(); + + emit friendListChanged(); +} + +void RsIdentityListModel::debug_dump() const +{ +// std::cerr << "==== FriendListModel Debug dump ====" << std::endl; +// +// for(uint32_t j=0;jid; + else + return RsGxsId(); +} + +RsIdentityListModel::EntryType RsIdentityListModel::getType(const QModelIndex& i) const +{ + if(!i.isValid()) + return ENTRY_TYPE_UNKNOWN; + + EntryIndex e; + if(!convertInternalIdToIndex(i.internalId(),e)) + return ENTRY_TYPE_UNKNOWN; + + return e.type; +} + +void RsIdentityListModel::setIdentities(const std::list& identities_meta) +{ + preMods(); + beginResetModel(); + clear(); + + for(auto id:identities_meta) + { + HierarchicalIdentityInformation idinfo; + idinfo.id = RsGxsId(id.mGroupId); + + if(rsIdentity->isOwnId(idinfo.id)) + mCategories[CATEGORY_OWN].child_identity_indices.push_back(mIdentities.size()); + else if(rsIdentity->isARegularContact(RsGxsId(id.mGroupId))) + mCategories[CATEGORY_CTS].child_identity_indices.push_back(mIdentities.size()); + else + mCategories[CATEGORY_ALL].child_identity_indices.push_back(mIdentities.size()); + + mIdentities.push_back(idinfo); + } + + if (mCategories.size()>0) + { + beginInsertRows(QModelIndex(),0,mCategories.size()-1); + endInsertRows(); + } + + endResetModel(); + postMods(); + + mLastInternalDataUpdate = time(NULL); + +} + +void RsIdentityListModel::updateInternalData() +{ + RsThread::async([this]() + { + // 1 - get message data from p3GxsForums + + std::list *ids = new std::list(); + + if(!rsIdentity->getIdentitiesSummaries(*ids)) + { + std::cerr << __PRETTY_FUNCTION__ << " failed to retrieve identity metadata." << std::endl; + return; + } + + // 3 - update the model in the UI thread. + + RsQThreadUtils::postToObject( [ids,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! + */ + + setIdentities(*ids) ; + + delete ids; + + + }, this ); + + }); + +} + +void RsIdentityListModel::collapseItem(const QModelIndex& index) +{ + if(getType(index) != ENTRY_TYPE_CATEGORY) + return; + + EntryIndex entry; + + if(!convertInternalIdToIndex(index.internalId(),entry)) + return; + + mExpandedCategories[entry.category_index] = false; + + // apparently we cannot be subtle here. + emit dataChanged(createIndex(0,0,(void*)NULL), createIndex(mTopLevel.size()-1,columnCount()-1,(void*)NULL)); +} + +void RsIdentityListModel::expandItem(const QModelIndex& index) +{ + if(getType(index) != ENTRY_TYPE_CATEGORY) + return; + + EntryIndex entry; + + if(!convertInternalIdToIndex(index.internalId(),entry)) + return; + + mExpandedCategories[entry.category_index] = true; + + // apparently we cannot be subtle here. + emit dataChanged(createIndex(0,0,(void*)NULL), createIndex(mTopLevel.size()-1,columnCount()-1,(void*)NULL)); +} + +bool RsIdentityListModel::isCategoryExpanded(const EntryIndex& e) const +{ + return true; +#warning TODO +// if(e.type != ENTRY_TYPE_CATEGORY) +// return false; +// +// EntryIndex entry; +// +// if(!convertInternalIdToIndex(e.internalId(),entry)) +// return false; +// +// return mExpandedCategories[entry.category_index]; +} + diff --git a/retroshare-gui/src/gui/Identity/IdentityListModel.h b/retroshare-gui/src/gui/Identity/IdentityListModel.h new file mode 100644 index 000000000..b6e410ae2 --- /dev/null +++ b/retroshare-gui/src/gui/Identity/IdentityListModel.h @@ -0,0 +1,219 @@ +/******************************************************************************* + * retroshare-gui/src/gui/msgs/RsFriendListModel.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/rsstatus.h" +#include "retroshare/rsmsgs.h" +#include "retroshare/rspeers.h" +#include "retroshare/rsidentity.h" + +typedef uint32_t ForumModelIndex; + +// This class is the item model used by Qt to display the information + +class RsIdentityListModel : public QAbstractItemModel +{ + Q_OBJECT + +public: + explicit RsIdentityListModel(QObject *parent = NULL); + ~RsIdentityListModel(){} + + enum Columns { + COLUMN_THREAD_NAME = 0x00, + COLUMN_THREAD_ID = 0x01, + COLUMN_THREAD_OWNER = 0x02, + COLUMN_THREAD_REPUTATION = 0x03, + COLUMN_THREAD_NB_COLUMNS = 0x04 + }; + + enum Roles{ SortRole = Qt::UserRole+1, + StatusRole = Qt::UserRole+2, + UnreadRole = Qt::UserRole+3, + FilterRole = Qt::UserRole+4, + }; + + enum FilterType{ FILTER_TYPE_NONE = 0x00, + FILTER_TYPE_ID = 0x01, + FILTER_TYPE_NAME = 0x02 + }; + + enum EntryType{ ENTRY_TYPE_UNKNOWN = 0x00, + ENTRY_TYPE_CATEGORY = 0x01, + ENTRY_TYPE_IDENTITY = 0x02 + }; + + static const int CATEGORY_OWN = 0x00; + static const int CATEGORY_CTS = 0x01; + static const int CATEGORY_ALL = 0x02; + + struct HierarchicalCategoryInformation + { + QString category_name; + std::vector child_identity_indices; // index in the array of hierarchical profiles + }; + struct HierarchicalIdentityInformation + { + RsGxsId id; + }; + + // This structure encodes the position of a node in the hierarchy. The type tells which of the index fields are valid. + + struct EntryIndex + { + public: + EntryIndex(); + + EntryType type; // type of the entry (group,profile,location) + + // Indices w.r.t. parent. The set of indices entirely determines the position of the entry in the hierarchy. + // An index of 0xff means "undefined" + + uint16_t category_index; // index of the category in the mCategory array + uint16_t identity_index; // index of the identity in its own category + + EntryIndex parent() const; + EntryIndex child(int row,const std::vector& top_level) const; + uint32_t parentRow(int) const; + }; + + QModelIndex root() const{ return createIndex(0,0,(void*)NULL) ;} + QModelIndex getIndexOfGroup(const RsNodeGroupId& mid) const; + + static const QString FilterString ; + + // This method will asynchroneously update the data + + EntryType getType(const QModelIndex&) const; + + RsGxsId getIdentity(const QModelIndex&) const; + + void setFilter(FilterType filter_type, const QStringList& strings) ; + + void expandItem(const QModelIndex&) ; + void collapseItem(const QModelIndex&) ; + + // Overloaded methods from QAbstractItemModel + + 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; + + void clear() ; + + /* Color definitions (for standard see default.qss) */ + QColor mTextColorGroup; + QColor mTextColorStatus[RS_STATUS_COUNT]; + +private: + const HierarchicalCategoryInformation *getCategoryInfo (const EntryIndex&) const; + const HierarchicalIdentityInformation *getIdentityInfo(const EntryIndex&) const; + + bool isCategoryExpanded(const EntryIndex& e) const; + void checkIdentity(HierarchicalIdentityInformation& node); + + std::map::const_iterator checkProfileIndex(const RsPgpId& pgp_id, + std::map& pgp_indices, + std::vector& mProfiles, + bool create); + + std::map::const_iterator createInvalidatedProfile(const RsPgpId& pgp_id, + const RsPgpFingerprint& fpr, + std::map& pgp_indices, + std::vector& mProfiles); + + QVariant sizeHintRole (const EntryIndex& e, int col) const; + QVariant displayRole (const EntryIndex& e, int col) const; + QVariant decorationRole(const EntryIndex& e, int col) const; + QVariant toolTipRole (const EntryIndex& e, int col) const; + QVariant statusRole (const EntryIndex& e, int col) const; + QVariant sortRole (const EntryIndex& e, int col) const; + QVariant fontRole (const EntryIndex& e, int col) const; + QVariant textColorRole (const EntryIndex& e, int col) const; + QVariant onlineRole (const EntryIndex& e, int col) const; + QVariant filterRole (const EntryIndex& e, int col) const; + + /*! + * \brief debug_dump + * Dumps the hierarchy of posts in the terminal, to allow checking whether the internal representation is correct. + */ + +public slots: + void checkInternalData(bool force); + void debug_dump() const; + +signals: + void dataLoaded(); // emitted after the messages have been set. Can be used to updated the UI. + void friendListChanged(); // emitted after the messages have been set. Can be used to updated the UI. + void dataAboutToLoad(); + +private: + void updateInternalData(); + void setIdentities(const std::list& identities_meta); + bool passesFilter(const EntryIndex &e, int column) const; + + void preMods() ; + void postMods() ; + + void *getParentRef(void *ref,int& row) const; + void *getChildRef(void *ref,int row) const; + int getChildrenCount(void *ref) const; + + static bool convertIndexToInternalId(const EntryIndex& e,quintptr& ref); + static bool convertInternalIdToIndex(quintptr ref, EntryIndex& e); + + uint32_t updateFilterStatus(ForumModelIndex i,int column,const QStringList& strings); + + QStringList mFilterStrings; + FilterType mFilterType; + + rstime_t mLastInternalDataUpdate; + rstime_t mLastNodeUpdate;; + + // The 3 vectors below store thehierarchical information for groups, profiles and locations, + // meaning which is the child/parent of which. The actual group/profile/node data are also stored in the + // structure. + + mutable std::vector mCategories; + mutable std::vector mIdentities; + + // The top level list contains all nodes to display, which type depends on the option to display groups or not. + // Idices in the list may be profile indices or group indices. In the former case the profile child index refers to + // the inde in the mProfiles tab, whereas in the the later case, the child index refers to the index of the profile in the + // group it belows to. + + std::vector mTopLevel; + + // keeps track of expanded/collapsed items, so as to only show icon for collapsed profiles + + std::vector mExpandedCategories; +}; + diff --git a/retroshare-gui/src/retroshare-gui.pro b/retroshare-gui/src/retroshare-gui.pro index d73117b84..86ebbed07 100644 --- a/retroshare-gui/src/retroshare-gui.pro +++ b/retroshare-gui/src/retroshare-gui.pro @@ -1257,6 +1257,7 @@ identities { HEADERS += \ gui/Identity/IdDialog.h \ + gui/Identity/IdentityListModel.h \ gui/Identity/IdEditDialog.h \ gui/Identity/IdDetailsDialog.h \ @@ -1266,6 +1267,7 @@ identities { SOURCES += \ gui/Identity/IdDialog.cpp \ + gui/Identity/IdentityListModel.cpp \ gui/Identity/IdEditDialog.cpp \ gui/Identity/IdDetailsDialog.cpp \