Debian Codegraph @

src/timeline/EventDelegateChooser.cpp

raw symbols SCIP
1 // SPDX-FileCopyrightText: Nheko Contributors
2 //
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
5 #include "EventDelegateChooser.h"
6 #include "TimelineModel.h"
7
8 #include "Logging.h"
9
10 #include <QQmlEngine>
11 #include <QtGlobal>
12
13 #include <ranges>
14
15 // privat qt headers to access required properties
16 #include <QtQml/private/qqmlincubator_p.h>
17 #include <QtQml/private/qqmlobjectcreator_p.h>
18
19 QQmlComponent *
20 EventDelegateChoice::delegate() const
21 {
22 return delegate_;
23 }
24
25 void
26 EventDelegateChoice::setDelegate(QQmlComponent *delegate)
27 {
28 if (delegate != delegate_) {
29 delegate_ = delegate;
30 emit delegateChanged();
31 emit changed();
32 }
33 }
34
35 QList<int>
36 EventDelegateChoice::roleValues() const
37 {
38 return roleValues_;
39 }
40
41 void
42 EventDelegateChoice::setRoleValues(const QList<int> &value)
43 {
44 if (value != roleValues_) {
45 roleValues_ = value;
46 emit roleValuesChanged();
47 emit changed();
48 }
49 }
50
51 QQmlListProperty<EventDelegateChoice>
52 EventDelegateChooser::choices()
53 {
54 return QQmlListProperty<EventDelegateChoice>(this,
55 this,
56 &EventDelegateChooser::appendChoice,
57 &EventDelegateChooser::choiceCount,
58 &EventDelegateChooser::choice,
59 &EventDelegateChooser::clearChoices);
60 }
61
62 void
63 EventDelegateChooser::appendChoice(QQmlListProperty<EventDelegateChoice> *p, EventDelegateChoice *c)
64 {
65 EventDelegateChooser *dc = static_cast<EventDelegateChooser *>(p->object);
66 dc->choices_.append(c);
67 }
68
69 qsizetype
70 EventDelegateChooser::choiceCount(QQmlListProperty<EventDelegateChoice> *p)
71 {
72 return static_cast<EventDelegateChooser *>(p->object)->choices_.count();
73 }
74 EventDelegateChoice *
75 EventDelegateChooser::choice(QQmlListProperty<EventDelegateChoice> *p, qsizetype index)
76 {
77 return static_cast<EventDelegateChooser *>(p->object)->choices_.at(index);
78 }
79 void
80 EventDelegateChooser::clearChoices(QQmlListProperty<EventDelegateChoice> *p)
81 {
82 static_cast<EventDelegateChooser *>(p->object)->choices_.clear();
83 }
84
85 void
86 EventDelegateChooser::componentComplete()
87 {
88 QQuickItem::componentComplete();
89 eventIncubator.reset(eventId_);
90 replyIncubator.reset(replyId);
91 // eventIncubator.forceCompletion();
92 }
93
94 void
95 EventDelegateChooser::DelegateIncubator::setInitialState(QObject *obj)
96 {
97 auto item = qobject_cast<QQuickItem *>(obj);
98 if (!item)
99 return;
100
101 item->setParentItem(&chooser);
102 item->setParent(&chooser);
103
104 auto roleNames = chooser.room_->roleNames();
105 QHash<QByteArray, int> nameToRole;
106 for (const auto &[k, v] : roleNames.asKeyValueRange()) {
107 nameToRole.insert(v, k);
108 }
109
110 QHash<int, int> roleToPropIdx;
111 std::vector<QModelRoleData> roles;
112 // Workaround for https://bugreports.qt.io/browse/QTBUG-98846
113 QHash<QString, RequiredPropertyKey> requiredProperties;
114 for (const auto &[propKey, prop] :
115 QQmlIncubatorPrivate::get(this)->requiredProperties()->asKeyValueRange()) {
116 requiredProperties.insert(prop.propertyName, propKey);
117 }
118
119 // collect required properties
120 auto mo = obj->metaObject();
121 for (int i = 0; i < mo->propertyCount(); i++) {
122 auto prop = mo->property(i);
123 // nhlog::ui()->critical("Found prop {}", prop.name());
124 // See https://bugreports.qt.io/browse/QTBUG-98846
125 if (!prop.isRequired() && !requiredProperties.contains(prop.name()))
126 continue;
127
128 if (auto role = nameToRole.find(prop.name()); role != nameToRole.end()) {
129 roleToPropIdx.insert(*role, i);
130 roles.emplace_back(*role);
131
132 // nhlog::ui()->critical("Found prop {}, idx {}, role {}", prop.name(), i, *role);
133 } else {
134 nhlog::ui()->critical("Required property {} not found in model!", prop.name());
135 }
136 }
137
138 // nhlog::ui()->debug("Querying data for id {}", currentId.toStdString());
139 chooser.room_->multiData(currentId, forReply ? chooser.eventId_ : QString(), roles);
140
141 Qt::beginPropertyUpdateGroup();
142 auto attached = qobject_cast<EventDelegateChooserAttachedType *>(
143 qmlAttachedPropertiesObject<EventDelegateChooser>(obj));
144 Q_ASSERT(attached != nullptr);
145 attached->setIsReply(this->forReply || chooser.limitAsReply_);
146
147 for (const auto &role : roles) {
148 const auto &roleName = roleNames[role.role()];
149 // nhlog::ui()->critical("Setting role {}, {} to {}",
150 // role.role(),
151 // roleName.toStdString(),
152 // role.data().toString().toStdString());
153
154 // nhlog::ui()->critical("Setting {}", mo->property(roleToPropIdx[role.role()]).name());
155 mo->property(roleToPropIdx[role.role()]).write(obj, role.data());
156
157 if (const auto &req = requiredProperties.find(roleName); req != requiredProperties.end())
158 QQmlIncubatorPrivate::get(this)->requiredProperties()->remove(*req);
159 }
160
161 Qt::endPropertyUpdateGroup();
162
163 // setInitialProperties(rolesToSet);
164
165 auto update = [this, obj, roleToPropIdx = std::move(roleToPropIdx)](
166 const QList<int> &changedRoles, TimelineModel *room) {
167 if (!room)
168 return;
169
170 if (changedRoles.empty() || changedRoles.contains(TimelineModel::Roles::Type)) {
171 int type = room
172 ->dataById(currentId,
173 TimelineModel::Roles::Type,
174 forReply ? chooser.eventId_ : QString())
175 .toInt();
176 if (type != oldType) {
177 // nhlog::ui()->debug("Type changed!");
178 reset(currentId);
179 return;
180 }
181 }
182
183 std::vector<QModelRoleData> rolesToRequest;
184
185 if (changedRoles.empty()) {
186 for (const auto role :
187 std::ranges::subrange(roleToPropIdx.keyBegin(), roleToPropIdx.keyEnd()))
188 rolesToRequest.emplace_back(role);
189 } else {
190 for (auto role : changedRoles) {
191 if (roleToPropIdx.contains(role)) {
192 rolesToRequest.emplace_back(role);
193 }
194 }
195 }
196
197 if (rolesToRequest.empty())
198 return;
199
200 auto mo = obj->metaObject();
201 room->multiData(currentId, forReply ? chooser.eventId_ : QString(), rolesToRequest);
202
203 Qt::beginPropertyUpdateGroup();
204 for (const auto &role : rolesToRequest) {
205 mo->property(roleToPropIdx[role.role()]).write(obj, role.data());
206 }
207 Qt::endPropertyUpdateGroup();
208 };
209
210 if (!forReply) {
211 auto row = chooser.room_->idToIndex(currentId);
212 auto connection = connect(
213 chooser.room_,
214 &QAbstractItemModel::dataChanged,
215 obj,
216 [row, update, room = chooser.room_](const QModelIndex &topLeft,
217 const QModelIndex &bottomRight,
218 const QList<int> &changedRoles) {
219 if (row < topLeft.row() || row > bottomRight.row())
220 return;
221
222 update(changedRoles, room);
223 },
224 Qt::QueuedConnection);
225 connect(
226 &this->chooser,
227 &EventDelegateChooser::destroyed,
228 obj,
229 [connection]() { QObject::disconnect(connection); },
230 Qt::SingleShotConnection);
231 connect(
232 &this->chooser,
233 &EventDelegateChooser::roomChanged,
234 obj,
235 [connection]() { QObject::disconnect(connection); },
236 Qt::SingleShotConnection);
237 }
238 }
239
240 void
241 EventDelegateChooser::DelegateIncubator::reset(QString id)
242 {
243 if (!chooser.room_ || id.isEmpty())
244 return;
245
246 // nhlog::ui()->debug("Reset with id {}, reply {}", id.toStdString(), forReply);
247
248 this->currentId = id;
249
250 auto role =
251 chooser.room_
252 ->dataById(id, TimelineModel::Roles::Type, forReply ? chooser.eventId_ : QString())
253 .toInt();
254 this->oldType = role;
255
256 for (const auto choice : std::as_const(chooser.choices_)) {
257 const auto &choiceValue = choice->roleValues();
258 if (choiceValue.contains(role) || choiceValue.empty()) {
259 // nhlog::ui()->debug(
260 // "Instantiating type: {}, c {}", (int)role, choiceValue.contains(role));
261
262 if (auto child = qobject_cast<QQuickItem *>(object())) {
263 child->setParentItem(nullptr);
264 }
265
266 choice->delegate()->create(*this, QQmlEngine::contextForObject(&chooser));
267 return;
268 }
269 }
270 }
271
272 void
273 EventDelegateChooser::DelegateIncubator::statusChanged(QQmlIncubator::Status status)
274 {
275 if (status == QQmlIncubator::Ready) {
276 auto child = qobject_cast<QQuickItem *>(object());
277 if (child == nullptr) {
278 nhlog::ui()->error("Delegate has to be derived of Item!");
279 return;
280 }
281
282 child->setParentItem(&chooser);
283 QQmlEngine::setObjectOwnership(child, QQmlEngine::ObjectOwnership::CppOwnership);
284
285 // connect(child, &QQuickItem::parentChanged, child, [child](QQuickItem *) {
286 // // QTBUG-115687
287 // if (child->flags().testFlag(QQuickItem::ItemObservesViewport)) {
288 // nhlog::ui()->critical("SETTING OBSERVES VIEWPORT");
289 // // Re-trigger the parent traversal to get subtreeTransformChangedEnabled turned
290 // on child->setFlag(QQuickItem::ItemObservesViewport);
291 // }
292 // });
293
294 if (forReply)
295 emit chooser.replyChanged();
296 else
297 emit chooser.mainChanged();
298
299 chooser.polish();
300 } else if (status == QQmlIncubator::Error) {
301 auto errors_ = errors();
302 for (const auto &e : std::as_const(errors_))
303 nhlog::ui()->error("Error instantiating delegate: {}", e.toString().toStdString());
304 }
305 }
306
307 void
308 EventDelegateChooser::updatePolish()
309 {
310 auto mainChild = qobject_cast<QQuickItem *>(eventIncubator.object());
311 auto replyChild = qobject_cast<QQuickItem *>(replyIncubator.object());
312
313 // nhlog::ui()->trace("POLISHING {}", (void *)this);
314
315 auto layoutItem = [this](QQuickItem *item, int inset) {
316 if (item) {
317 QObject::disconnect(item, &QQuickItem::implicitWidthChanged, this, &QQuickItem::polish);
318
319 auto attached = qobject_cast<EventDelegateChooserAttachedType *>(
320 qmlAttachedPropertiesObject<EventDelegateChooser>(item));
321 Q_ASSERT(attached != nullptr);
322
323 int maxWidth = maxWidth_ - inset;
324
325 // in theory we could also reset the width, but that doesn't seem to work nicely for
326 // text areas because of how they cache it.
327 if (attached->maxWidth() > 0)
328 item->setWidth(attached->maxWidth());
329 else
330 item->setWidth(maxWidth);
331 item->ensurePolished();
332 auto width = item->implicitWidth();
333
334 if (width < 1 || width > maxWidth)
335 width = maxWidth;
336
337 if (attached->maxWidth() > 0 && width > attached->maxWidth())
338 width = attached->maxWidth();
339
340 if (attached->keepAspectRatio()) {
341 auto height = width * attached->aspectRatio();
342 if (attached->maxHeight() && height > attached->maxHeight()) {
343 height = attached->maxHeight();
344 width = height / attached->aspectRatio();
345 }
346
347 item->setHeight(height);
348 }
349
350 item->setWidth(width);
351 item->ensurePolished();
352
353 QObject::connect(item, &QQuickItem::implicitWidthChanged, this, &QQuickItem::polish);
354 }
355 };
356
357 layoutItem(mainChild, mainInset_);
358 layoutItem(replyChild, replyInset_);
359 }
360
361 void
362 EventDelegateChooserAttachedType::polishChooser()
363 {
364 auto p = parent();
365 if (p) {
366 auto chooser = qobject_cast<EventDelegateChooser *>(p->parent());
367 if (chooser) {
368 chooser->polish();
369 }
370 }
371 }
372
373 #include "moc_EventDelegateChooser.cpp"