File: roomlistdock.cpp

package info (click to toggle)
quaternion 0.0.97.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,800 kB
  • sloc: cpp: 8,380; xml: 172; sh: 5; makefile: 2
file content (337 lines) | stat: -rw-r--r-- 12,608 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/**************************************************************************
 *                                                                        *
 * SPDX-FileCopyrightText: 2015 Felix Rohrbach <kde@fxrh.de>              *
 *                                                                        *
 * SPDX-License-Identifier: GPL-3.0-or-later
 *                                                                        *
 **************************************************************************/

#include "roomlistdock.h"

#include "logging_categories.h"

#include <QtWidgets/QMenu>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QStyledItemDelegate>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPlainTextEdit>
#include <QtGui/QGuiApplication>
#include <QtGui/QClipboard>

#include "mainwindow.h"
#include "models/roomlistmodel.h"
#include "models/orderbytag.h"
#include "quaternionroom.h"
#include "roomdialogs.h"

#include <Quotient/connection.h>
#include <Quotient/settings.h>

using Quotient::SettingsGroup;

class RoomListItemDelegate // clazy:exclude=missing-qobject-macro
    : public QStyledItemDelegate
{
    public:
        using QStyledItemDelegate::QStyledItemDelegate;

        void paint(QPainter *painter, const QStyleOptionViewItem &option,
                   const QModelIndex &index) const override;
};

void RoomListItemDelegate::paint(QPainter* painter,
         const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    QStyleOptionViewItem o { option };

    if (!index.parent().isValid()) // Group captions
    {
        o.displayAlignment = Qt::AlignHCenter;
        o.font.setBold(true);
    }

    if (index.data(RoomListModel::HasUnreadRole).toBool())
        o.font.setBold(true);

    if (index.data(RoomListModel::HighlightCountRole).toInt() > 0)
    {
        static const auto highlightColor =
            Quotient::Settings().get("UI/highlight_color", QColor("orange"));
        o.palette.setColor(QPalette::Text, highlightColor);
        // Highlighting the text may not work out on monochrome colour schemes,
        // hence duplicating with italic font.
        o.font.setItalic(true);
    }

    const auto joinState = index.data(RoomListModel::JoinStateRole).toString();
    if (joinState == "invite")
        o.font.setItalic(true);
    else if (joinState == "leave" || joinState == "upgraded")
        o.font.setStrikeOut(true);

    QStyledItemDelegate::paint(painter, o, index);
}

