File: roomdialogs.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 (515 lines) | stat: -rw-r--r-- 19,444 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
/*
 * SPDX-FileCopyrightText: 2017 Kitsune Ral <kitsune-ral@users.sf.net>
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

#include "roomdialogs.h"

#include "accountselector.h"
#include "logging_categories.h"
#include "mainwindow.h"
#include "models/orderbytag.h" // For tagToCaption()
#include "quaternionroom.h"

#include <Quotient/events/roompowerlevelsevent.h>

#include <Quotient/csapi/capabilities.h> // Only needed because loadCapabilities() implies it

#include <Quotient/accountregistry.h>
#include <Quotient/connection.h>
#include <Quotient/qt_connection_util.h>
#include <Quotient/user.h>

#include <QtWidgets/QCheckBox>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QCompleter>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QListWidget>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QPlainTextEdit>
#include <QtWidgets/QPushButton>

#include <QtCore/QElapsedTimer>
#include <QtCore/QStringBuilder>
#include <QtGui/QStandardItemModel>

RoomDialogBase::RoomDialogBase(const QString& title,
        const QString& applyButtonText,
        QuaternionRoom* r, QWidget* parent,
        QDialogButtonBox::StandardButtons extraButtons)
    : Dialog(title, parent, StatusLine, applyButtonText, extraButtons)
    , room(r), avatar(new QLabel)
    , roomName(new QLineEdit)
    , aliasServer(new QLabel), alias(new QLineEdit)
    , topic(new QPlainTextEdit)
    , publishRoom(new QCheckBox(tr("Publish room in room directory")))
    , guestCanJoin(new QCheckBox(tr("Allow guest accounts to join the room")))
    , mainFormLayout(addLayout<QFormLayout>())
{
    if (room)
    {
        avatar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
        avatar->setPixmap({64, 64});
    }
    topic->setTabChangesFocus(true);
    topic->setSizeAdjustPolicy(
                QAbstractScrollArea::AdjustToContentsOnFirstShow);

    // Layout controls

    {
        if (room)
        {
            auto* topLayout = new QHBoxLayout;
            topLayout->addWidget(avatar);
            {
                essentialsLayout = new QFormLayout;
                essentialsLayout->addRow(tr("Room name"), roomName);
                essentialsLayout->addRow(tr("Primary alias"), alias);
                topLayout->addLayout(essentialsLayout);
            }
            mainFormLayout->addRow(topLayout);
        } else {
            mainFormLayout->addRow(tr("Room name"), roomName);
            auto* aliasLayout = new QHBoxLayout;
            aliasLayout->addWidget(new QLabel("#"));
            aliasLayout->addWidget(alias);
            aliasLayout->addWidget(aliasServer);
            mainFormLayout->addRow(tr("Primary alias"), aliasLayout);
        }
    }
    mainFormLayout->addRow(tr("Topic"), topic);
    if (!room) // TODO: Support this in RoomSettingsDialog as well
    {
        mainFormLayout->addRow(publishRoom);
//        formLayout->addRow(guestCanJoin); // TODO: quotient-im/libQuotient#36
    }
}

QComboBox* RoomDialogBase::addVersionSelector(QLayout* layout)
{
    auto* versionSelector = new QComboBox;
    layout->addWidget(versionSelector);
    {
        auto* specLink =
                new QLabel("<a href='https://matrix.org/docs/spec/#complete-list-of-room-versions'>" +
                           tr("About room versions") + "</a>");
        specLink->setOpenExternalLinks(true);
        layout->addWidget(specLink);
    }
    return versionSelector;
}

void RoomDialogBase::refillVersionSelector(QComboBox* selector,
                                           Connection* account)
{
    selector->clear();
    selector->addItem(tr("(loading)", "Loading room versions from the server"), QString());
    selector->setEnabled(false);
    account->loadCapabilities().then([selector, account] {
        selector->clear();
        const auto& versions = account->availableRoomVersions();
        if (versions.empty()) {
            selector->addItem(tr("(no available room versions)"), QString());
        } else
            for (const auto& v : versions) {
                const bool isDefault = v.id == account->defaultRoomVersion();
                const auto postfix = isDefault      ? tr("default", "Default room version")
                                     : v.isStable() ? tr("stable", "Stable room version")
                                                    : v.status;
                selector->addItem(v.id % " (" % postfix % ")", v.id);
                const auto idx = selector->count() - 1;
                if (isDefault) {
                    auto font = selector->itemData(idx, Qt::FontRole).value<QFont>();
                    font.setBold(true);
                    selector->setItemData(idx, font, Qt::FontRole);
                    selector->setCurrentIndex(idx);
                }
                if (!v.isStable())
                    selector->setItemData(idx, QColor(Qt::red), Qt::ForegroundRole);
            }
        selector->setEnabled(!versions.isEmpty());
    });
}

void RoomDialogBase::addEssentials(QWidget* accountControl,
                                   QLayout* versionBox)
{
    Q_ASSERT(accountControl != nullptr && versionBox != nullptr);
    auto* layout = essentialsLayout ? essentialsLayout : mainFormLayout;
    layout->insertRow(0, tr("Account"), accountControl);
    layout->insertRow(1, tr("Room version"), versionBox);
}

bool RoomDialogBase::checkRoomVersion(QString version, Connection* account)
{
    if (account->stableRoomVersions().contains(version))
        return true;

    return QMessageBox::warning(this, tr("Continue with unstable version?"),
            tr("You are using an UNSTABLE room version (%1)."
               " The server may stop supporting it at any moment."
               " Do you still want to use this version?").arg(version),
            QMessageBox::Yes|QMessageBox::No, QMessageBox::No)
        == QMessageBox::Yes;
}

RoomSettingsDialog::RoomSettingsDialog(QuaternionRoom* room, MainWindow* parent)
    : RoomDialogBase(tr("Room settings: %1").arg(room->displayName()),
                     tr("Update room"), room, parent)
    , account(new QLabel(room->connection()->userId()))
    , version(new QLabel(room->version()))
    , tagsList(new QListWidget)
{
    auto* versionBox = new QGridLayout;
    versionBox->addWidget(version, 0, 0);
    if (room->isUnstable())
        versionBox->addWidget(
            new QLabel(tr("This version is unstable! Consider upgrading.")),
            1, 0);
    if (room->canSwitchVersions())
    {
        auto* changeActionButton =
                new QPushButton(tr("Upgrade", "Upgrade a room version"));
        connect(changeActionButton, &QAbstractButton::clicked, this, [this, room] {
            Dialog chooseVersionDlg(tr("Choose new room version"), this,
                    NoStatusLine, tr("Upgrade", "Upgrade a room version"),
                    NoExtraButtons);
            chooseVersionDlg.addWidget(
                new QLabel(tr("You are about to upgrade %1.\n"
                              "This operation cannot be reverted.")
                           .arg(room->displayName())));
            auto* hBox = chooseVersionDlg.addLayout<QHBoxLayout>();
            auto* versionSelector = addVersionSelector(hBox);
            refillVersionSelector(versionSelector, room->connection());
            if (chooseVersionDlg.exec() == QDialog::Accepted)
            {
                version->setText(versionSelector->currentData().toString());
                apply();
            }
        });
        versionBox->addWidget(changeActionButton, 0, 1, -1, 1);
    }
    addEssentials(account, versionBox);
    connect(room, &QuaternionRoom::avatarChanged, this, [this, room] {
        if (!userChangedAvatar)
            avatar->setPixmap(QPixmap::fromImage(room->avatar(64)));
    });
    avatar->setPixmap(QPixmap::fromImage(room->avatar(64)));
    tagsList->setSizeAdjustPolicy(
                QAbstractScrollArea::AdjustToContentsOnFirstShow);
    tagsList->setUniformItemSizes(true);
    tagsList->setSelectionMode(QAbstractItemView::ExtendedSelection);

    mainFormLayout->addRow(tr("Tags"), tagsList);

    auto* roomIdLabel = new QLabel(room->id());
    roomIdLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
    mainFormLayout->addRow(tr("Room identifier"), roomIdLabel);

    connect(room, &QObject::destroyed, this, &QObject::deleteLater);

    // Uncomment to debug room display name calculation code
//    auto* refreshNameButton =
//        buttonBox()->addButton(tr("Refresh name"), QDialogButtonBox::ApplyRole);
//    connect(refreshNameButton, &QPushButton::clicked,
//            room, &QuaternionRoom::refreshDisplayName);
}

void RoomSettingsDialog::load()
{
    if (const auto* plEvt =
        room->currentState().get<Quotient::RoomPowerLevelsEvent>()) {
        const int userPl = plEvt->powerLevelForUser(room->localMember().id());

        roomName->setText(room->name());
        roomName->setReadOnly(plEvt->powerLevelForState("m.room.name") > userPl);
        alias->setText(room->canonicalAlias());
        alias->setReadOnly(plEvt->powerLevelForState("m.room.canonical_alias")
                           > userPl);
        topic->setPlainText(room->topic());
        topic->setReadOnly(plEvt->powerLevelForState("m.room.topic") > userPl);
    }
    // QPlainTextEdit may change some characters before any editing occurs;
    // so save this already adjusted topic to compare later.
    previousTopic = topic->toPlainText();

    tagsList->clear();
    auto roomTags = room->tagNames();
    for (const auto& tag: room->connection()->tagNames())
    {
        auto* item = new QListWidgetItem(tagToCaption(tag), tagsList);
        item->setData(Qt::UserRole, tag);
        item->setFlags(Qt::ItemIsEnabled|Qt::ItemIsUserCheckable);
        item->setCheckState(
                    roomTags.contains(tag) ? Qt::Checked : Qt::Unchecked);
        item->setToolTip(tag);
        tagsList->addItem(item);
    }
}

bool RoomSettingsDialog::validate()
{
    if (room->version() == version->text()
            || (room->canSwitchVersions()
                && checkRoomVersion(version->text(), room->connection())))
        return true; // The room is the same, or it's allowed to change it

    version->setText(room->version());
    return false; // Cancel applying, stay on the settings dialog
}

void RoomSettingsDialog::apply()
{
    using Quotient::Room;
    if (version->text() != room->version())
    {
        setStatusMessage(tr("Creating the new room version, please wait"));
        connectUntil(room, &Room::upgraded, this,
            [this] (const QString&, Room* newRoom) {
                accept();
                static_cast<MainWindow*>(parent())->selectRoom(newRoom);
                return true;
            });
        connect(room, &Room::upgradeFailed, this, &Dialog::applyFailed, Qt::SingleShotConnection);
        room->switchVersion(version->text());
        return; // It's either a version upgrade or everything else
    }
    if (roomName->text() != room->name())
        room->setName(roomName->text());
    if (alias->text() != room->canonicalAlias())
        room->setCanonicalAlias(alias->text());
    if (topic->toPlainText() != previousTopic)
        room->setTopic(topic->toPlainText());
    auto tags = room->tags();
    for (int i = 0; i < tagsList->count(); ++i)
    {
        const auto* item = tagsList->item(i);
        const auto tagName = item->data(Qt::UserRole).toString();
        if (item->checkState() == Qt::Checked)
            tags[tagName]; // Just ensure the tag is there, no overwriting
        else
            tags.remove(tagName);
    }
    room->setTags(tags, Room::WithinSameState);
    accept();
}

class NextInvitee : public QComboBox
{
    public:
        using QComboBox::QComboBox;

    private:
        void focusInEvent(QFocusEvent* event) override
        {
            QComboBox::focusInEvent(event);
            static_cast<CreateRoomDialog*>(parent())->updatePushButtons();
        }
        void focusOutEvent(QFocusEvent* event) override
        {
            QComboBox::focusOutEvent(event);
            static_cast<CreateRoomDialog*>(parent())->updatePushButtons();
        }
};

class InviteeList : public QListWidget
{
    public:
        using QListWidget::QListWidget;

    private:
        void keyPressEvent(QKeyEvent* event) override
        {
            if (event->key() ==  Qt::Key_Delete)
                delete takeItem(currentRow());
            else
                QListWidget::keyPressEvent(event);
        }
        void mousePressEvent(QMouseEvent* event) override
        {
            if (event->button() == Qt::MiddleButton)
                delete takeItem(currentRow());
            else
                QListWidget::mousePressEvent(event);
        }
};

CreateRoomDialog::CreateRoomDialog(Quotient::AccountRegistry* accounts,
                                   QWidget* parent)
    : RoomDialogBase(tr("Create room"), tr("Create room"), nullptr, parent,
                     NoExtraButtons)
    , accountChooser(new AccountSelector(accounts))
    , version(nullptr) // Will be initialized below
    , nextInvitee(new NextInvitee)
    , addToInviteesButton(
          new QPushButton(tr("Add", "Add a user to the list of invitees")))
    , removeFromInviteesButton(
          new QPushButton(tr("Remove", "Remove a user from the list of invitees")))
    , invitees(new InviteeList)
{
    Q_ASSERT(!accounts->empty());

    auto* versionBox = new QHBoxLayout;
    version = addVersionSelector(versionBox);
    addEssentials(accountChooser, versionBox);
    connect(accountChooser, &AccountSelector::currentAccountChanged,
            this, &CreateRoomDialog::accountSwitched);
    mainFormLayout->insertRow(0, new QLabel(
            tr("Please fill the fields as desired. None are mandatory")));

    nextInvitee->setEditable(true);
    nextInvitee->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
    nextInvitee->setMinimumContentsLength(42);
    auto* completer = new QCompleter(nextInvitee);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
    completer->setModelSorting(QCompleter::CaseSensitivelySortedModel);
    nextInvitee->setCompleter(completer);
    connect(nextInvitee, &NextInvitee::currentTextChanged,
            this, &CreateRoomDialog::updatePushButtons);
    // Add button initialization
    addToInviteesButton->setFocusPolicy(Qt::NoFocus);
    addToInviteesButton->setDisabled(true);
    connect(addToInviteesButton, &QPushButton::clicked, [this] {
        auto userName = nextInvitee->currentText();
        if (userName.indexOf('@') == -1)
        {
            userName.prepend('@');
            if (userName.indexOf(':') == -1)
                userName += ':' + accountChooser->currentAccount()->domain();
        }
        invitees->addItem(userName);
        nextInvitee->clear();
    });

    // Remove button initialization
    removeFromInviteesButton->setFocusPolicy(Qt::NoFocus);
    removeFromInviteesButton->setDisabled(true);
    connect(removeFromInviteesButton, &QPushButton::clicked, [this] {
        if (invitees->currentItem() == nullptr)
            return;
        delete invitees->takeItem(invitees->currentRow());
    });
    connect(invitees, &InviteeList::currentItemChanged, this,
            &CreateRoomDialog::updatePushButtons);

    invitees->setSizeAdjustPolicy(
                QAbstractScrollArea::AdjustToContentsOnFirstShow);
    invitees->setUniformItemSizes(true);
    invitees->setSortingEnabled(true);

    // Layout additional controls

    auto* inviteLayout = new QHBoxLayout;
    inviteLayout->addWidget(nextInvitee);
    inviteLayout->addWidget(addToInviteesButton);
    inviteLayout->addWidget(removeFromInviteesButton);

    mainFormLayout->addRow(tr("Invite user(s)"), inviteLayout);
    mainFormLayout->addRow("", invitees);

    setPendingApplyMessage(tr("Creating the room, please wait"));

    if (accounts->size() > 1)
        accountChooser->setFocus();
    else
        roomName->setFocus();
}

void CreateRoomDialog::updatePushButtons()
{
    addToInviteesButton->setEnabled(!nextInvitee->currentText().isEmpty());
    removeFromInviteesButton->setEnabled(invitees->currentItem() != nullptr);
    if (addToInviteesButton->isEnabled() && nextInvitee->hasFocus())
        addToInviteesButton->setDefault(true);
    else
        buttonBox()->button(QDialogButtonBox::Ok)->setDefault(true);
}

void CreateRoomDialog::load()
{
    roomName->clear();
    alias->clear();
    topic->clear();
    previousTopic.clear();
    nextInvitee->clear();
    accountSwitched();
    invitees->clear();
}

bool CreateRoomDialog::validate()
{
    auto* connection = accountChooser->currentAccount();
    if (checkRoomVersion(version->currentData().toString(), connection))
        return true;

    refillVersionSelector(version, connection);
    return false;
}

void CreateRoomDialog::apply()
{
    using namespace Quotient;
    auto* const account = accountChooser->currentAccount();
    QStringList userIds;
    for (int i = 0; i < invitees->count(); ++i)
        if (const auto& userId = invitees->item(i)->text(); account->user(userId))
            userIds.push_back(userId);
        else
            qCWarning(MAIN).nospace() << std::source_location::current().function_name() << ": "
                                      << userId << "is not a correct user id, skipping";


    account
        ->createRoom(publishRoom->isChecked() ? Connection::PublishRoom : Connection::UnpublishRoom,
                     alias->text(), roomName->text(), topic->toPlainText(), userIds, "",
                     version->currentData().toString(), false)
        .then(this, &Dialog::accept,
              [this](const BaseJob* job) { applyFailed(job->errorString()); });
}

void CreateRoomDialog::accountSwitched()
{
    const auto& savedCurrentText = nextInvitee->currentText();

    auto* connection = accountChooser->currentAccount();
    refillVersionSelector(version, connection);
    aliasServer->setText(':' + connection->domain());

    auto* completer = nextInvitee->completer();
    Q_ASSERT(completer != nullptr && connection != nullptr);

    auto*& model = userLists[connection];
    if (!model) {
        model = new QStandardItemModel(completer);

//    auto prefix =
//            savedCurrentText.midRef(savedCurrentText.startsWith('@') ? 1 : 0);
//    if (prefix.size() >= 3)
//    {
        QElapsedTimer et; et.start();
        for (const auto& uId: connection->userIds())
        {
            if (!Quotient::isGuestUserId(uId))
            {
                // It would be great to show a user's full name rather than MXID; unfortunately,
                // this implies fetching profiles for the whole list of users known to a given
                // account, one by one, and that can easily be thousands.
                auto* item = new QStandardItem(uId);
                model->appendRow(item);
            }
        }
        qCDebug(MAIN) << "Completion candidates:" << model->rowCount()
                      << "out of" << connection->userIds().size() << "filled in"
                      << et;
//    }
    }
    nextInvitee->setModel(model);
    nextInvitee->setEditText(savedCurrentText);
    completer->setCompletionPrefix(savedCurrentText);
}