Debian Codegraph @

src/timeline/CommunitiesModel.cpp

raw symbols SCIP
1 // SPDX-FileCopyrightText: Nheko Contributors
2 //
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
5 #include "CommunitiesModel.h"
6
7 #include <mtx/responses/common.hpp>
8 #include <set>
9
10 #include "Cache.h"
11 #include "Cache_p.h"
12 #include "ChatPage.h"
13 #include "Logging.h"
14 #include "MatrixClient.h"
15 #include "Permissions.h"
16 #include "UserSettingsPage.h"
17 #include "Utils.h"
18 #include "timeline/TimelineModel.h"
19
20 CommunitiesModel::CommunitiesModel(QObject *parent)
21 : QAbstractListModel(parent)
22 , hiddenTagIds_{UserSettings::instance()->hiddenTags()}
23 , mutedTagIds_{UserSettings::instance()->mutedTags()}
24 {
25 instance_ = this;
26 }
27
28 QHash<int, QByteArray>
29 CommunitiesModel::roleNames() const
30 {
31 return {
32 {AvatarUrl, "avatarUrl"},
33 {DisplayName, "displayName"},
34 {Tooltip, "tooltip"},
35 {Collapsed, "collapsed"},
36 {Collapsible, "collapsible"},
37 {Hidden, "hidden"},
38 {Depth, "depth"},
39 {Id, "id"},
40 {UnreadMessages, "unreadMessages"},
41 {HasLoudNotification, "hasLoudNotification"},
42 {Muted, "muted"},
43 };
44 }
45
46 bool
47 CommunitiesModel::setData(const QModelIndex &index, const QVariant &value, int role)
48 {
49 if (role != CommunitiesModel::Collapsed)
50 return false;
51 else if (index.row() >= 2 || index.row() - 2 < spaceOrder_.size()) {
52 spaceOrder_.tree.at(index.row() - 2).collapsed = value.toBool();
53
54 const auto cindex = spaceOrder_.lastChild(index.row() - 2);
55 emit dataChanged(index, this->index(cindex + 2), {Collapsed, Qt::DisplayRole});
56 spaceOrder_.storeCollapsed();
57 return true;
58 } else
59 return false;
60 }
61
62 QVariant
63 CommunitiesModel::data(const QModelIndex &index, int role) const
64 {
65 if (role == CommunitiesModel::Roles::Muted) {
66 if (index.row() == 0)
67 return mutedTagIds_.contains(QStringLiteral("global"));
68 else
69 return mutedTagIds_.contains(data(index, CommunitiesModel::Roles::Id).toString());
70 }
71
72 if (index.row() == 0) {
73 switch (role) {
74 case CommunitiesModel::Roles::AvatarUrl:
75 return QStringLiteral(":/icons/icons/ui/world.svg");
76 case CommunitiesModel::Roles::DisplayName:
77 return tr("All rooms");
78 case CommunitiesModel::Roles::Tooltip:
79 return tr("Shows all rooms without filtering.");
80 case CommunitiesModel::Roles::Collapsed:
81 return false;
82 case CommunitiesModel::Roles::Collapsible:
83 return false;
84 case CommunitiesModel::Roles::Hidden:
85 return false;
86 case CommunitiesModel::Roles::Parent:
87 return "";
88 case CommunitiesModel::Roles::Depth:
89 return 0;
90 case CommunitiesModel::Roles::Id:
91 return "";
92 case CommunitiesModel::Roles::UnreadMessages:
93 return (int)globalUnreads.notification_count;
94 case CommunitiesModel::Roles::HasLoudNotification:
95 return globalUnreads.highlight_count > 0;
96 }
97 } else if (index.row() == 1) {
98 switch (role) {
99 case CommunitiesModel::Roles::AvatarUrl:
100 return QStringLiteral(":/icons/icons/ui/people.svg");
101 case CommunitiesModel::Roles::DisplayName:
102 return tr("Direct Chats");
103 case CommunitiesModel::Roles::Tooltip:
104 return tr("Show direct chats.");
105 case CommunitiesModel::Roles::Collapsed:
106 return false;
107 case CommunitiesModel::Roles::Collapsible:
108 return false;
109 case CommunitiesModel::Roles::Hidden:
110 return hiddenTagIds_.contains(QStringLiteral("dm"));
111 case CommunitiesModel::Roles::Parent:
112 return "";
113 case CommunitiesModel::Roles::Depth:
114 return 0;
115 case CommunitiesModel::Roles::Id:
116 return "dm";
117 case CommunitiesModel::Roles::UnreadMessages:
118 return (int)dmUnreads.notification_count;
119 case CommunitiesModel::Roles::HasLoudNotification:
120 return dmUnreads.highlight_count > 0;
121 }
122 } else if (index.row() - 2 < spaceOrder_.size()) {
123 auto id = spaceOrder_.tree.at(index.row() - 2).id;
124 switch (role) {
125 case CommunitiesModel::Roles::AvatarUrl:
126 return QString::fromStdString(spaces_.at(id).avatar_url);
127 case CommunitiesModel::Roles::DisplayName:
128 case CommunitiesModel::Roles::Tooltip:
129 return QString::fromStdString(spaces_.at(id).name);
130 case CommunitiesModel::Roles::Collapsed:
131 return spaceOrder_.tree.at(index.row() - 2).collapsed;
132 case CommunitiesModel::Roles::Collapsible: {
133 auto idx = index.row() - 2;
134 return idx != spaceOrder_.lastChild(idx);
135 }
136 case CommunitiesModel::Roles::Hidden:
137 return hiddenTagIds_.contains("space:" + id);
138 case CommunitiesModel::Roles::Parent: {
139 if (auto p = spaceOrder_.parent(index.row() - 2); p >= 0)
140 return spaceOrder_.tree[p].id;
141
142 return "";
143 }
144 case CommunitiesModel::Roles::Depth:
145 return spaceOrder_.tree.at(index.row() - 2).depth;
146 case CommunitiesModel::Roles::Id:
147 return "space:" + id;
148 case CommunitiesModel::Roles::UnreadMessages: {
149 int count = 0;
150 auto end = spaceOrder_.lastChild(index.row() - 2);
151 for (int i = index.row() - 2; i <= end; i++)
152 count +=
153 static_cast<int>(spaceOrder_.tree[i].notificationCounts.notification_count);
154 return count;
155 }
156 case CommunitiesModel::Roles::HasLoudNotification: {
157 auto end = spaceOrder_.lastChild(index.row() - 2);
158 for (int i = index.row() - 2; i <= end; i++)
159 if (spaceOrder_.tree[i].notificationCounts.highlight_count > 0)
160 return true;
161 return false;
162 }
163 }
164 } else if (index.row() - 2 < tags_.size() + spaceOrder_.size()) {
165 auto tag = tags_.at(index.row() - 2 - spaceOrder_.size());
166 if (tag == QLatin1String("m.favourite")) {
167 switch (role) {
168 case CommunitiesModel::Roles::AvatarUrl:
169 return QStringLiteral(":/icons/icons/ui/star.svg");
170 case CommunitiesModel::Roles::DisplayName:
171 return tr("Favourites");
172 case CommunitiesModel::Roles::Tooltip:
173 return tr("Rooms you have favourited.");
174 }
175 } else if (tag == QLatin1String("m.lowpriority")) {
176 switch (role) {
177 case CommunitiesModel::Roles::AvatarUrl:
178 return QStringLiteral(":/icons/icons/ui/lowprio.svg");
179 case CommunitiesModel::Roles::DisplayName:
180 return tr("Low Priority");
181 case CommunitiesModel::Roles::Tooltip:
182 return tr("Rooms with low priority.");
183 }
184 } else if (tag == QLatin1String("m.server_notice")) {
185 switch (role) {
186 case CommunitiesModel::Roles::AvatarUrl:
187 return QStringLiteral(":/icons/icons/ui/tag.svg");
188 case CommunitiesModel::Roles::DisplayName:
189 return tr("Server Notices");
190 case CommunitiesModel::Roles::Tooltip:
191 return tr("Messages from your server or administrator.");
192 }
193 } else {
194 switch (role) {
195 case CommunitiesModel::Roles::AvatarUrl:
196 return QStringLiteral(":/icons/icons/ui/tag.svg");
197 case CommunitiesModel::Roles::DisplayName:
198 case CommunitiesModel::Roles::Tooltip:
199 return tag.mid(2);
200 }
201 }
202
203 switch (role) {
204 case CommunitiesModel::Roles::Hidden:
205 return hiddenTagIds_.contains("tag:" + tag);
206 case CommunitiesModel::Roles::Collapsed:
207 return true;
208 case CommunitiesModel::Roles::Collapsible:
209 return false;
210 case CommunitiesModel::Roles::Parent:
211 return "";
212 case CommunitiesModel::Roles::Depth:
213 return 0;
214 case CommunitiesModel::Roles::Id:
215 return "tag:" + tag;
216 case CommunitiesModel::Roles::UnreadMessages:
217 if (auto it = tagNotificationCache.find(tag); it != tagNotificationCache.end())
218 return (int)it->second.notification_count;
219 else
220 return 0;
221 case CommunitiesModel::Roles::HasLoudNotification:
222 if (auto it = tagNotificationCache.find(tag); it != tagNotificationCache.end())
223 return it->second.highlight_count > 0;
224 else
225 return 0;
226 }
227 }
228 return QVariant();
229 }
230
231 namespace {
232 struct temptree
233 {
234 std::map<std::string, temptree> children;
235
236 void insert(const std::vector<std::string> &parents, const std::string &child)
237 {
238 temptree *t = this;
239 for (const auto &e : parents)
240 t = &t->children[e];
241 t->children[child];
242 }
243
244 void flatten(CommunitiesModel::FlatTree &to, int i = 0) const
245 {
246 for (const auto &[child, subtree] : children) {
247 to.tree.push_back({QString::fromStdString(child), i, {}, false});
248 subtree.flatten(to, i + 1);
249 }
250 }
251 };
252
253 void
254 addChildren(temptree &t,
255 std::vector<std::string> path,
256 std::string child,
257 const std::map<std::string, std::set<std::string>> &children)
258 {
259 if (std::find(path.begin(), path.end(), child) != path.end())
260 return;
261
262 path.push_back(child);
263
264 if (children.count(child)) {
265 for (const auto &c : children.at(child)) {
266 t.insert(path, c);
267 addChildren(t, path, c, children);
268 }
269 }
270 }
271 }
272
273 void
274 CommunitiesModel::initializeSidebar()
275 {
276 beginResetModel();
277 tags_.clear();
278 spaceOrder_.tree.clear();
279 spaces_.clear();
280 tagNotificationCache.clear();
281 globalUnreads.notification_count = {};
282 dmUnreads.notification_count = {};
283
284 {
285 auto e = cache::client()->getAccountData(mtx::events::EventType::Direct);
286 if (e) {
287 if (auto event =
288 std::get_if<mtx::events::AccountDataEvent<mtx::events::account_data::Direct>>(
289 &e.value())) {
290 directMessages_.clear();
291 for (const auto &[userId, roomIds] : event->content.user_to_rooms)
292 for (const auto &roomId : roomIds)
293 directMessages_.push_back(roomId);
294 }
295 }
296 }
297
298 std::set<std::string> ts;
299
300 std::set<std::string> isSpace;
301 std::map<std::string, std::set<std::string>> spaceChilds;
302 std::map<std::string, std::set<std::string>> spaceParents;
303
304 auto infos = cache::roomInfo();
305 for (auto it = infos.begin(); it != infos.end(); ++it) {
306 if (it.value().is_space) {
307 spaces_[it.key()] = it.value();
308 isSpace.insert(it.key().toStdString());
309 } else {
310 for (const auto &t : it.value().tags) {
311 if (t.find("u.") == 0 || t.find("m." == 0)) {
312 ts.insert(t);
313 }
314 }
315 }
316
317 for (const auto &t : it->tags) {
318 auto tagId = QString::fromStdString(t);
319 auto &tNs = tagNotificationCache[tagId];
320 tNs.notification_count += it->notification_count;
321 tNs.highlight_count += it->highlight_count;
322 }
323
324 auto &e = roomNotificationCache[it.key()];
325 e.highlight_count = it->highlight_count;
326 e.notification_count = it->notification_count;
327 globalUnreads.notification_count += it->notification_count;
328 globalUnreads.highlight_count += it->highlight_count;
329
330 if (std::find(begin(directMessages_), end(directMessages_), it.key().toStdString()) !=
331 end(directMessages_)) {
332 dmUnreads.notification_count += it->notification_count;
333 dmUnreads.highlight_count += it->highlight_count;
334 }
335 }
336
337 // NOTE(Nico): We build a forrest from the Directed Cyclic(!) Graph of spaces. To do that we
338 // start with orphan spaces at the top. This leaves out some space circles, but there is no good
339 // way to break that cycle imo anyway. Then we carefully walk a tree down from each root in our
340 // forrest, carefully checking not to run in a circle and get lost forever.
341 // TODO(Nico): Optimize this. We can do this with a lot fewer allocations and checks.
342 for (const auto &space : isSpace) {
343 spaceParents[space];
344 for (const auto &p : cache::client()->getParentRoomIds(space)) {
345 spaceParents[space].insert(p);
346 spaceChilds[p].insert(space);
347 }
348 }
349
350 temptree spacetree;
351 std::vector<std::string> path;
352 for (const auto &space : isSpace) {
353 if (!spaceParents[space].empty())
354 continue;
355
356 spacetree.children[space] = {};
357 }
358 for (const auto &space : spacetree.children) {
359 addChildren(spacetree, path, space.first, spaceChilds);
360 }
361
362 // NOTE(Nico): This flattens the tree into a list, preserving the depth at each element.
363 spacetree.flatten(spaceOrder_);
364
365 for (const auto &t : ts)
366 tags_.push_back(QString::fromStdString(t));
367
368 spaceOrder_.restoreCollapsed();
369
370 for (auto &space : spaceOrder_.tree) {
371 for (const auto &c : cache::client()->getChildRoomIds(space.id.toStdString())) {
372 const auto &counts = roomNotificationCache[QString::fromStdString(c)];
373 space.notificationCounts.highlight_count += counts.highlight_count;
374 space.notificationCounts.notification_count += counts.notification_count;
375 }
376 }
377
378 endResetModel();
379
380 emit tagsChanged();
381 emit hiddenTagsChanged();
382 emit containsSubspacesChanged();
383
384 setCurrentTagId(UserSettings::instance()->currentTagId());
385 }
386
387 void
388 CommunitiesModel::FlatTree::storeCollapsed()
389 {
390 QList<QStringList> elements;
391
392 int depth = -1;
393
394 QStringList current;
395 elements.reserve(static_cast<int>(tree.size()));
396
397 for (const auto &e : tree) {
398 if (e.depth > depth) {
399 current.push_back(e.id);
400 } else if (e.depth == depth) {
401 current.back() = e.id;
402 } else {
403 current.pop_back();
404 current.back() = e.id;
405 }
406
407 if (e.collapsed)
408 elements.push_back(current);
409 }
410
411 UserSettings::instance()->setCollapsedSpaces(elements);
412 }
413 void
414 CommunitiesModel::FlatTree::restoreCollapsed()
415 {
416 QList<QStringList> elements = UserSettings::instance()->collapsedSpaces();
417
418 int depth = -1;
419
420 QStringList current;
421
422 for (auto &e : tree) {
423 if (e.depth > depth) {
424 current.push_back(e.id);
425 } else if (e.depth == depth) {
426 current.back() = e.id;
427 } else {
428 current.pop_back();
429 current.back() = e.id;
430 }
431
432 if (elements.contains(current))
433 e.collapsed = true;
434 }
435 }
436
437 void
438 CommunitiesModel::clear()
439 {
440 beginResetModel();
441 tags_.clear();
442 endResetModel();
443 resetCurrentTagId();
444
445 emit tagsChanged();
446 }
447
448 void
449 CommunitiesModel::sync(const mtx::responses::Sync &sync_)
450 {
451 bool tagsUpdated = false;
452 const auto userid = http::client()->user_id().to_string();
453
454 for (const auto &[roomid, room] : sync_.rooms.join) {
455 for (const auto &e : room.account_data.events)
456 if (std::holds_alternative<
457 mtx::events::AccountDataEvent<mtx::events::account_data::Tags>>(e)) {
458 tagsUpdated = true;
459 }
460 for (const auto &e : room.state.events) {
461 if (std::holds_alternative<mtx::events::StateEvent<mtx::events::state::space::Child>>(
462 e) ||
463 std::holds_alternative<mtx::events::StateEvent<mtx::events::state::space::Parent>>(
464 e))
465 tagsUpdated = true;
466
467 if (auto ev = std::get_if<mtx::events::StateEvent<mtx::events::state::Member>>(&e);
468 ev && ev->state_key == userid)
469 tagsUpdated = true;
470 }
471 for (const auto &e : room.timeline.events) {
472 if (std::holds_alternative<mtx::events::StateEvent<mtx::events::state::space::Child>>(
473 e) ||
474 std::holds_alternative<mtx::events::StateEvent<mtx::events::state::space::Parent>>(
475 e))
476 tagsUpdated = true;
477
478 if (auto ev = std::get_if<mtx::events::StateEvent<mtx::events::state::Member>>(&e);
479 ev && ev->state_key == userid)
480 tagsUpdated = true;
481 }
482
483 auto roomId = QString::fromStdString(roomid);
484 auto &oldUnreads = roomNotificationCache[roomId];
485 auto notificationCDiff = -static_cast<int64_t>(oldUnreads.notification_count) +
486 static_cast<int64_t>(room.unread_notifications.notification_count);
487 auto highlightCDiff = -static_cast<int64_t>(oldUnreads.highlight_count) +
488 static_cast<int64_t>(room.unread_notifications.highlight_count);
489
490 auto applyDiff = [notificationCDiff,
491 highlightCDiff](mtx::responses::UnreadNotifications &n) {
492 n.highlight_count = static_cast<int64_t>(n.highlight_count) + highlightCDiff;
493 n.notification_count = static_cast<int64_t>(n.notification_count) + notificationCDiff;
494 };
495 if (highlightCDiff || notificationCDiff) {
496 // bool hidden = hiddenTagIds_.contains(roomId);
497 applyDiff(globalUnreads);
498 emit dataChanged(index(0),
499 index(0),
500 {
501 UnreadMessages,
502 HasLoudNotification,
503 });
504 if (std::find(begin(directMessages_), end(directMessages_), roomid) !=
505 end(directMessages_)) {
506 applyDiff(dmUnreads);
507 emit dataChanged(index(1),
508 index(1),
509 {
510 UnreadMessages,
511 HasLoudNotification,
512 });
513 }
514
515 auto spaces = cache::client()->getParentRoomIds(roomid);
516 auto tags = cache::singleRoomInfo(roomid).tags;
517
518 for (const auto &t : tags) {
519 auto tagId = QString::fromStdString(t);
520 applyDiff(tagNotificationCache[tagId]);
521 int idx = tags_.indexOf(tagId) + 2 + spaceOrder_.size();
522 emit dataChanged(index(idx),
523 index(idx),
524 {
525 UnreadMessages,
526 HasLoudNotification,
527 });
528 }
529
530 for (const auto &s : spaces) {
531 auto spaceId = QString::fromStdString(s);
532
533 for (int i = 0; i < spaceOrder_.size(); i++) {
534 if (spaceOrder_.tree[i].id != spaceId)
535 continue;
536
537 applyDiff(spaceOrder_.tree[i].notificationCounts);
538
539 int idx = i;
540 do {
541 emit dataChanged(index(idx + 2),
542 index(idx + 2),
543 {
544 UnreadMessages,
545 HasLoudNotification,
546 });
547 idx = spaceOrder_.parent(idx);
548 } while (idx != -1);
549 }
550 }
551 }
552
553 roomNotificationCache[roomId] = room.unread_notifications;
554 }
555 for (const auto &[roomid, room] : sync_.rooms.leave) {
556 (void)room;
557 if (spaces_.count(QString::fromStdString(roomid)))
558 tagsUpdated = true;
559 if (hiddenTagIds_.contains(QString::fromStdString("space:" + roomid))) {
560 hiddenTagIds_.removeAll(QString::fromStdString("space:" + roomid));
561 UserSettings::instance()->setHiddenTags(hiddenTagIds_);
562 tagsUpdated = true;
563 }
564 }
565 for (const auto &e : sync_.account_data.events) {
566 if (auto event =
567 std::get_if<mtx::events::AccountDataEvent<mtx::events::account_data::Direct>>(&e)) {
568 directMessages_.clear();
569 for (const auto &[userId, roomIds] : event->content.user_to_rooms)
570 for (const auto &roomId : roomIds)
571 directMessages_.push_back(roomId);
572 tagsUpdated = true;
573 break;
574 }
575 }
576
577 if (tagsUpdated)
578 initializeSidebar();
579 }
580
581 void
582 CommunitiesModel::setCurrentTagId(const QString &tagId)
583 {
584 if (currentTagId_ == tagId)
585 return;
586
587 if (tagId.startsWith(QLatin1String("tag:"))) {
588 auto tag = tagId.mid(4);
589 for (const auto &t : std::as_const(tags_)) {
590 if (t == tag) {
591 this->currentTagId_ = tagId;
592 UserSettings::instance()->setCurrentTagId(tagId);
593 emit currentTagIdChanged(currentTagId_);
594 return;
595 }
596 }
597 } else if (tagId.startsWith(QLatin1String("space:"))) {
598 auto tag = tagId.mid(6);
599 for (const auto &t : spaceOrder_.tree) {
600 if (t.id == tag) {
601 this->currentTagId_ = tagId;
602 UserSettings::instance()->setCurrentTagId(tagId);
603 emit currentTagIdChanged(currentTagId_);
604 return;
605 }
606 }
607 } else if (tagId == QLatin1String("dm")) {
608 this->currentTagId_ = tagId;
609 UserSettings::instance()->setCurrentTagId(tagId);
610 emit currentTagIdChanged(currentTagId_);
611 return;
612 }
613
614 this->currentTagId_ = QLatin1String("");
615 UserSettings::instance()->setCurrentTagId(tagId);
616 emit currentTagIdChanged(currentTagId_);
617 }
618
619 bool
620 CommunitiesModel::trySwitchToSpace(const QString &tag)
621 {
622 for (const auto &t : spaceOrder_.tree) {
623 if (t.id == tag) {
624 this->currentTagId_ = "space:" + tag;
625 UserSettings::instance()->setCurrentTagId(tag);
626 emit currentTagIdChanged(currentTagId_);
627 return true;
628 }
629 }
630
631 return false;
632 }
633
634 void
635 CommunitiesModel::toggleTagId(QString tagId)
636 {
637 if (hiddenTagIds_.contains(tagId))
638 hiddenTagIds_.removeOne(tagId);
639 else
640 hiddenTagIds_.push_back(tagId);
641
642 // sanity check to remove stale spaces
643 hiddenTagIds_.removeIf([this](const QString &value) {
644 return value.startsWith("space:") && !spaces_.contains(value.mid(6));
645 });
646
647 UserSettings::instance()->setHiddenTags(hiddenTagIds_);
648
649 if (tagId.startsWith(QLatin1String("tag:"))) {
650 auto idx = tags_.indexOf(tagId.mid(4));
651 if (idx != -1)
652 emit dataChanged(
653 index(idx + 1 + spaceOrder_.size()), index(idx + 1 + spaceOrder_.size()), {Hidden});
654 } else if (tagId.startsWith(QLatin1String("space:"))) {
655 auto idx = spaceOrder_.indexOf(tagId.mid(6));
656 if (idx != -1)
657 emit dataChanged(index(idx + 1), index(idx + 1), {Hidden});
658 } else if (tagId == QLatin1String("dm")) {
659 emit dataChanged(index(1), index(1), {Hidden});
660 }
661
662 emit hiddenTagsChanged();
663 }
664
665 void
666 CommunitiesModel::toggleTagMute(QString tagId)
667 {
668 if (tagId.isEmpty())
669 tagId = QStringLiteral("global");
670
671 if (mutedTagIds_.contains(tagId))
672 mutedTagIds_.removeOne(tagId);
673 else
674 mutedTagIds_.push_back(tagId);
675 UserSettings::instance()->setMutedTags(mutedTagIds_);
676
677 if (tagId.startsWith(QLatin1String("tag:"))) {
678 auto idx = tags_.indexOf(tagId.mid(4));
679 if (idx != -1)
680 emit dataChanged(index(idx + 2 + spaceOrder_.size()),
681 index(idx + 2 + spaceOrder_.size()));
682 } else if (tagId.startsWith(QLatin1String("space:"))) {
683 auto idx = spaceOrder_.indexOf(tagId.mid(6));
684 if (idx != -1)
685 emit dataChanged(index(idx + 2), index(idx + 2));
686 } else if (tagId == QLatin1String("dm")) {
687 emit dataChanged(index(1), index(1));
688 } else if (tagId == QLatin1String("global")) {
689 emit dataChanged(index(0), index(0));
690 }
691 }
692
693 FilteredCommunitiesModel::FilteredCommunitiesModel(CommunitiesModel *model, QObject *parent)
694 : QSortFilterProxyModel(parent)
695 {
696 setSourceModel(model);
697 setDynamicSortFilter(true);
698 sort(0);
699 }
700
701 namespace {
702 enum Categories
703 {
704 World,
705 Direct,
706 Favourites,
707 Server,
708 LowPrio,
709 Space,
710 UserTag,
711 };
712
713 Categories
714 tagIdToCat(const QString &tagId)
715 {
716 if (tagId.isEmpty())
717 return World;
718 else if (tagId == QLatin1String("dm"))
719 return Direct;
720 else if (tagId == QLatin1String("tag:m.favourite"))
721 return Favourites;
722 else if (tagId == QLatin1String("tag:m.server_notice"))
723 return Server;
724 else if (tagId == QLatin1String("tag:m.lowpriority"))
725 return LowPrio;
726 else if (tagId.startsWith(QLatin1String("space:")))
727 return Space;
728 else
729 return UserTag;
730 }
731 }
732
733 bool
734 FilteredCommunitiesModel::lessThan(const QModelIndex &left, const QModelIndex &right) const
735 {
736 QModelIndex const left_idx = sourceModel()->index(left.row(), 0, QModelIndex());
737 QModelIndex const right_idx = sourceModel()->index(right.row(), 0, QModelIndex());
738
739 Categories leftCat = tagIdToCat(sourceModel()->data(left_idx, CommunitiesModel::Id).toString());
740 Categories rightCat =
741 tagIdToCat(sourceModel()->data(right_idx, CommunitiesModel::Id).toString());
742
743 if (leftCat != rightCat)
744 return leftCat < rightCat;
745
746 if (leftCat == Space) {
747 return left.row() < right.row();
748 }
749
750 QString leftName = sourceModel()->data(left_idx, CommunitiesModel::DisplayName).toString();
751 QString rightName = sourceModel()->data(right_idx, CommunitiesModel::DisplayName).toString();
752
753 return leftName.compare(rightName, Qt::CaseInsensitive) < 0;
754 }
755 bool
756 FilteredCommunitiesModel::filterAcceptsRow(int sourceRow, const QModelIndex &) const
757 {
758 CommunitiesModel *m = qobject_cast<CommunitiesModel *>(this->sourceModel());
759 if (!m)
760 return true;
761
762 if (sourceRow < 2 || sourceRow - 2 >= m->spaceOrder_.size())
763 return true;
764
765 auto idx = sourceRow - 2;
766
767 while (idx >= 0 && m->spaceOrder_.tree[idx].depth > 0) {
768 idx = m->spaceOrder_.parent(idx);
769
770 if (idx >= 0 && m->spaceOrder_.tree.at(idx).collapsed)
771 return false;
772 }
773
774 return true;
775 }
776
777 QVariantList
778 CommunitiesModel::spaceChildrenListFromIndex(const QString &room, int idx) const
779 {
780 if (idx < -1)
781 return {};
782
783 auto room_ = room.toStdString();
784
785 int begin = idx + 1;
786 int end = idx >= 0 ? this->spaceOrder_.lastChild(idx) + 1 : this->spaceOrder_.size();
787 QVariantList ret;
788
789 bool canSendParent = Permissions(room).canChange(qml_mtx_events::SpaceParent);
790
791 for (int i = begin; i < end; i++) {
792 const auto &e = spaceOrder_.tree[i];
793 if (e.depth == spaceOrder_.tree[begin].depth && spaces_.count(e.id)) {
794 bool canSendChild = Permissions(e.id).canChange(qml_mtx_events::SpaceChild);
795 // For now hide the space, if we can't send any child, since then the only allowed
796 // action would be removing a space and even that only works if it currently only has a
797 // parent set in the child.
798 if (!canSendChild)
799 continue;
800
801 auto spaceId = e.id.toStdString();
802 auto child =
803 cache::client()->getStateEvent<mtx::events::state::space::Child>(spaceId, room_);
804 auto parent =
805 cache::client()->getStateEvent<mtx::events::state::space::Parent>(room_, spaceId);
806
807 bool childValid =
808 child && !child->content.via.value_or(std::vector<std::string>{}).empty();
809 bool parentValid =
810 parent && !parent->content.via.value_or(std::vector<std::string>{}).empty();
811 bool canonical = parent && parent->content.canonical;
812
813 if (e.id == room) {
814 canonical = parentValid = childValid = canSendChild = canSendParent = false;
815 }
816
817 ret.push_back(
818 QVariant::fromValue(SpaceItem(e.id,
819 QString::fromStdString(spaces_.at(e.id).name),
820 i,
821 childValid,
822 parentValid,
823 canonical,
824 canSendChild,
825 canSendParent)));
826 }
827 }
828
829 // nhlog::ui()->critical("Returning {} spaces", ret.size());
830 return ret;
831 }
832
833 void
834 CommunitiesModel::updateSpaceStatus(QString space,
835 QString room,
836 bool setParent,
837 bool setChild,
838 bool canonical) const
839 {
840 nhlog::ui()->critical("Setting space {} children {}: {} {} {}",
841 space.toStdString(),
842 room.toStdString(),
843 setParent,
844 setChild,
845 canonical);
846 auto child =
847 cache::client()
848 ->getStateEvent<mtx::events::state::space::Child>(space.toStdString(), room.toStdString())
849 .value_or(mtx::events::StateEvent<mtx::events::state::space::Child>{})
850 .content;
851 auto parent =
852 cache::client()
853 ->getStateEvent<mtx::events::state::space::Parent>(room.toStdString(), space.toStdString())
854 .value_or(mtx::events::StateEvent<mtx::events::state::space::Parent>{})
855 .content;
856
857 if (setChild) {
858 if (!child.via || child.via->empty()) {
859 child.via = utils::roomVias(room.toStdString());
860 child.suggested = true;
861
862 http::client()->send_state_event(
863 space.toStdString(),
864 room.toStdString(),
865 child,
866 [space, room](mtx::responses::EventId, mtx::http::RequestErr err) {
867 if (err) {
868 ChatPage::instance()->showNotification(
869 tr("Failed to update community: %1")
870 .arg(QString::fromStdString(err->matrix_error.error)));
871 nhlog::net()->error("Failed to update child {} of {}: {}",
872 room.toStdString(),
873 space.toStdString(),
874 *err);
875 }
876 });
877 }
878 } else {
879 if (child.via && !child.via->empty()) {
880 http::client()->send_state_event(
881 space.toStdString(),
882 room.toStdString(),
883 mtx::events::state::space::Child{},
884 [space, room](mtx::responses::EventId, mtx::http::RequestErr err) {
885 if (err) {
886 ChatPage::instance()->showNotification(
887 tr("Failed to delete room from community: %1")
888 .arg(QString::fromStdString(err->matrix_error.error)));
889 nhlog::net()->error("Failed to delete child {} of {}: {}",
890 room.toStdString(),
891 space.toStdString(),
892 *err);
893 }
894 });
895 }
896 }
897
898 if (setParent) {
899 if (!parent.via || parent.via->empty() || canonical != parent.canonical) {
900 parent.via = utils::roomVias(room.toStdString());
901 parent.canonical = canonical;
902
903 http::client()->send_state_event(
904 room.toStdString(),
905 space.toStdString(),
906 parent,
907 [space, room](mtx::responses::EventId, mtx::http::RequestErr err) {
908 if (err) {
909 ChatPage::instance()->showNotification(
910 tr("Failed to update community for room: %1")
911 .arg(QString::fromStdString(err->matrix_error.error)));
912 nhlog::net()->error("Failed to update parent {} of {}: {}",
913 space.toStdString(),
914 room.toStdString(),
915 *err);
916 }
917 });
918 }
919 } else {
920 if (parent.via && !parent.via->empty()) {
921 http::client()->send_state_event(
922 room.toStdString(),
923 space.toStdString(),
924 mtx::events::state::space::Parent{},
925 [space, room](mtx::responses::EventId, mtx::http::RequestErr err) {
926 if (err) {
927 ChatPage::instance()->showNotification(
928 tr("Failed to remove community from room: %1")
929 .arg(QString::fromStdString(err->matrix_error.error)));
930 nhlog::net()->error("Failed to delete parent {} of {}: {}",
931 space.toStdString(),
932 room.toStdString(),
933 *err);
934 }
935 });
936 }
937 }
938 }
939
940 #include "moc_CommunitiesModel.cpp"