diff --git a/src/mumble/UserEdit.cpp b/src/mumble/UserEdit.cpp index 86aa33ef1..90b79cf99 100644 --- a/src/mumble/UserEdit.cpp +++ b/src/mumble/UserEdit.cpp @@ -31,221 +31,111 @@ #include "mumble_pch.hpp" #include "UserEdit.h" + +#include + #include "Channel.h" #include "Global.h" #include "ServerHandler.h" #include "User.h" +#include "Mumble.pb.h" +#include "UserListModel.h" + + +UserEdit::UserEdit(const MumbleProto::UserList &userList, QWidget *parent) + : QDialog(parent) + , m_model(new UserListModel(userList, this)) + , m_filter(new UserListFilterProxyModel(this)) { -UserEdit::UserEdit(const MumbleProto::UserList &msg, QWidget *p) : QDialog(p) - , iInactiveForDaysFiltervalue(0) { setupUi(this); - qtwUserList->setFocus(); - qtwUserList->setContextMenuPolicy(Qt::CustomContextMenu); + const int userCount = userList.users_size(); + setWindowTitle(tr("Registered users: %n account(s)", "", userCount)); - int n = msg.users_size(); - setWindowTitle(tr("Registered Users: %n Account(s)", "", n)); + m_filter->setSourceModel(m_model); + qtvUserList->setModel(m_filter); + + QItemSelectionModel *selectionModel = qtvUserList->selectionModel(); + connect(selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)), + this, SLOT(onSelectionChanged(QItemSelection,QItemSelection))); + connect(selectionModel, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), + this, SLOT(onCurrentRowChanged(QModelIndex,QModelIndex))); + + qtvUserList->setFocus(); + qtvUserList->setContextMenuPolicy(Qt::CustomContextMenu); #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) - qtwUserList->header()->setSectionResizeMode(0, QHeaderView::Stretch); // user name - qtwUserList->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); // last seen - qtwUserList->header()->setSectionResizeMode(2, QHeaderView::Stretch); // on channel + qtvUserList->header()->setSectionResizeMode(UserListModel::COL_NICK, QHeaderView::Stretch); + qtvUserList->header()->setSectionResizeMode(UserListModel::COL_INACTIVEDAYS, QHeaderView::ResizeToContents); + qtvUserList->header()->setSectionResizeMode(UserListModel::COL_LASTCHANNEL, QHeaderView::Stretch); #else - qtwUserList->header()->setResizeMode(0, QHeaderView::Stretch); // user name - qtwUserList->header()->setResizeMode(1, QHeaderView::ResizeToContents); // last seen - qtwUserList->header()->setResizeMode(2, QHeaderView::Stretch); // on channel + qtvUserList->header()->setResizeMode(UserListModel::COL_NICK, QHeaderView::Stretch); + qtvUserList->header()->setResizeMode(UserListModel::COL_INACTIVEDAYS, QHeaderView::ResizeToContents); + qtvUserList->header()->setResizeMode(UserListModel::COL_LASTCHANNEL, QHeaderView::Stretch); #endif - qtwUserList->sortByColumn(0, Qt::AscendingOrder); // sort by user name - qmUsers.clear(); - for (int i = 0; i < msg.users_size(); ++i) { - const MumbleProto::UserList_User &u = msg.users(i); - UserInfo uie; - protoUserToUserInfo(u, uie); - qmUsers.insert(uie.user_id, uie); + if (m_model->isLegacy()) { + qlInactive->hide(); + qsbInactive->hide(); + qcbInactive->hide(); } - refreshUserList(); -} -void UserEdit::protoUserToUserInfo(const MumbleProto::UserList_User & u, UserInfo & uie) -{ - uie.user_id = u.user_id(); - uie.name = u8(u.name()); - if (u.has_last_channel()) { - uie.last_channel = u.last_channel(); - } - if (u.has_last_seen()) { - uie.last_active = QDateTime::fromString(u8(u.last_seen()), Qt::ISODate); - uie.last_active.setTimeSpec(Qt::UTC); - } -} - -void UserEdit::refreshUserList() { - qtwUserList->clearSelection(); - qtwUserList->clear(); - - QMapIterator i(qmUsers); - while (i.hasNext()) { - i.next(); - UserEditListItem *ueli = new UserEditListItem(i.key()); - - const QString username = i.value().name; - ueli->setText(0, username); - - QString qsLastActive; - QDateTime qdtLastActive(i.value().last_active); - int iSeenDaysAgo = 0; - if (qdtLastActive.isValid()) { - iSeenDaysAgo = qdtLastActive.daysTo(QDateTime::currentDateTime().toUTC()); - qsLastActive = tr("%1").arg(QString::number(iSeenDaysAgo)); - } - ueli->setText(1, qsLastActive); - ueli->setToolTip(1, qdtLastActive.toLocalTime().toString(Qt::ISODate)); - - boost::optional lastchanid = i.value().last_channel; - Channel *c = lastchanid ? Channel::get(*lastchanid) : NULL; - QString lastchantreestring = getChanneltreestring(c); - ueli->setText(2, lastchantreestring); - - if (lastchanid) { - showExtendedGUI(); - } else { - hideExtendedGUI(); - } - - bool bHidden = false; - bHidden = bHidden || ((iInactiveForDaysFiltervalue > 0) && (iSeenDaysAgo < iInactiveForDaysFiltervalue)); - bHidden = bHidden || (!username.contains(qlSearch->text(), Qt::CaseInsensitive) - && !lastchantreestring.contains(qlSearch->text(), Qt::CaseInsensitive)); - if (bHidden) { - delete ueli; - continue; - } - - qtwUserList->addTopLevelItem(ueli); - } -} - -QString UserEdit::getChanneltreestring(Channel* c) const -{ - QString tree = QLatin1String("-"); - if (c) { - QStringList channel_tree; - while (c->cParent != NULL) { - channel_tree.prepend(c->qsName); - c = c->cParent; - } - - //TODO: This seems unnecessary - QStringList _channel_tree; - for (QStringList::iterator it = channel_tree.begin(); it != channel_tree.end(); ++it) { - _channel_tree.append(*it); - } - - channel_tree.clear(); - channel_tree.append(_channel_tree); - - tree = QLatin1String("/ ") + channel_tree.join(QLatin1String(" / ")); - } - return tree; -} - -void UserEdit::showExtendedGUI() -{ - qtwUserList->showColumn(1); - qtwUserList->showColumn(2); - qlInactive->show(); - qsbInactive->show(); - qcbInactive->show(); -} - -void UserEdit::hideExtendedGUI() -{ - qtwUserList->hideColumn(1); - qtwUserList->hideColumn(2); - qlInactive->hide(); - qsbInactive->hide(); - qcbInactive->hide(); + qtvUserList->sortByColumn(UserListModel::COL_NICK, Qt::AscendingOrder); } void UserEdit::accept() { - QList ql = qtwUserList->findItems(QString(), Qt::MatchStartsWith); - foreach(QTreeWidgetItem * qlwi, ql) { - const QString &name = qlwi->text(0); - int id = qlwi->data(0, Qt::UserRole).toInt(); - if (qmUsers.value(id).name != name) { - qmChanged.insert(id, name); - } - } - - if (! qmChanged.isEmpty()) { - MumbleProto::UserList mpul; - QMap::const_iterator i; - for (i = qmChanged.constBegin(); i != qmChanged.constEnd(); ++i) { - MumbleProto::UserList_User *u = mpul.add_users(); - u->set_user_id(i.key()); - if (! i.value().isEmpty()) { - u->set_name(u8(i.value())); - } - } - g.sh->sendMessage(mpul); + if (m_model->isUserListDirty()) { + MumbleProto::UserList userList = m_model->getUserListUpdate(); + g.sh->sendMessage(userList); } QDialog::accept(); } +void UserEdit::on_qlSearch_textChanged(QString pattern) { + m_filter->setFilterWildcard(pattern); +} + + void UserEdit::on_qpbRename_clicked() { - int idx = qtwUserList->currentIndex().row(); - if (idx >= 0) { - QTreeWidgetItem *item = qtwUserList->currentItem(); - if (item) { - qtwUserList->editItem(item); - } - } + QModelIndex current = qtvUserList->selectionModel()->currentIndex(); + if (!current.isValid()) + return; + + QModelIndex nickIndex = current.sibling(current.row(), UserListModel::COL_NICK); + qtvUserList->edit(nickIndex); } void UserEdit::on_qpbRemove_clicked() { - while (qtwUserList->selectedItems().count() > 0) { - QTreeWidgetItem *qlwi = qtwUserList->selectedItems().takeAt(0); - int id = qlwi->data(0, Qt::UserRole).toInt(); - qmChanged.insert(id, QString()); - delete qlwi; - } + m_filter->removeRowsInSelection(qtvUserList->selectionModel()->selection()); } -void UserEdit::on_qtwUserList_customContextMenuRequested(const QPoint &point) { +void UserEdit::on_qtvUserList_customContextMenuRequested(const QPoint &point) { QMenu *menu = new QMenu(this); - QAction *action; + if (qtvUserList->selectionModel()->currentIndex().isValid()) { + QAction *renameAction = menu->addAction(tr("Rename")); + connect(renameAction, SIGNAL(triggered()), + this, SLOT(on_qpbRename_clicked())); - if (!(qtwUserList->selectedItems().count() > 1)) - { - action = menu->addAction(tr("Rename")); - connect(action, SIGNAL(triggered()), this, SLOT(renameTriggered())); menu->addSeparator(); } - action = menu->addAction(tr("Remove")); - connect(action, SIGNAL(triggered()), this, SLOT(on_qpbRemove_clicked())); + QAction *removeAction = menu->addAction(tr("Remove")); + connect(removeAction, SIGNAL(triggered()), + this, SLOT(on_qpbRemove_clicked())); - menu->exec(qtwUserList->mapToGlobal(point)); + menu->exec(qtvUserList->mapToGlobal(point)); delete menu; } -void UserEdit::renameTriggered() { - QTreeWidgetItem *item = qtwUserList->currentItem(); - if (item) { - qtwUserList->editItem(item, 0); - } +void UserEdit::onSelectionChanged(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/) { + const bool somethingSelected = !(qtvUserList->selectionModel()->selection().empty()); + qpbRemove->setEnabled(somethingSelected); } -void UserEdit::on_qlSearch_textChanged(QString) { - refreshUserList(); -} - -void UserEdit::on_qtwUserList_itemSelectionChanged() { - qpbRename->setEnabled(qtwUserList->selectedItems().count() == 1); - qpbRemove->setEnabled(qtwUserList->selectedItems().count() > 0); +void UserEdit::onCurrentRowChanged(const QModelIndex ¤t, const QModelIndex &) { + qpbRename->setEnabled(current.isValid()); } void UserEdit::on_qsbInactive_valueChanged(int) { @@ -257,39 +147,66 @@ void UserEdit::on_qcbInactive_currentIndexChanged(int) { } void UserEdit::updateInactiveDaysFilter() { - const int iTimespanUnit = qcbInactive->currentIndex(); - const int iTimespanCount = qsbInactive->value(); - int iInactiveForDays = 0; - switch (iTimespanUnit) { - case 0: - iInactiveForDays = iTimespanCount; + const int timespanUnit = qcbInactive->currentIndex(); + const int timespanCount = qsbInactive->value(); + + int minimumInactiveDays = 0; + switch (timespanUnit) { + case TU_DAYS: + minimumInactiveDays = timespanCount; break; - case 1: - iInactiveForDays = iTimespanCount * 7; + case TU_WEEKS: + minimumInactiveDays = timespanCount * 7; break; - case 2: - iInactiveForDays = iTimespanCount * 30; + case TU_MONTHS: + minimumInactiveDays = timespanCount * 30; break; - case 3: - iInactiveForDays = iTimespanCount * 365; + case TU_YEARS: + minimumInactiveDays = timespanCount * 365; break; default: break; } - iInactiveForDaysFiltervalue = iInactiveForDays; - refreshUserList(); + + m_filter->setFilterMinimumInactiveDays(minimumInactiveDays); } -UserEditListItem::UserEditListItem(const int userid) : QTreeWidgetItem() { - setFlags(flags() | Qt::ItemIsEditable); - setData(0, Qt::UserRole, userid); +UserListFilterProxyModel::UserListFilterProxyModel(QObject *parent) + : QSortFilterProxyModel(parent) + , m_minimumInactiveDays(0) { + + setFilterKeyColumn(UserListModel::COL_NICK); + setSortLocaleAware(true); + setDynamicSortFilter(true); } -bool UserEditListItem::operator<(const QTreeWidgetItem &other) const { - // Avoid duplicating the User sorting code for a little more complexity - User first, second; - first.qsName = text(0); - second.qsName = other.text(0); - return User::lessThan(&first, &second); +bool UserListFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { + if(!QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent)) { + return false; + } + + const QModelIndex inactiveDaysIdx = sourceModel()->index(source_row, + UserListModel::COL_INACTIVEDAYS, + source_parent); + + bool ok; + const int inactiveDays = inactiveDaysIdx.data().toInt(&ok); + + // If inactiveDaysIdx doesn't store an int the account hasn't been seen yet and mustn't be filtered + if (ok && inactiveDays < m_minimumInactiveDays) + return false; + + return true; } + +void UserListFilterProxyModel::setFilterMinimumInactiveDays(int minimumInactiveDays) { + m_minimumInactiveDays = minimumInactiveDays; + invalidateFilter(); +} + +void UserListFilterProxyModel::removeRowsInSelection(const QItemSelection &selection) { + QItemSelection sourceSelection = mapSelectionToSource(selection); + qobject_cast(sourceModel())->removeRowsInSelection(sourceSelection); +} + diff --git a/src/mumble/UserEdit.h b/src/mumble/UserEdit.h index 05c4acdb9..fe87f0d6c 100644 --- a/src/mumble/UserEdit.h +++ b/src/mumble/UserEdit.h @@ -33,52 +33,72 @@ #include "Message.h" #include "User.h" -#include "mumble_pch.hpp" #include "ui_UserEdit.h" +#include + +class UserListModel; +class UserListFilterProxyModel; + namespace MumbleProto { -class UserList; + class UserList; + class UserList_User; } -namespace MumbleProto { class UserList_User; } - -class UserEditListItem : public QTreeWidgetItem { - public: - UserEditListItem(const int userid); - bool operator<(const QTreeWidgetItem & other) const; -}; +/// +/// Dialog used for server-side registered user list editing. +/// class UserEdit : public QDialog, public Ui::UserEdit { - private: Q_OBJECT Q_DISABLE_COPY(UserEdit) - - protected: - QMap qmUsers; - QMap qmChanged; - - int iInactiveForDaysFiltervalue; - - void refreshUserList(); - void updateInactiveDaysFilter(); - void showExtendedGUI(); - void hideExtendedGUI(); - - void protoUserToUserInfo(const MumbleProto::UserList_User & u, UserInfo & uie); - QString getChanneltreestring(Channel* c) const; - public: - UserEdit(const MumbleProto::UserList &mpul, QWidget *p = NULL); + /// Constructs a dialog for editing the given userList. + UserEdit(const MumbleProto::UserList &userList, QWidget *parent = NULL); + public slots: void accept(); - void on_qlSearch_textChanged(QString ); - public slots: + + void on_qlSearch_textChanged(QString); void on_qpbRemove_clicked(); void on_qpbRename_clicked(); - void on_qtwUserList_customContextMenuRequested(const QPoint&); - void renameTriggered(); - void on_qtwUserList_itemSelectionChanged(); - void on_qsbInactive_valueChanged(int ); - void on_qcbInactive_currentIndexChanged(int index); + void on_qtvUserList_customContextMenuRequested(const QPoint&); + void onSelectionChanged(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/); + void onCurrentRowChanged(const QModelIndex & current, const QModelIndex &/*previous*/); + void on_qsbInactive_valueChanged(int); + void on_qcbInactive_currentIndexChanged(int); + + private: + enum TimespanUnits { TU_DAYS, TU_WEEKS, TU_MONTHS, TU_YEARS, COUNT_TU }; + + /// Polls the inactive-filter controls for their current value and updates the model filter. + void updateInactiveDaysFilter(); + + UserListModel *m_model; + UserListFilterProxyModel *m_filter; }; -#endif +/// +/// Provides filtering and sorting capabilities for UserListModel instances to UserEdit. +/// @see UserEdit +/// @see UserListModel +/// +class UserListFilterProxyModel : public QSortFilterProxyModel { + Q_OBJECT +public: + explicit UserListFilterProxyModel(QObject *parent = NULL); + + bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const; + +public slots: + /// Sets the amount of inactive days below which rows will get filterd by the proxy + void setFilterMinimumInactiveDays(int minimumInactiveDays); + /// Helper function for removing all rows involved in a given selection (must include COL_NICK). + void removeRowsInSelection(const QItemSelection& selection); + +private: + /// Every row with less inactive days will be filtered. + int m_minimumInactiveDays; +}; + + +#endif // MUMBLE_MUMBLE_USEREDIT_H_ diff --git a/src/mumble/UserEdit.ui b/src/mumble/UserEdit.ui index a69fed0bf..a279a8098 100644 --- a/src/mumble/UserEdit.ui +++ b/src/mumble/UserEdit.ui @@ -20,73 +20,28 @@ + + + + + 0 + 0 + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + Registered Users - - - - true - - - QAbstractItemView::ExtendedSelection - - - QAbstractItemView::SelectRows - - - false - - - true - - - false - - - 3 - - - false - - - - Nick - - - - - Inactive days - - - - - Last Channel - - - - - - - - - true - - - - - - - Qt::AlignCenter - - - Who are you looking for? - - - @@ -116,38 +71,21 @@ - - - - - 0 - 0 - + + + + + true + - Inactive for + - - - - - - - 0 - 0 - + + Qt::AlignCenter - - - 48 - 16777215 - - - - true - - - 9999 + + Who are you looking for? @@ -194,25 +132,63 @@ + + + + + 0 + 0 + + + + + 48 + 16777215 + + + + true + + + 9999 + + + + + + + + 0 + 0 + + + + Inactive for + + + + + + + true + + + QAbstractItemView::ExtendedSelection + + + false + + + false + + + true + + + - - - - - 0 - 0 - - - - Qt::Horizontal - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - diff --git a/src/mumble/UserListModel.cpp b/src/mumble/UserListModel.cpp new file mode 100644 index 000000000..c4cfbe33e --- /dev/null +++ b/src/mumble/UserListModel.cpp @@ -0,0 +1,314 @@ +/* Copyright (C) 2013, Stefan Hacker + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + - Neither the name of the Mumble Developers nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include + +#include "UserListModel.h" +#include "Channel.h" +#include "Message.h" + +#include +#include + +UserListModel::UserListModel(const MumbleProto::UserList& userList, QObject *parent) + : QAbstractTableModel(parent) + , m_legacyMode(false) { + + m_userList.reserve(userList.users_size()); + for (int i = 0; i < userList.users_size(); ++i) { + m_userList.append(userList.users(i)); + } + + if (!m_userList.empty()) { + const MumbleProto::UserList_User& user = m_userList.back(); + m_legacyMode = !user.has_last_seen() || !user.has_last_channel(); + } +} + +int UserListModel::rowCount(const QModelIndex &parent) const { + if (parent.isValid()) + return 0; + + return m_userList.size(); +} + +int UserListModel::columnCount(const QModelIndex &parent) const { + if (parent.isValid()) + return 0; + + if (m_legacyMode) { + // Only COL_NICK + return 1; + } + + return COUNT_COL; +} + +QVariant UserListModel::headerData(int section, Qt::Orientation orientation, int role) const { + if (orientation != Qt::Horizontal) + return QVariant(); + + if (section < 0 || section >= columnCount()) + return QVariant(); + + if (role == Qt::DisplayRole) { + switch (section) { + case COL_NICK: return tr("Nick"); + case COL_INACTIVEDAYS: return tr("Inactive days"); + case COL_LASTCHANNEL: return tr("Last channel"); + default: return QVariant(); + } + } + + return QVariant(); +} + +QVariant UserListModel::data(const QModelIndex &index, int role) const { + if (!index.isValid()) + return QVariant(); + + if (index.row() < 0 && index.row() >= m_userList.size()) + return QVariant(); + + if (index.column() >= columnCount()) + return QVariant(); + + const MumbleProto::UserList_User& user = m_userList[index.row()]; + + if (role == Qt::DisplayRole) { + switch (index.column()) { + case COL_NICK: return u8(user.name()); + case COL_INACTIVEDAYS: return lastSeenToTodayDayCount(user.last_seen()); + case COL_LASTCHANNEL: return pathForChannelId(user.last_channel()); + default: return QVariant(); + } + } else if (role == Qt::ToolTipRole) { + switch (index.column()) { + case COL_INACTIVEDAYS: return tr("Last seen: %1").arg(user.last_seen().empty() ? + tr("Never") + : u8(user.last_seen())); + case COL_LASTCHANNEL: return tr("Channel id: %1").arg(user.last_channel()); + default: return QVariant(); + } + } else if (role == Qt::UserRole) { + switch (index.column()) { + case COL_INACTIVEDAYS: return isoUTCToDateTime(user.last_seen()); + case COL_LASTCHANNEL: return user.last_channel(); + default: return QVariant(); + } + } else if (role == Qt::EditRole) { + if (index.column() == COL_NICK) { + return u8(user.name()); + } + } + + return QVariant(); +} + +bool UserListModel::setData(const QModelIndex &index, const QVariant &value, int role) { + if (!index.isValid()) + return false; + + if (index.column() != COL_NICK || role != Qt::EditRole) + return false; + + if (index.row() < 0 || index.row() >= m_userList.size()) + return false; + + const std::string newNick = u8(value.toString()); + if (newNick.empty()) { + // Empty nick is not valid + return false; + } + + MumbleProto::UserList_User& user = m_userList[index.row()]; + if (newNick != user.name()) { + foreach (const MumbleProto::UserList_User& otherUser, m_userList) { + if (otherUser.name() == newNick) { + // Duplicate is not valid + return false; + } + } + + user.set_name(newNick); + m_changes[user.user_id()] = user; + + emit dataChanged(index, index); + } + + return true; +} + +Qt::ItemFlags UserListModel::flags(const QModelIndex &index) const { + const Qt::ItemFlags original = QAbstractTableModel::flags(index); + + if (index.column() == COL_NICK) { + return original | Qt::ItemIsEditable; + } + + return original; +} + +bool UserListModel::removeRows(int row, int count, const QModelIndex &parent) { + if (row + count > m_userList.size()) + return false; + + beginRemoveRows(parent, row, row + count - 1); + + ModelUserList::Iterator startIt = m_userList.begin() + row; + ModelUserList::Iterator endIt = startIt + count; + + for (ModelUserList::Iterator it = startIt; + it != endIt; + ++it) { + it->clear_name(); + m_changes[it->user_id()] = *it; + } + + m_userList.erase(startIt, endIt); + + endRemoveRows(); + return true; +} + +void UserListModel::removeRowsInSelection(const QItemSelection &selection) { + QModelIndexList indices = selection.indexes(); + + std::vector rows; + rows.reserve(indices.size()); + + foreach (const QModelIndex& idx, indices) { + if (idx.column() != COL_NICK) + continue; + + rows.push_back(idx.row()); + } + + // Make sure to presort the rows so we work from back (high) to front (low). + // This prevents the row numbers from becoming invalid after removing a group. + // The basic idea is to take a number of sorted rows (e.g. 10,9,5,3,2,1) and + // delete them with the minimum number of removeRows calls. This means grouping + // adjacent rows (e.g. (10,9),(5),(3,2,1)) and using a removeRows call for each group. + std::sort(rows.begin(), rows.end(), std::greater()); + + int nextRow = -2; + int groupRowCount = 0; + + for (size_t i = 0; i < rows.size(); ++i) { + if (rows[i] == nextRow) { + ++groupRowCount; + --nextRow; + } else { + if (groupRowCount > 0) { + // Remove previous group + const int lastRowInGroup = nextRow + 1; + removeRows(lastRowInGroup, groupRowCount); + } + + // Start next group + nextRow = rows[i] - 1; + groupRowCount = 1; + } + } + + if (groupRowCount > 0) { + // Remove leftover group + const int lastRowInGroup = nextRow + 1; + removeRows(lastRowInGroup, groupRowCount); + } +} + +MumbleProto::UserList UserListModel::getUserListUpdate() const { + MumbleProto::UserList updateList; + + for (ModelUserListChangeMap::ConstIterator it = m_changes.constBegin(); + it != m_changes.constEnd(); + ++it) { + MumbleProto::UserList_User* user = updateList.add_users(); + *user = it.value(); + } + + return updateList; +} + +bool UserListModel::isUserListDirty() const { + return !m_changes.empty(); +} + +bool UserListModel::isLegacy() const { + return m_legacyMode; +} + +QVariant UserListModel::lastSeenToTodayDayCount(const std::string &lastSeenDate) const { + if (lastSeenDate.empty()) + return QVariant(); + + QVariant count = m_stringToLastSeenToTodayCount.value(u8(lastSeenDate)); + if (count.isNull()) { + QDateTime dt = isoUTCToDateTime(lastSeenDate); + if (!dt.isValid()) { + // Not convertable to int + return QVariant(); + } + count = dt.daysTo(QDateTime::currentDateTime().toUTC()); + m_stringToLastSeenToTodayCount.insert(u8(lastSeenDate), count); + } + return count; +} + +QString UserListModel::pathForChannelId(const int channelId) const { + QString path = m_channelIdToPathMap.value(channelId); + if (path.isNull()) { + path = QLatin1String("-"); + + Channel *channel = Channel::get(channelId); + if (channel != NULL) { + QStringList pathParts; + + while (channel->cParent != NULL) { + pathParts.prepend(channel->qsName); + channel = channel->cParent; + } + + pathParts.append(QString()); + + path = QLatin1String("/ ") + pathParts.join(QLatin1String(" / ")); + } + + m_channelIdToPathMap.insert(channelId, path); + } + return path; +} + +QDateTime UserListModel::isoUTCToDateTime(const std::string &isoTime) const { + QDateTime dt = QDateTime::fromString(u8(isoTime), Qt::ISODate); + dt.setTimeSpec(Qt::UTC); + return dt; +} diff --git a/src/mumble/UserListModel.h b/src/mumble/UserListModel.h new file mode 100644 index 000000000..7f9c53f75 --- /dev/null +++ b/src/mumble/UserListModel.h @@ -0,0 +1,103 @@ +/* Copyright (C) 2013, Stefan Hacker + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + - Neither the name of the Mumble Developers nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef MUMBLE_MUMBLE_USERLISTMODEL_H_ +#define MUMBLE_MUMBLE_USERLISTMODEL_H_ + +#include +#include + +#include "Mumble.pb.h" + +/// +/// The UserListModel class provides a table model backed by a UserList protobuf structure. +/// It supports removing rows and editing user nicks. +/// +class UserListModel : public QAbstractTableModel { + Q_OBJECT + public: + /// Enumerates the columns in the table model + enum Columns { COL_NICK, COL_INACTIVEDAYS, COL_LASTCHANNEL, COUNT_COL }; + + /// UserListModel constructs a table model representing the userList. + /// @param userList User list protobuf structure (will be copied) + /// @param parent Parent in QObject hierarchy + UserListModel(const MumbleProto::UserList& userList, QObject *parent = NULL); + + int rowCount(const QModelIndex &parent = QModelIndex()) const; + int columnCount(const QModelIndex &parent = QModelIndex()) const; + + QVariant headerData(int section, Qt::Orientation orientation, int role) const; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + bool setData(const QModelIndex &index, const QVariant &value, int role); + Qt::ItemFlags flags(const QModelIndex &index) const; + + bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); + + /// Function for removing all rows in a selection + void removeRowsInSelection(const QItemSelection &selection); + + /// Returns a message for updating the original server state to the current model state. + MumbleProto::UserList getUserListUpdate() const; + + /// Returns true if the UserList given during construction was changed. + bool isUserListDirty() const; + + /// Returns true if the model only contains COL_NICK (true for Mumble <= 1.2.4) + bool isLegacy() const; + + private: + + /// Given an ISO formatted UTC time string returns the number of days since then. + /// @return QVariant() is returned for invalid strings. + QVariant lastSeenToTodayDayCount(const std::string& lastSeenDate) const; + /// Returns a textual representation of the channel hierarchy of the given channel + QString pathForChannelId(const int channelId) const; + /// Converts a ISO formatted UTC time string to a QDateTime object. + QDateTime isoUTCToDateTime(const std::string& isoTime) const; + + typedef QList ModelUserList; + /// Model backend for user data + ModelUserList m_userList; + + typedef QHash< ::google::protobuf::uint32, MumbleProto::UserList_User> ModelUserListChangeMap; + /// Change map indexed by user id + ModelUserListChangeMap m_changes; + + /// True if the message given on construction lacked column data (true for murmur <= 1.2.4) + bool m_legacyMode; + + /// Cache for lastSeenToTodayDayCount + mutable QHash m_stringToLastSeenToTodayCount; + /// Cache for pathForChannelId conversions + mutable QHash m_channelIdToPathMap; +}; + +#endif // MUMBLE_MUMBLE_USERLISTMODEL_H_ diff --git a/src/mumble/mumble.pro b/src/mumble/mumble.pro index 8acd935ae..d199d2b2d 100644 --- a/src/mumble/mumble.pro +++ b/src/mumble/mumble.pro @@ -68,8 +68,8 @@ isEqual(QT_MAJOR_VERSION, 5) { CONFIG += no-cocoa } -HEADERS *= BanEditor.h ACLEditor.h ConfigWidget.h Log.h AudioConfigDialog.h AudioStats.h AudioInput.h AudioOutput.h AudioOutputSample.h AudioOutputSpeech.h AudioOutputUser.h CELTCodec.h CustomElements.h MainWindow.h ServerHandler.h About.h ConnectDialog.h GlobalShortcut.h TextToSpeech.h Settings.h Database.h VersionCheck.h Global.h UserModel.h Audio.h ConfigDialog.h Plugins.h PTTButtonWidget.h LookConfig.h Overlay.h OverlayText.h SharedMemory.h AudioWizard.h ViewCert.h TextMessage.h NetworkConfig.h LCD.h Usage.h Cert.h ClientUser.h UserEdit.h Tokens.h UserView.h RichTextEditor.h UserInformation.h SocketRPC.h VoiceRecorder.h VoiceRecorderDialog.h WebFetch.h ../SignalCurry.h -SOURCES *= BanEditor.cpp ACLEditor.cpp ConfigWidget.cpp Log.cpp AudioConfigDialog.cpp AudioStats.cpp AudioInput.cpp AudioOutput.cpp AudioOutputSample.cpp AudioOutputSpeech.cpp AudioOutputUser.cpp main.cpp CELTCodec.cpp CustomElements.cpp MainWindow.cpp ServerHandler.cpp About.cpp ConnectDialog.cpp Settings.cpp Database.cpp VersionCheck.cpp Global.cpp UserModel.cpp Audio.cpp ConfigDialog.cpp Plugins.cpp PTTButtonWidget.cpp LookConfig.cpp OverlayClient.cpp OverlayConfig.cpp OverlayEditor.cpp OverlayEditorScene.cpp OverlayUser.cpp OverlayUserGroup.cpp Overlay.cpp OverlayText.cpp SharedMemory.cpp AudioWizard.cpp ViewCert.cpp Messages.cpp TextMessage.cpp GlobalShortcut.cpp NetworkConfig.cpp LCD.cpp Usage.cpp Cert.cpp ClientUser.cpp UserEdit.cpp Tokens.cpp UserView.cpp RichTextEditor.cpp UserInformation.cpp SocketRPC.cpp VoiceRecorder.cpp VoiceRecorderDialog.cpp WebFetch.cpp +HEADERS *= BanEditor.h ACLEditor.h ConfigWidget.h Log.h AudioConfigDialog.h AudioStats.h AudioInput.h AudioOutput.h AudioOutputSample.h AudioOutputSpeech.h AudioOutputUser.h CELTCodec.h CustomElements.h MainWindow.h ServerHandler.h About.h ConnectDialog.h GlobalShortcut.h TextToSpeech.h Settings.h Database.h VersionCheck.h Global.h UserModel.h Audio.h ConfigDialog.h Plugins.h PTTButtonWidget.h LookConfig.h Overlay.h OverlayText.h SharedMemory.h AudioWizard.h ViewCert.h TextMessage.h NetworkConfig.h LCD.h Usage.h Cert.h ClientUser.h UserEdit.h UserListModel.h Tokens.h UserView.h RichTextEditor.h UserInformation.h SocketRPC.h VoiceRecorder.h VoiceRecorderDialog.h WebFetch.h ../SignalCurry.h +SOURCES *= BanEditor.cpp ACLEditor.cpp ConfigWidget.cpp Log.cpp AudioConfigDialog.cpp AudioStats.cpp AudioInput.cpp AudioOutput.cpp AudioOutputSample.cpp AudioOutputSpeech.cpp AudioOutputUser.cpp main.cpp CELTCodec.cpp CustomElements.cpp MainWindow.cpp ServerHandler.cpp About.cpp ConnectDialog.cpp Settings.cpp Database.cpp VersionCheck.cpp Global.cpp UserModel.cpp Audio.cpp ConfigDialog.cpp Plugins.cpp PTTButtonWidget.cpp LookConfig.cpp OverlayClient.cpp OverlayConfig.cpp OverlayEditor.cpp OverlayEditorScene.cpp OverlayUser.cpp OverlayUserGroup.cpp Overlay.cpp OverlayText.cpp SharedMemory.cpp AudioWizard.cpp ViewCert.cpp Messages.cpp TextMessage.cpp GlobalShortcut.cpp NetworkConfig.cpp LCD.cpp Usage.cpp Cert.cpp ClientUser.cpp UserEdit.cpp UserListModel.cpp Tokens.cpp UserView.cpp RichTextEditor.cpp UserInformation.cpp SocketRPC.cpp VoiceRecorder.cpp VoiceRecorderDialog.cpp WebFetch.cpp SOURCES *= smallft.cpp DIST *= ../../icons/mumble.ico licenses.h smallft.h ../../icons/mumble.xpm murmur_pch.h mumble.plist RESOURCES *= mumble.qrc mumble_flags.qrc