RoomListDock::RoomListDock(MainWindow* parent)
    : QDockWidget("Rooms", parent)
    , view(new QTreeView(this))
    , model(new RoomListModel(view))
{
    setObjectName("RoomsDock");
//    proxyModel = new QSortFilterProxyModel();
//    proxyModel->setDynamicSortFilter(true);
//    proxyModel->setSourceModel(model);
    updateSortingMode();
    view->setModel(model);
    view->setItemDelegate(new RoomListItemDelegate(this));
    view->setAnimated(true);
    view->setUniformRowHeights(true);
    view->setSelectionBehavior(QTreeView::SelectRows);
    view->setHeaderHidden(true);
    view->setIndentation(0);
    view->setRootIsDecorated(false);
    const auto iconExtent = view->fontMetrics().height();
    view->setIconSize(
        QIcon::fromTheme("user-available", QIcon(":/irc-channel-joined"))
            .actualSize({ iconExtent, iconExtent }));

    static const auto Expanded = QStringLiteral("expand");
    static const auto Collapsed = QStringLiteral("collapse");
    connect( view, &QTreeView::activated, this, &RoomListDock::rowSelected ); // See #608
    connect( view, &QTreeView::clicked, this, &RoomListDock::rowSelected);
    connect( view, &QTreeView::pressed, this, [this] {
        if (QGuiApplication::mouseButtons() & Qt::MiddleButton) {
            if (auto room = getSelectedRoom())
                room->markAllMessagesAsRead();
        }
    });
    connect( model, &RoomListModel::rowsInserted,
             this, &RoomListDock::refreshTitle );
    connect( model, &RoomListModel::rowsRemoved,
             this, &RoomListDock::refreshTitle );
    connect( model, &RoomListModel::saveCurrentSelection, this, [this] {
        selectedGroupCache = getSelectedGroup();
        selectedRoomCache = getSelectedRoom();
    });
    connect( model, &RoomListModel::restoreCurrentSelection, this, [this] {
        const auto& idx =
            model->indexOf(selectedGroupCache, selectedRoomCache);
//            proxyModel->mapFromSource(model->indexOf(selectedRoomCache));
        view->setCurrentIndex(idx);
        view->scrollTo(idx);
        selectedGroupCache.clear();
        selectedRoomCache = nullptr;
    });

    static SettingsGroup dockSettings("UI/RoomsDock");
    connect(model, &RoomListModel::groupAdded, this, [this](int groupPos) {
        const auto& i = model->index(groupPos, 0);
        const auto groupKey = model->roomGroupAt(i).toString();
        if (groupKey.startsWith("org.qmatrixclient"))
            qCCritical(MAIN)
                << groupKey << "is deprecated!"; // Fighting the legacy
        auto groupState = dockSettings.value(groupKey);
        if (!groupState.isValid()) {
            if (groupKey.startsWith(RoomGroup::SystemPrefix)) {
                const auto legacyKey = RoomGroup::LegacyPrefix
                                       + groupKey.mid(
                                           RoomGroup::SystemPrefix.size());
                groupState = dockSettings.value(legacyKey);
                dockSettings.setValue(groupKey, groupState);
                if (groupState.isValid())
                    dockSettings.remove(legacyKey);
            }
        }
        view->setExpanded(i, groupState.isValid()
                                 ? groupState.toString() == Expanded
                                 : groupKey == Quotient::FavouriteTag);
    });
    connect(view, &QTreeView::expanded, this, [this](QModelIndex i) {
        dockSettings.setValue(model->roomGroupAt(i).toString(), Expanded);
    });
    connect(view, &QTreeView::collapsed, this, [this](QModelIndex i) {
        dockSettings.setValue(model->roomGroupAt(i).toString(), Collapsed);
    });

    setWidget(view);

    roomContextMenu = new QMenu(this);
    markAsReadAction =
        roomContextMenu->addAction(QIcon::fromTheme("mail-mark-read"),
            tr("Mark room as read"), this, [this] {
            if (auto room = getSelectedRoom())
                room->markAllMessagesAsRead();
        });
    roomContextMenu->addSeparator();
    addTagsAction =
        roomContextMenu->addAction(QIcon::fromTheme("tag-new"),
        tr("Add tags..."), this, &RoomListDock::addTagsSelected);
    roomSettingsAction = roomContextMenu->addAction(
        QIcon::fromTheme("user-group-properties"),
        tr("Change room &settings..."),
        [this, parent] { parent->openRoomSettings(getSelectedRoom()); });
    roomPermalinkAction = roomContextMenu->addAction(
        QIcon::fromTheme("link"), tr("Copy room link to clipboard"), [this] {
            QGuiApplication::clipboard()->setText(
                "https://matrix.to/#/" + getSelectedRoom()->canonicalAlias());
        });
    roomContextMenu->addSeparator();
    joinAction =
        roomContextMenu->addAction(QIcon::fromTheme("irc-join-channel"),
        tr("Join room"), this, [this] {
            if (auto room = getSelectedRoom())
            {
                Q_ASSERT(room->connection());
                room->connection()->joinRoom(room->id());
            }
        });
    leaveAction =
        roomContextMenu->addAction(QIcon::fromTheme("irc-close-channel"),
        {}, this, [this] {
            if (auto room = getSelectedRoom())
                room->leaveRoom();
        });
    roomContextMenu->addSeparator();
    forgetAction =
        roomContextMenu->addAction(QIcon::fromTheme("irc-remove-operator"),
        tr("Forget room"), this, [this] {
            if (auto room = getSelectedRoom()) {
                QMessageBox::StandardButton confirmation = QMessageBox::question(
                    this, tr("Forget this room?"),
                    tr("Are you sure you want to forget room %1?").arg(room->displayName()));
                if (confirmation == QMessageBox::Yes) {
                    if (QUO_CHECK(room->connection()))
                        room->connection()->forgetRoom(room->id());
                }
            }
        });

    groupContextMenu = new QMenu(this);
    deleteTagAction =
        groupContextMenu->addAction(QIcon::fromTheme("tag-delete"),
        tr("Remove tag"), this, [this] {
            model->deleteTag(view->currentIndex());
        });

    setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this, &QWidget::customContextMenuRequested, this, &RoomListDock::showContextMenu);
}

void RoomListDock::addConnection(Quotient::Connection* connection)
{
    model->addConnection(connection);
}

void RoomListDock::deleteConnection(Quotient::Connection* connection)
{
    model->deleteConnection(connection);
}

void RoomListDock::updateSortingMode()
{
//    const auto sortMode =
//            Quotient::Settings().value("UI/sort_rooms_by", 0).toInt();
//    proxyModel->sort(sortMode,
//                     sortMode == 0 ? Qt::AscendingOrder : Qt::DescendingOrder);
    model->setOrder<OrderByTag>();
}

void RoomListDock::setSelectedRoom(QuaternionRoom* room)
{
    if (getSelectedRoom() == room)
        return;
    // First try the current group; if that fails, try the entire list
    QModelIndex idx;
    auto currentGroup = getSelectedGroup();
    if (!currentGroup.isNull())
        idx = model->indexOf(currentGroup, room);
    if (!idx.isValid())
        idx = model->indexOf({}, room);
    if (idx.isValid())
    {
        view->setCurrentIndex(idx);
        view->scrollTo(idx);
    }
}

void RoomListDock::rowSelected(const QModelIndex& index)
{
    if (model->isValidRoomIndex(index))
//        emit roomSelected( model->roomAt(proxyModel->mapToSource(index)));
        emit roomSelected(model->roomAt(index));
}

void RoomListDock::showContextMenu(const QPoint& pos)
{
    auto index = view->indexAt(view->mapFromParent(pos));
    if (!index.isValid())
        return; // No context menu on root item yet
    if (model->isValidGroupIndex(index))
    {
        // Don't allow to delete system "tags"
        auto tagName = model->roomGroupAt(index);
        deleteTagAction->setDisabled(
            tagName.toString().startsWith(RoomGroup::SystemPrefix));
        groupContextMenu->popup(mapToGlobal(pos));
        return;
    }
    Q_ASSERT(model->isValidRoomIndex(index));
    auto room = model->roomAt(index);
//    auto room = model->roomAt(proxyModel->mapToSource(index));

    using Quotient::JoinState;
    bool joined = room->joinState() == JoinState::Join;
    bool invited = room->joinState() == JoinState::Invite;
    markAsReadAction->setEnabled(joined);
    addTagsAction->setEnabled(joined);
    joinAction->setEnabled(!joined);
    leaveAction->setText(invited ? tr("Reject invitation") : tr("Leave room"));
    leaveAction->setEnabled(room->joinState() != JoinState::Leave);
    forgetAction->setVisible(!invited);

    roomContextMenu->popup(mapToGlobal(pos));
}

QVariant RoomListDock::getSelectedGroup() const
{
    auto index = view->currentIndex();
    return !index.isValid() ? QVariant() : model->roomGroupAt(index);
}

QuaternionRoom* RoomListDock::getSelectedRoom() const
{
    QModelIndex index = view->currentIndex();
    return !index.isValid() || !index.parent().isValid() ? nullptr
                            : model->roomAt(index);
//                            : model->roomAt(proxyModel->mapToSource(index));
}

void RoomListDock::addTagsSelected()
{
    if (auto room = getSelectedRoom())
    {
        Dialog dlg(tr("Enter new tags for the room"), this, Dialog::NoStatusLine,
                   tr("Add", "A caption on a button to add tags"),
                   Dialog::NoExtraButtons);
        dlg.addWidget(
            new QLabel(tr("Enter tags to add to this room, one tag per line")));
        auto tagsInput = new QPlainTextEdit();
        tagsInput->setTabChangesFocus(true);
        dlg.addWidget(tagsInput);
        if (dlg.exec() != QDialog::Accepted)
            return;

        auto tags = room->tags();
        const auto enteredTags =
            tagsInput->toPlainText().split('\n', Qt::SkipEmptyParts);
        for (const auto& tag: enteredTags)
            tags[captionToTag(tag)]; // No overwriting, just ensure existence

        room->setTags(tags, Quotient::Room::WithinSameState);
    }
}

void RoomListDock::refreshTitle()
{
    setWindowTitle(tr("Rooms (%L1)").arg(model->totalRooms()));
}