Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qgraphicsanchorlayout_p.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6
7#include <QtWidgets/qwidget.h>
8#include <QtWidgets/qapplication.h>
9#include <QtCore/qstack.h>
10
11#ifdef QT_DEBUG
12#include <QtCore/qfile.h>
13#endif
14
15#include <numeric>
16
17QT_BEGIN_NAMESPACE
18
19using namespace Qt::StringLiterals;
20
21// To ensure that all variables inside the simplex solver are non-negative,
22// we limit the size of anchors in the interval [-limit, limit]. Then before
23// sending them to the simplex solver we add "limit" as an offset, so that
24// they are actually calculated in the interval [0, 2 * limit]
25// To avoid numerical errors in platforms where we use single precision,
26// we use a tighter limit for the variables range.
27const qreal g_offset = (sizeof(qreal) == sizeof(double)) ? QWIDGETSIZE_MAX : QWIDGETSIZE_MAX / 32;
28
29QGraphicsAnchorPrivate::QGraphicsAnchorPrivate(decltype(QObjectPrivateVersion) version)
30 : QObjectPrivate(version), layoutPrivate(nullptr), data(nullptr),
31 sizePolicy(QSizePolicy::Fixed), preferredSize(0),
32 hasSize(true)
33{
34}
35
37{
38 if (data) {
39 // The QGraphicsAnchor was already deleted at this moment. We must clean
40 // the dangling pointer to avoid double deletion in the AnchorData dtor.
41 data->graphicsAnchor = nullptr;
42
43 layoutPrivate->removeAnchor(data->from, data->to);
44 }
45}
46
47void QGraphicsAnchorPrivate::setSizePolicy(QSizePolicy::Policy policy)
48{
49 if (sizePolicy != policy) {
50 sizePolicy = policy;
51 layoutPrivate->q_func()->invalidate();
52 }
53}
54
56{
57 if (!data) {
58 qWarning("QGraphicsAnchor::setSpacing: The anchor does not exist.");
59 return;
60 }
61
62 if (hasSize && (preferredSize == value))
63 return;
64
65 // The anchor has an user-defined size
66 hasSize = true;
67 preferredSize = value;
68
69 layoutPrivate->q_func()->invalidate();
70}
71
73{
74 if (!data) {
75 qWarning("QGraphicsAnchor::setSpacing: The anchor does not exist.");
76 return;
77 }
78
79 // Return to standard direction
80 hasSize = false;
81
82 layoutPrivate->q_func()->invalidate();
83}
84
86{
87 if (!data) {
88 qWarning("QGraphicsAnchor::setSpacing: The anchor does not exist.");
89 return 0;
90 }
91
92 return preferredSize;
93}
94
95
96static void applySizePolicy(QSizePolicy::Policy policy,
97 qreal minSizeHint, qreal prefSizeHint, qreal maxSizeHint,
98 qreal *minSize, qreal *prefSize,
99 qreal *maxSize)
100{
101 // minSize, prefSize and maxSize are initialized
102 // with item's preferred Size: this is QSizePolicy::Fixed.
103 //
104 // Then we check each flag to find the resultant QSizePolicy,
105 // according to the following table:
106 //
107 // constant value
108 // QSizePolicy::Fixed 0
109 // QSizePolicy::Minimum GrowFlag
110 // QSizePolicy::Maximum ShrinkFlag
111 // QSizePolicy::Preferred GrowFlag | ShrinkFlag
112 // QSizePolicy::Ignored GrowFlag | ShrinkFlag | IgnoreFlag
113
114 if (policy & QSizePolicy::ShrinkFlag)
115 *minSize = minSizeHint;
116 else
117 *minSize = prefSizeHint;
118
119 if (policy & QSizePolicy::GrowFlag)
120 *maxSize = maxSizeHint;
121 else
122 *maxSize = prefSizeHint;
123
124 // Note that these two initializations are affected by the previous flags
125 if (policy & QSizePolicy::IgnoreFlag)
126 *prefSize = *minSize;
127 else
128 *prefSize = prefSizeHint;
129}
130
132{
133 if (graphicsAnchor) {
134 // Remove reference to ourself to avoid double removal in
135 // QGraphicsAnchorPrivate dtor.
136 QGraphicsAnchorPrivate::get(graphicsAnchor)->data = nullptr;
137
138 delete graphicsAnchor;
139 }
140}
141
142
144{
145 QSizePolicy::Policy policy;
146 qreal minSizeHint;
147 qreal prefSizeHint;
148 qreal maxSizeHint;
149
150 if (item) {
151 // It is an internal anchor, fetch size information from the item
152 if (isLayoutAnchor) {
153 minSize = 0;
154 prefSize = 0;
155 maxSize = QWIDGETSIZE_MAX;
156 if (isCenterAnchor)
157 maxSize /= 2;
158
159 minPrefSize = prefSize;
160 maxPrefSize = maxSize;
161 return;
162 } else {
163 if (!isVertical) {
164 policy = item->sizePolicy().horizontalPolicy();
165 minSizeHint = item->effectiveSizeHint(Qt::MinimumSize).width();
166 prefSizeHint = item->effectiveSizeHint(Qt::PreferredSize).width();
167 maxSizeHint = item->effectiveSizeHint(Qt::MaximumSize).width();
168 } else {
169 policy = item->sizePolicy().verticalPolicy();
170 minSizeHint = item->effectiveSizeHint(Qt::MinimumSize).height();
171 prefSizeHint = item->effectiveSizeHint(Qt::PreferredSize).height();
172 maxSizeHint = item->effectiveSizeHint(Qt::MaximumSize).height();
173 }
174
175 if (isCenterAnchor) {
176 minSizeHint /= 2;
177 prefSizeHint /= 2;
178 maxSizeHint /= 2;
179 }
180 }
181 } else {
182 // It is a user-created anchor, fetch size information from the associated QGraphicsAnchor
183 Q_ASSERT(graphicsAnchor);
184 QGraphicsAnchorPrivate *anchorPrivate = QGraphicsAnchorPrivate::get(graphicsAnchor);
185
186 // Policy, min and max sizes are straightforward
187 policy = anchorPrivate->sizePolicy;
188 minSizeHint = 0;
189 maxSizeHint = QWIDGETSIZE_MAX;
190
191 // Preferred Size
192 if (anchorPrivate->hasSize) {
193 // Anchor has user-defined size
194 prefSizeHint = anchorPrivate->preferredSize;
195 } else if (styleInfo) {
196 // Fetch size information from style
197 const Qt::Orientation orient = QGraphicsAnchorLayoutPrivate::edgeOrientation(from->m_edge);
198 qreal s = styleInfo->defaultSpacing(orient);
199 if (s < 0) {
200 QSizePolicy::ControlType controlTypeFrom = from->m_item->sizePolicy().controlType();
201 QSizePolicy::ControlType controlTypeTo = to->m_item->sizePolicy().controlType();
202 s = styleInfo->perItemSpacing(controlTypeFrom, controlTypeTo, orient);
203
204 // ### Currently we do not support negative anchors inside the graph.
205 // To avoid those being created by a negative style spacing, we must
206 // make this test.
207 if (s < 0)
208 s = 0;
209 }
210 prefSizeHint = s;
211 } else {
212 prefSizeHint = 0;
213 }
214 }
215
216 // Fill minSize, prefSize and maxSize based on policy and sizeHints
217 applySizePolicy(policy, minSizeHint, prefSizeHint, maxSizeHint,
218 &minSize, &prefSize, &maxSize);
219
220 minPrefSize = prefSize;
221 maxPrefSize = maxSize;
222
223 // Set the anchor effective sizes to preferred.
224 //
225 // Note: The idea here is that all items should remain at their
226 // preferred size unless where that's impossible. In cases where
227 // the item is subject to restrictions (anchored to the layout
228 // edges, for instance), the simplex solver will be run to
229 // recalculate and override the values we set here.
230 sizeAtMinimum = prefSize;
231 sizeAtPreferred = prefSize;
232 sizeAtMaximum = prefSize;
233}
234
236{
237 firstEdge->sizeAtMinimum = sizeAtMinimum;
238 firstEdge->sizeAtPreferred = sizeAtPreferred;
239 firstEdge->sizeAtMaximum = sizeAtMaximum;
240
241 if (secondForward()) {
242 secondEdge->sizeAtMinimum = sizeAtMinimum;
243 secondEdge->sizeAtPreferred = sizeAtPreferred;
244 secondEdge->sizeAtMaximum = sizeAtMaximum;
245 } else {
246 secondEdge->sizeAtMinimum = -sizeAtMinimum;
247 secondEdge->sizeAtPreferred = -sizeAtPreferred;
248 secondEdge->sizeAtMaximum = -sizeAtMaximum;
249 }
250
253}
254
255/*
256 \internal
257
258 Initialize the parallel anchor size hints using the sizeHint information from
259 its children.
260
261 Note that parallel groups can lead to unfeasibility, so during calculation, we can
262 find out one unfeasibility. Because of that this method return boolean. This can't
263 happen in sequential, so there the method is void.
264 */
266{
267 // Normalize second child sizes.
268 // A negative anchor of sizes min, minPref, pref, maxPref and max, is equivalent
269 // to a forward anchor of sizes -max, -maxPref, -pref, -minPref, -min
270 qreal secondMin;
271 qreal secondMinPref;
272 qreal secondPref;
273 qreal secondMaxPref;
274 qreal secondMax;
275
276 if (secondForward()) {
277 secondMin = secondEdge->minSize;
278 secondMinPref = secondEdge->minPrefSize;
279 secondPref = secondEdge->prefSize;
280 secondMaxPref = secondEdge->maxPrefSize;
281 secondMax = secondEdge->maxSize;
282 } else {
283 secondMin = -secondEdge->maxSize;
284 secondMinPref = -secondEdge->maxPrefSize;
285 secondPref = -secondEdge->prefSize;
286 secondMaxPref = -secondEdge->minPrefSize;
287 secondMax = -secondEdge->minSize;
288 }
289
290 minSize = qMax(firstEdge->minSize, secondMin);
291 maxSize = qMin(firstEdge->maxSize, secondMax);
292
293 // This condition means that the maximum size of one anchor being simplified is smaller than
294 // the minimum size of the other anchor. The consequence is that there won't be a valid size
295 // for this parallel setup.
296 if (minSize > maxSize) {
297 return false;
298 }
299
300 // Preferred size calculation
301 // The calculation of preferred size is done as follows:
302 //
303 // 1) Check whether one of the child anchors is the layout structural anchor
304 // If so, we can simply copy the preferred information from the other child,
305 // after bounding it to our minimum and maximum sizes.
306 // If not, then we proceed with the actual calculations.
307 //
308 // 2) The whole algorithm for preferred size calculation is based on the fact
309 // that, if a given anchor cannot remain at its preferred size, it'd rather
310 // grow than shrink.
311 //
312 // What happens though is that while this affirmative is true for simple
313 // anchors, it may not be true for sequential anchors that have one or more
314 // reversed anchors inside it. That happens because when a sequential anchor
315 // grows, any reversed anchors inside it may be required to shrink, something
316 // we try to avoid, as said above.
317 //
318 // To overcome this, besides their actual preferred size "prefSize", each anchor
319 // exports what we call "minPrefSize" and "maxPrefSize". These two values define
320 // a surrounding interval where, if required to move, the anchor would rather
321 // remain inside.
322 //
323 // For standard anchors, this area simply represents the region between
324 // prefSize and maxSize, which makes sense since our first affirmation.
325 // For composed anchors, these values are calculated as to reduce the global
326 // "damage", that is, to reduce the total deviation and the total amount of
327 // anchors that had to shrink.
328
329 if (firstEdge->isLayoutAnchor) {
330 prefSize = qBound(minSize, secondPref, maxSize);
331 minPrefSize = qBound(minSize, secondMinPref, maxSize);
332 maxPrefSize = qBound(minSize, secondMaxPref, maxSize);
333 } else if (secondEdge->isLayoutAnchor) {
334 prefSize = qBound(minSize, firstEdge->prefSize, maxSize);
335 minPrefSize = qBound(minSize, firstEdge->minPrefSize, maxSize);
336 maxPrefSize = qBound(minSize, firstEdge->maxPrefSize, maxSize);
337 } else {
338 // Calculate the intersection between the "preferred" regions of each child
339 const qreal lowerBoundary =
340 qBound(minSize, qMax(firstEdge->minPrefSize, secondMinPref), maxSize);
341 const qreal upperBoundary =
342 qBound(minSize, qMin(firstEdge->maxPrefSize, secondMaxPref), maxSize);
343 const qreal prefMean =
344 qBound(minSize, (firstEdge->prefSize + secondPref) / 2, maxSize);
345
346 if (lowerBoundary < upperBoundary) {
347 // If there is an intersection between the two regions, this intersection
348 // will be used as the preferred region of the parallel anchor itself.
349 // The preferred size will be the bounded average between the two preferred
350 // sizes.
351 prefSize = qBound(lowerBoundary, prefMean, upperBoundary);
352 minPrefSize = lowerBoundary;
353 maxPrefSize = upperBoundary;
354 } else {
355 // If there is no intersection, we have to attribute "damage" to at least
356 // one of the children. The minimum total damage is achieved in points
357 // inside the region that extends from (1) the upper boundary of the lower
358 // region to (2) the lower boundary of the upper region.
359 // Then, we expose this region as _our_ preferred region and once again,
360 // use the bounded average as our preferred size.
361 prefSize = qBound(upperBoundary, prefMean, lowerBoundary);
362 minPrefSize = upperBoundary;
363 maxPrefSize = lowerBoundary;
364 }
365 }
366
367 // See comment in AnchorData::refreshSizeHints() about sizeAt* values
368 sizeAtMinimum = prefSize;
369 sizeAtPreferred = prefSize;
370 sizeAtMaximum = prefSize;
371
372 return true;
373}
374
375/*!
376 \internal
377 returns the factor in the interval [-1, 1].
378 -1 is at Minimum
379 0 is at Preferred
380 1 is at Maximum
381*/
383 qreal minPref, qreal pref,
384 qreal maxPref, qreal max)
385{
386 QGraphicsAnchorLayoutPrivate::Interval interval;
387 qreal lower;
388 qreal upper;
389
390 if (value < minPref) {
391 interval = QGraphicsAnchorLayoutPrivate::MinimumToMinPreferred;
392 lower = min;
393 upper = minPref;
394 } else if (value < pref) {
395 interval = QGraphicsAnchorLayoutPrivate::MinPreferredToPreferred;
396 lower = minPref;
397 upper = pref;
398 } else if (value < maxPref) {
399 interval = QGraphicsAnchorLayoutPrivate::PreferredToMaxPreferred;
400 lower = pref;
401 upper = maxPref;
402 } else {
403 interval = QGraphicsAnchorLayoutPrivate::MaxPreferredToMaximum;
404 lower = maxPref;
405 upper = max;
406 }
407
408 qreal progress;
409 if (upper == lower) {
410 progress = 0;
411 } else {
412 progress = (value - lower) / (upper - lower);
413 }
414
415 return std::pair(interval, progress);
416}
417
418static qreal interpolate(const std::pair<QGraphicsAnchorLayoutPrivate::Interval, qreal> &factor,
419 qreal min, qreal minPref, qreal pref, qreal maxPref, qreal max)
420{
421 qreal lower = 0;
422 qreal upper = 0;
423
424 switch (factor.first) {
425 case QGraphicsAnchorLayoutPrivate::MinimumToMinPreferred:
426 lower = min;
427 upper = minPref;
428 break;
429 case QGraphicsAnchorLayoutPrivate::MinPreferredToPreferred:
430 lower = minPref;
431 upper = pref;
432 break;
433 case QGraphicsAnchorLayoutPrivate::PreferredToMaxPreferred:
434 lower = pref;
435 upper = maxPref;
436 break;
437 case QGraphicsAnchorLayoutPrivate::MaxPreferredToMaximum:
438 lower = maxPref;
439 upper = max;
440 break;
441 }
442
443 return lower + factor.second * (upper - lower);
444}
445
447{
448 // Band here refers if the value is in the Minimum To Preferred
449 // band (the lower band) or the Preferred To Maximum (the upper band).
450
451 const std::pair<QGraphicsAnchorLayoutPrivate::Interval, qreal> minFactor =
452 getFactor(sizeAtMinimum, minSize, minPrefSize, prefSize, maxPrefSize, maxSize);
453 const std::pair<QGraphicsAnchorLayoutPrivate::Interval, qreal> prefFactor =
454 getFactor(sizeAtPreferred, minSize, minPrefSize, prefSize, maxPrefSize, maxSize);
455 const std::pair<QGraphicsAnchorLayoutPrivate::Interval, qreal> maxFactor =
456 getFactor(sizeAtMaximum, minSize, minPrefSize, prefSize, maxPrefSize, maxSize);
457
458 // XXX This is not safe if Vertex simplification takes place after the sequential
459 // anchor is created. In that case, "prev" will be a group-vertex, different from
460 // "from" or "to", that _contains_ one of them.
461 AnchorVertex *prev = from;
462
463 for (AnchorData *e : m_edges) {
464 const bool edgeIsForward = (e->from == prev);
465 if (edgeIsForward) {
466 e->sizeAtMinimum = interpolate(minFactor, e->minSize, e->minPrefSize,
467 e->prefSize, e->maxPrefSize, e->maxSize);
468 e->sizeAtPreferred = interpolate(prefFactor, e->minSize, e->minPrefSize,
469 e->prefSize, e->maxPrefSize, e->maxSize);
470 e->sizeAtMaximum = interpolate(maxFactor, e->minSize, e->minPrefSize,
471 e->prefSize, e->maxPrefSize, e->maxSize);
472 prev = e->to;
473 } else {
474 Q_ASSERT(prev == e->to);
475 e->sizeAtMinimum = interpolate(minFactor, e->maxSize, e->maxPrefSize,
476 e->prefSize, e->minPrefSize, e->minSize);
477 e->sizeAtPreferred = interpolate(prefFactor, e->maxSize, e->maxPrefSize,
478 e->prefSize, e->minPrefSize, e->minSize);
479 e->sizeAtMaximum = interpolate(maxFactor, e->maxSize, e->maxPrefSize,
480 e->prefSize, e->minPrefSize, e->minSize);
481 prev = e->from;
482 }
483
484 e->updateChildrenSizes();
485 }
486}
487
489{
490 minSize = 0;
491 prefSize = 0;
492 maxSize = 0;
493 minPrefSize = 0;
494 maxPrefSize = 0;
495
496 AnchorVertex *prev = from;
497
498 for (AnchorData *edge : m_edges) {
499 const bool edgeIsForward = (edge->from == prev);
500 if (edgeIsForward) {
501 minSize += edge->minSize;
502 prefSize += edge->prefSize;
503 maxSize += edge->maxSize;
504 minPrefSize += edge->minPrefSize;
505 maxPrefSize += edge->maxPrefSize;
506 prev = edge->to;
507 } else {
508 Q_ASSERT(prev == edge->to);
509 minSize -= edge->maxSize;
510 prefSize -= edge->prefSize;
511 maxSize -= edge->minSize;
512 minPrefSize -= edge->maxPrefSize;
513 maxPrefSize -= edge->minPrefSize;
514 prev = edge->from;
515 }
516 }
517
518 // See comment in AnchorData::refreshSizeHints() about sizeAt* values
519 sizeAtMinimum = prefSize;
520 sizeAtPreferred = prefSize;
521 sizeAtMaximum = prefSize;
522}
523
524#ifdef QT_DEBUG
525void AnchorData::dump(int indent) {
526 if (type == Parallel) {
527 qDebug("%*s type: parallel:", indent, "");
528 ParallelAnchorData *p = static_cast<ParallelAnchorData *>(this);
529 p->firstEdge->dump(indent+2);
530 p->secondEdge->dump(indent+2);
531 } else if (type == Sequential) {
532 const auto *s = static_cast<SequentialAnchorData *>(this);
533 qDebug("%*s type: sequential(%lld):", indent, "", qint64(s->m_edges.size()));
534 for (AnchorData *e : s->m_edges)
535 e->dump(indent + 2);
536 } else {
537 qDebug("%*s type: Normal:", indent, "");
538 }
539}
540
541#endif
542
544{
545 // Calculate
546 QSet<AnchorData *> cPositives;
547 QSet<AnchorData *> cNegatives;
548 QSet<AnchorData *> intersection;
549
550 cPositives = positives + path.negatives;
551 cNegatives = negatives + path.positives;
552
553 intersection = cPositives & cNegatives;
554
555 cPositives -= intersection;
556 cNegatives -= intersection;
557
558 // Fill
560 for (AnchorData *ad : std::as_const(cPositives))
561 c->variables.insert(ad, 1.0);
562
563 for (AnchorData *ad : std::as_const(cNegatives))
564 c->variables.insert(ad, -1.0);
565
566 return c;
567}
568
569#ifdef QT_DEBUG
570QString GraphPath::toString() const
571{
572 QString string;
573 string += "Path: "_L1;
574
575 for (AnchorData *edge : positives)
576 string += QString::fromLatin1(" (+++) %1").arg(edge->toString());
577
578 for (AnchorData *edge : negatives)
579 string += QString::fromLatin1(" (---) %1").arg(edge->toString());
580
581 return string;
582}
583#endif
584
585QGraphicsAnchorLayoutPrivate::QGraphicsAnchorLayoutPrivate()
586 : calculateGraphCacheDirty(true), styleInfoDirty(true)
587{
588}
589
590Qt::AnchorPoint QGraphicsAnchorLayoutPrivate::oppositeEdge(Qt::AnchorPoint edge)
591{
592 switch (edge) {
593 case Qt::AnchorLeft:
594 edge = Qt::AnchorRight;
595 break;
596 case Qt::AnchorRight:
597 edge = Qt::AnchorLeft;
598 break;
599 case Qt::AnchorTop:
600 edge = Qt::AnchorBottom;
601 break;
602 case Qt::AnchorBottom:
603 edge = Qt::AnchorTop;
604 break;
605 default:
606 break;
607 }
608 return edge;
609}
610
611
612/*!
613 \internal
614
615 Adds \a newAnchor to the graph.
616
617 Returns the newAnchor itself if it could be added without further changes to the graph. If a
618 new parallel anchor had to be created, then returns the new parallel anchor. If a parallel anchor
619 had to be created and it results in an unfeasible setup, \a feasible is set to false, otherwise
620 true.
621
622 Note that in the case a new parallel anchor is created, it might also take over some constraints
623 from its children anchors.
624*/
625AnchorData *QGraphicsAnchorLayoutPrivate::addAnchorMaybeParallel(AnchorData *newAnchor, bool *feasible)
626{
627 const Qt::Orientation orientation = newAnchor->isVertical ? Qt::Vertical : Qt::Horizontal;
628 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
629 *feasible = true;
630
631 // If already exists one anchor where newAnchor is supposed to be, we create a parallel
632 // anchor.
633 if (AnchorData *oldAnchor = g.takeEdge(newAnchor->from, newAnchor->to)) {
634 ParallelAnchorData *parallel = new ParallelAnchorData(oldAnchor, newAnchor);
635
636 // The parallel anchor will "replace" its children anchors in
637 // every center constraint that they appear.
638
639 // ### If the dependent (center) anchors had reference(s) to their constraints, we
640 // could avoid traversing all the itemCenterConstraints.
641 QList<QSimplexConstraint *> &constraints = itemCenterConstraints[orientation];
642 const std::array<AnchorData *, 2> children = { oldAnchor, newAnchor };
643 const std::array<QList<QSimplexConstraint *> *, 2> childrenConstraints = {
644 &parallel->m_firstConstraints, &parallel->m_secondConstraints
645 };
646
647 for (int i = 0; i < 2; ++i) {
648 AnchorData *child = children[i];
649 QList<QSimplexConstraint *> *childConstraints = childrenConstraints[i];
650
651 // We need to fix the second child constraints if the parallel group will have the
652 // opposite direction of the second child anchor. For the point of view of external
653 // entities, this anchor was reversed. So if at some point we say that the parallel
654 // has a value of 20, this mean that the second child (when reversed) will be
655 // assigned -20.
656 const bool needsReverse = i == 1 && !parallel->secondForward();
657
658 if (!child->isCenterAnchor)
659 continue;
660
661 parallel->isCenterAnchor = true;
662
663 for (QSimplexConstraint *c : constraints) {
664 if (c->variables.contains(child)) {
665 childConstraints->append(c);
666 qreal v = c->variables.take(child);
667 if (needsReverse)
668 v *= -1;
669 c->variables.insert(parallel, v);
670 }
671 }
672 }
673
674 // At this point we can identify that the parallel anchor is not feasible, e.g. one
675 // anchor minimum size is bigger than the other anchor maximum size.
676 *feasible = parallel->calculateSizeHints();
677 newAnchor = parallel;
678 }
679
680 g.createEdge(newAnchor->from, newAnchor->to, newAnchor);
681 return newAnchor;
682}
683
684/*!
685 \internal
686
687 Takes the sequence of vertices described by (\a before, \a vertices, \a after) and removes
688 all anchors connected to the vertices in \a vertices, returning one simplified anchor between
689 \a before and \a after.
690
691 Note that this function doesn't add the created anchor to the graph. This should be done by
692 the caller.
693*/
694static AnchorData *createSequence(Graph<AnchorVertex, AnchorData> *graph, AnchorVertex *before,
695 const QList<AnchorVertex *> &vertices, AnchorVertex *after)
696{
697#if defined(QT_DEBUG) && 0
698 QString strVertices;
699 for (const AnchorVertex *vertex : vertices)
700 strVertices += QString::fromLatin1("%1 - ").arg(vertex->toString());
701 QString strPath = QString::fromLatin1("%1 - %2%3").arg(before->toString(), strVertices, after->toString());
702 qDebug("simplifying [%s] to [%s - %s]", qPrintable(strPath), qPrintable(before->toString()), qPrintable(after->toString()));
703#endif
704
705 AnchorVertex *prev = before;
706 QList<AnchorData *> edges;
707 edges.reserve(vertices.size() + 1);
708
709 // Take from the graph, the edges that will be simplificated
710 for (AnchorVertex *next : vertices) {
711 AnchorData *ad = graph->takeEdge(prev, next);
712 Q_ASSERT(ad);
713 edges.append(ad);
714 prev = next;
715 }
716
717 // Take the last edge (not covered in the loop above)
718 AnchorData *ad = graph->takeEdge(vertices.last(), after);
719 Q_ASSERT(ad);
720 edges.append(ad);
721
722 // Create sequence
723 SequentialAnchorData *sequence = new SequentialAnchorData(vertices, edges);
724 sequence->from = before;
725 sequence->to = after;
726
728
729 return sequence;
730}
731
732/*!
733 \internal
734
735 The purpose of this function is to simplify the graph.
736 Simplification serves two purposes:
737 1. Reduce the number of edges in the graph, (thus the number of variables to the equation
738 solver is reduced, and the solver performs better).
739 2. Be able to do distribution of sequences of edges more intelligently (esp. with sequential
740 anchors)
741
742 It is essential that it must be possible to restore simplified anchors back to their "original"
743 form. This is done by restoreSimplifiedAnchor().
744
745 There are two types of simplification that can be done:
746 1. Sequential simplification
747 Sequential simplification means that all sequences of anchors will be merged into one single
748 anchor. Only anhcors that points in the same direction will be merged.
749 2. Parallel simplification
750 If a simplified sequential anchor is about to be inserted between two vertices in the graph
751 and there already exist an anchor between those two vertices, a parallel anchor will be
752 created that serves as a placeholder for the sequential anchor and the anchor that was
753 already between the two vertices.
754
755 The process of simplification can be described as:
756
757 1. Simplify all sequences of anchors into one anchor.
758 If no further simplification was done, go to (3)
759 - If there already exist an anchor where the sequential anchor is supposed to be inserted,
760 take that anchor out of the graph
761 - Then create a parallel anchor that holds the sequential anchor and the anchor just taken
762 out of the graph.
763 2. Go to (1)
764 3. Done
765
766 When creating the parallel anchors, the algorithm might identify unfeasible situations. In this
767 case the simplification process stops and returns \c false. Otherwise returns \c true.
768*/
769bool QGraphicsAnchorLayoutPrivate::simplifyGraph(Qt::Orientation orientation)
770{
771 if (items.isEmpty())
772 return true;
773
774#if defined(QT_DEBUG) && 0
775 qDebug("Simplifying Graph for %s",
776 orientation == Horizontal ? "Horizontal" : "Vertical");
777
778 static int count = 0;
779 if (orientation == Horizontal) {
780 count++;
781 dumpGraph(QString::fromLatin1("%1-full").arg(count));
782 }
783#endif
784
785 // Vertex simplification
786 if (!simplifyVertices(orientation)) {
787 restoreVertices(orientation);
788 return false;
789 }
790
791 // Anchor simplification
792 bool dirty;
793 bool feasible = true;
794 do {
795 dirty = simplifyGraphIteration(orientation, &feasible);
796 } while (dirty && feasible);
797
798 // Note that if we are not feasible, we fallback and make sure that the graph is fully restored
799 if (!feasible) {
800 restoreSimplifiedGraph(orientation);
801 restoreVertices(orientation);
802 return false;
803 }
804
805#if defined(QT_DEBUG) && 0
806 dumpGraph(QString::fromLatin1("%1-simplified-%2").arg(count).arg(
807 QString::fromLatin1(orientation == Horizontal ? "Horizontal" : "Vertical")));
808#endif
809
810 return true;
811}
812
814{
815 AnchorVertex *other;
816 if (data->from == oldV) {
817 data->from = newV;
818 other = data->to;
819 } else {
820 data->to = newV;
821 other = data->from;
822 }
823 return other;
824}
825
826bool QGraphicsAnchorLayoutPrivate::replaceVertex(Qt::Orientation orientation, AnchorVertex *oldV,
827 AnchorVertex *newV, const QList<AnchorData *> &edges)
828{
829 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
830 bool feasible = true;
831
832 for (AnchorData *ad : edges) {
833 AnchorVertex *otherV = replaceVertex_helper(ad, oldV, newV);
834
835#if defined(QT_DEBUG)
836 ad->name = QString::fromLatin1("%1 --to--> %2").arg(ad->from->toString(), ad->to->toString());
837#endif
838
839 bool newFeasible;
840 AnchorData *newAnchor = addAnchorMaybeParallel(ad, &newFeasible);
841 feasible &= newFeasible;
842
843 if (newAnchor != ad) {
844 // A parallel was created, we mark that in the list of anchors created by vertex
845 // simplification. This is needed because we want to restore them in a separate step
846 // from the restoration of anchor simplification.
847 anchorsFromSimplifiedVertices[orientation].append(newAnchor);
848 }
849
850 g.takeEdge(oldV, otherV);
851 }
852
853 return feasible;
854}
855
856/*!
857 \internal
858*/
859bool QGraphicsAnchorLayoutPrivate::simplifyVertices(Qt::Orientation orientation)
860{
861 Q_Q(QGraphicsAnchorLayout);
862 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
863
864 // We'll walk through vertices
865 QStack<AnchorVertex *> stack;
866 stack.push(layoutFirstVertex[orientation]);
867 QSet<AnchorVertex *> visited;
868
869 while (!stack.isEmpty()) {
870 AnchorVertex *v = stack.pop();
871 visited.insert(v);
872
873 // Each adjacent of 'v' is a possible vertex to be merged. So we traverse all of
874 // them. Since once a merge is made, we might add new adjacents, and we don't want to
875 // pass two times through one adjacent. The 'index' is used to track our position.
876 QList<AnchorVertex *> adjacents = g.adjacentVertices(v);
877 int index = 0;
878
879 while (index < adjacents.size()) {
880 AnchorVertex *next = adjacents.at(index);
881 index++;
882
883 AnchorData *data = g.edgeData(v, next);
884 const bool bothLayoutVertices = v->m_item == q && next->m_item == q;
885 const bool zeroSized = !data->minSize && !data->maxSize;
886
887 if (!bothLayoutVertices && zeroSized) {
888
889 // Create a new vertex pair, note that we keep a list of those vertices so we can
890 // easily process them when restoring the graph.
891 AnchorVertexPair *newV = new AnchorVertexPair(v, next, data);
892 simplifiedVertices[orientation].append(newV);
893
894 // Collect the anchors of both vertices, the new vertex pair will take their place
895 // in those anchors
896 const QList<AnchorVertex *> &vAdjacents = g.adjacentVertices(v);
897 const QList<AnchorVertex *> &nextAdjacents = g.adjacentVertices(next);
898
899 for (AnchorVertex *adjacent : vAdjacents) {
900 if (adjacent != next) {
901 AnchorData *ad = g.edgeData(v, adjacent);
902 newV->m_firstAnchors.append(ad);
903 }
904 }
905
906 for (AnchorVertex *adjacent : nextAdjacents) {
907 if (adjacent != v) {
908 AnchorData *ad = g.edgeData(next, adjacent);
909 newV->m_secondAnchors.append(ad);
910
911 // We'll also add new vertices to the adjacent list of the new 'v', to be
912 // created as a vertex pair and replace the current one.
913 if (!adjacents.contains(adjacent))
914 adjacents.append(adjacent);
915 }
916 }
917
918 // ### merge this loop into the ones that calculated m_firstAnchors/m_secondAnchors?
919 // Make newV take the place of v and next
920 bool feasible = replaceVertex(orientation, v, newV, newV->m_firstAnchors);
921 feasible &= replaceVertex(orientation, next, newV, newV->m_secondAnchors);
922
923 // Update the layout vertex information if one of the vertices is a layout vertex.
924 AnchorVertex *layoutVertex = nullptr;
925 if (v->m_item == q)
926 layoutVertex = v;
927 else if (next->m_item == q)
928 layoutVertex = next;
929
930 if (layoutVertex) {
931 // Layout vertices always have m_item == q...
932 newV->m_item = q;
933 changeLayoutVertex(orientation, layoutVertex, newV);
934 }
935
936 g.takeEdge(v, next);
937
938 // If a non-feasibility is found, we leave early and cancel the simplification
939 if (!feasible)
940 return false;
941
942 v = newV;
943 visited.insert(newV);
944
945 } else if (!visited.contains(next) && !stack.contains(next)) {
946 // If the adjacent is not fit for merge and it wasn't visited by the outermost
947 // loop, we add it to the stack.
948 stack.push(next);
949 }
950 }
951 }
952
953 return true;
954}
955
956/*!
957 \internal
958
959 One iteration of the simplification algorithm. Returns \c true if another iteration is needed.
960
961 The algorithm walks the graph in depth-first order, and only collects vertices that has two
962 edges connected to it. If the vertex does not have two edges or if it is a layout edge, it
963 will take all the previously collected vertices and try to create a simplified sequential
964 anchor representing all the previously collected vertices. Once the simplified anchor is
965 inserted, the collected list is cleared in order to find the next sequence to simplify.
966
967 Note that there are some catches to this that are not covered by the above explanation, see
968 the function comments for more details.
969*/
970bool QGraphicsAnchorLayoutPrivate::simplifyGraphIteration(Qt::Orientation orientation,
971 bool *feasible)
972{
973 Q_Q(QGraphicsAnchorLayout);
974 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
975
976 QSet<AnchorVertex *> visited;
977 QStack<std::pair<AnchorVertex *, AnchorVertex *> > stack;
978 stack.push(std::pair(static_cast<AnchorVertex *>(nullptr), layoutFirstVertex[orientation]));
979 QList<AnchorVertex *> candidates;
980
981 // Walk depth-first, in the stack we store start of the candidate sequence (beforeSequence)
982 // and the vertex to be visited.
983 while (!stack.isEmpty()) {
984 std::pair<AnchorVertex *, AnchorVertex *> pair = stack.pop();
985 AnchorVertex *beforeSequence = pair.first;
986 AnchorVertex *v = pair.second;
987
988 // The basic idea is to determine whether we found an end of sequence,
989 // if that's the case, we stop adding vertices to the candidate list
990 // and do a simplification step.
991 //
992 // A vertex can trigger an end of sequence if
993 // (a) it is a layout vertex, we don't simplify away the layout vertices;
994 // (b) it does not have exactly 2 adjacents;
995 // (c) its next adjacent is already visited (a cycle in the graph).
996 // (d) the next anchor is a center anchor.
997
998 const QList<AnchorVertex *> &adjacents = g.adjacentVertices(v);
999 const bool isLayoutVertex = v->m_item == q;
1000 AnchorVertex *afterSequence = v;
1001 bool endOfSequence = false;
1002
1003 //
1004 // Identify the end cases.
1005 //
1006
1007 // Identifies cases (a) and (b)
1008 endOfSequence = isLayoutVertex || adjacents.size() != 2;
1009
1010 if (!endOfSequence) {
1011 // This is a tricky part. We peek at the next vertex to find out whether
1012 //
1013 // - we already visited the next vertex (c);
1014 // - the next anchor is a center (d).
1015 //
1016 // Those are needed to identify the remaining end of sequence cases. Note that unlike
1017 // (a) and (b), we preempt the end of sequence by looking into the next vertex.
1018
1019 // Peek at the next vertex
1020 AnchorVertex *after;
1021 if (candidates.isEmpty())
1022 after = (beforeSequence == adjacents.last() ? adjacents.first() : adjacents.last());
1023 else
1024 after = (candidates.constLast() == adjacents.last() ? adjacents.first() : adjacents.last());
1025
1026 // ### At this point we assumed that candidates will not contain 'after', this may not hold
1027 // when simplifying FLOATing anchors.
1028 Q_ASSERT(!candidates.contains(after));
1029
1030 const AnchorData *data = g.edgeData(v, after);
1031 Q_ASSERT(data);
1032 const bool cycleFound = visited.contains(after);
1033
1034 // Now cases (c) and (d)...
1035 endOfSequence = cycleFound || data->isCenterAnchor;
1036
1037 if (!endOfSequence) {
1038 // If it's not an end of sequence, then the vertex didn't trigger neither of the
1039 // previously three cases, so it can be added to the candidates list.
1040 candidates.append(v);
1041 } else if (cycleFound && (beforeSequence != after)) {
1042 afterSequence = after;
1043 candidates.append(v);
1044 }
1045 }
1046
1047 //
1048 // Add next non-visited vertices to the stack.
1049 //
1050 for (AnchorVertex *next : adjacents) {
1051 if (visited.contains(next))
1052 continue;
1053
1054 // If current vertex is an end of sequence, and it'll reset the candidates list. So
1055 // the next vertices will build candidates lists with the current vertex as 'before'
1056 // vertex. If it's not an end of sequence, we keep the original 'before' vertex,
1057 // since we are keeping the candidates list.
1058 if (endOfSequence)
1059 stack.push(std::pair(v, next));
1060 else
1061 stack.push(std::pair(beforeSequence, next));
1062 }
1063
1064 visited.insert(v);
1065
1066 if (!endOfSequence || candidates.isEmpty())
1067 continue;
1068
1069 //
1070 // Create a sequence for (beforeSequence, candidates, afterSequence).
1071 //
1072
1073 // One restriction we have is to not simplify half of an anchor and let the other half
1074 // unsimplified. So we remove center edges before and after the sequence.
1075 const AnchorData *firstAnchor = g.edgeData(beforeSequence, candidates.constFirst());
1076 if (firstAnchor->isCenterAnchor) {
1077 beforeSequence = candidates.constFirst();
1078 candidates.remove(0);
1079
1080 // If there's not candidates to be simplified, leave.
1081 if (candidates.isEmpty())
1082 continue;
1083 }
1084
1085 const AnchorData *lastAnchor = g.edgeData(candidates.constLast(), afterSequence);
1086 if (lastAnchor->isCenterAnchor) {
1087 afterSequence = candidates.constLast();
1088 candidates.remove(candidates.size() - 1);
1089
1090 if (candidates.isEmpty())
1091 continue;
1092 }
1093
1094 //
1095 // Add the sequence to the graph.
1096 //
1097
1098 AnchorData *sequence = createSequence(&g, beforeSequence, candidates, afterSequence);
1099
1100 // If 'beforeSequence' and 'afterSequence' already had an anchor between them, we'll
1101 // create a parallel anchor between the new sequence and the old anchor.
1102 bool newFeasible;
1103 AnchorData *newAnchor = addAnchorMaybeParallel(sequence, &newFeasible);
1104
1105 if (!newFeasible) {
1106 *feasible = false;
1107 return false;
1108 }
1109
1110 // When a new parallel anchor is create in the graph, we finish the iteration and return
1111 // true to indicate a new iteration is needed. This happens because a parallel anchor
1112 // changes the number of adjacents one vertex has, possibly opening up oportunities for
1113 // building candidate lists (when adjacents == 2).
1114 if (newAnchor != sequence)
1115 return true;
1116
1117 // If there was no parallel simplification, we'll keep walking the graph. So we clear the
1118 // candidates list to start again.
1119 candidates.clear();
1120 }
1121
1122 return false;
1123}
1124
1125void QGraphicsAnchorLayoutPrivate::restoreSimplifiedAnchor(AnchorData *edge)
1126{
1127 const Qt::Orientation orientation = edge->isVertical ? Qt::Vertical : Qt::Horizontal;
1128#if 0
1129 static const char *anchortypes[] = {"Normal",
1130 "Sequential",
1131 "Parallel"};
1132 qDebug("Restoring %s edge.", anchortypes[int(edge->type)]);
1133#endif
1134
1135 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
1136
1137 if (edge->type == AnchorData::Normal) {
1138 g.createEdge(edge->from, edge->to, edge);
1139
1140 } else if (edge->type == AnchorData::Sequential) {
1141 const auto *sequence = static_cast<SequentialAnchorData *>(edge);
1142
1143 for (AnchorData *data : sequence->m_edges)
1144 restoreSimplifiedAnchor(data);
1145
1146 delete sequence;
1147
1148 } else if (edge->type == AnchorData::Parallel) {
1149
1150 // Skip parallel anchors that were created by vertex simplification, they will be processed
1151 // later, when restoring vertex simplification.
1152 // ### we could improve this check bit having a bit inside 'edge'
1153 if (anchorsFromSimplifiedVertices[orientation].contains(edge))
1154 return;
1155
1156 ParallelAnchorData* parallel = static_cast<ParallelAnchorData*>(edge);
1157 restoreSimplifiedConstraints(parallel);
1158
1159 // ### Because of the way parallel anchors are created in the anchor simplification
1160 // algorithm, we know that one of these will be a sequence, so it'll be safe if the other
1161 // anchor create an edge between the same vertices as the parallel.
1162 Q_ASSERT(parallel->firstEdge->type == AnchorData::Sequential
1163 || parallel->secondEdge->type == AnchorData::Sequential);
1164 restoreSimplifiedAnchor(parallel->firstEdge);
1165 restoreSimplifiedAnchor(parallel->secondEdge);
1166
1167 delete parallel;
1168 }
1169}
1170
1171void QGraphicsAnchorLayoutPrivate::restoreSimplifiedConstraints(ParallelAnchorData *parallel)
1172{
1173 if (!parallel->isCenterAnchor)
1174 return;
1175
1176 for (QSimplexConstraint *c : std::as_const(parallel->m_firstConstraints)) {
1177 qreal v = c->variables[parallel];
1178 c->variables.remove(parallel);
1179 c->variables.insert(parallel->firstEdge, v);
1180 }
1181
1182 // When restoring, we might have to revert constraints back. See comments on
1183 // addAnchorMaybeParallel().
1184 const bool needsReverse = !parallel->secondForward();
1185
1186 for (QSimplexConstraint *c : std::as_const(parallel->m_secondConstraints)) {
1187 qreal v = c->variables[parallel];
1188 if (needsReverse)
1189 v *= -1;
1190 c->variables.remove(parallel);
1191 c->variables.insert(parallel->secondEdge, v);
1192 }
1193}
1194
1195void QGraphicsAnchorLayoutPrivate::restoreSimplifiedGraph(Qt::Orientation orientation)
1196{
1197#if 0
1198 qDebug("Restoring Simplified Graph for %s",
1199 orientation == Horizontal ? "Horizontal" : "Vertical");
1200#endif
1201
1202 // Restore anchor simplification
1203 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
1204 const QList<std::pair<AnchorVertex *, AnchorVertex *>> connections = g.connections();
1205 for (const auto &connection : connections) {
1206 AnchorVertex *v1 = connection.first;
1207 AnchorVertex *v2 = connection.second;
1208 AnchorData *edge = g.edgeData(v1, v2);
1209
1210 // We restore only sequential anchors and parallels that were not created by
1211 // vertex simplification.
1212 if (edge->type == AnchorData::Sequential
1213 || (edge->type == AnchorData::Parallel &&
1214 !anchorsFromSimplifiedVertices[orientation].contains(edge))) {
1215
1216 g.takeEdge(v1, v2);
1217 restoreSimplifiedAnchor(edge);
1218 }
1219 }
1220
1221 restoreVertices(orientation);
1222}
1223
1224void QGraphicsAnchorLayoutPrivate::restoreVertices(Qt::Orientation orientation)
1225{
1226 Q_Q(QGraphicsAnchorLayout);
1227
1228 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
1229 QList<AnchorVertexPair *> &toRestore = simplifiedVertices[orientation];
1230
1231 // Since we keep a list of parallel anchors and vertices that were created during vertex
1232 // simplification, we can now iterate on those lists instead of traversing the graph
1233 // recursively.
1234
1235 // First, restore the constraints changed when we created parallel anchors. Note that this
1236 // works at this point because the constraints doesn't depend on vertex information and at
1237 // this point it's always safe to identify whether the second child is forward or backwards.
1238 // In the next step, we'll change the anchors vertices so that would not be possible anymore.
1239 QList<AnchorData *> &parallelAnchors = anchorsFromSimplifiedVertices[orientation];
1240
1241 for (auto it = parallelAnchors.crbegin(); it != parallelAnchors.crend(); ++it) {
1242 ParallelAnchorData *parallel = static_cast<ParallelAnchorData *>(*it);
1243 restoreSimplifiedConstraints(parallel);
1244 }
1245
1246 // Then, we will restore the vertices in the inverse order of creation, this way we ensure that
1247 // the vertex being restored was not wrapped by another simplification.
1248 for (auto it = toRestore.crbegin(); it != toRestore.crend(); ++it) {
1249 auto *pair = *it;
1250 const QList<AnchorVertex *> adjacents = g.adjacentVertices(pair);
1251
1252 // Restore the removed edge, this will also restore both vertices 'first' and 'second' to
1253 // the graph structure.
1254 AnchorVertex *first = pair->m_first;
1255 AnchorVertex *second = pair->m_second;
1256 g.createEdge(first, second, pair->m_removedAnchor);
1257
1258 // Restore the anchors for the first child vertex
1259 for (AnchorData *ad : std::as_const(pair->m_firstAnchors)) {
1260 Q_ASSERT(ad->from == pair || ad->to == pair);
1261
1262 replaceVertex_helper(ad, pair, first);
1263 g.createEdge(ad->from, ad->to, ad);
1264 }
1265
1266 // Restore the anchors for the second child vertex
1267 for (AnchorData *ad : std::as_const(pair->m_secondAnchors)) {
1268 Q_ASSERT(ad->from == pair || ad->to == pair);
1269
1270 replaceVertex_helper(ad, pair, second);
1271 g.createEdge(ad->from, ad->to, ad);
1272 }
1273
1274 for (AnchorVertex *adjacent : adjacents)
1275 g.takeEdge(pair, adjacent);
1276
1277 // The pair simplified a layout vertex, so place back the correct vertex in the variable
1278 // that track layout vertices
1279 if (pair->m_item == q) {
1280 AnchorVertex *layoutVertex = first->m_item == q ? first : second;
1281 Q_ASSERT(layoutVertex->m_item == q);
1282 changeLayoutVertex(orientation, pair, layoutVertex);
1283 }
1284
1285 delete pair;
1286 }
1287 qDeleteAll(parallelAnchors);
1288 parallelAnchors.clear();
1289 toRestore.clear();
1290}
1291
1292Qt::Orientation
1293QGraphicsAnchorLayoutPrivate::edgeOrientation(Qt::AnchorPoint edge) noexcept
1294{
1295 return edge > Qt::AnchorRight ? Qt::Vertical : Qt::Horizontal;
1296}
1297
1298/*!
1299 \internal
1300
1301 Create internal anchors to connect the layout edges (Left to Right and
1302 Top to Bottom).
1303
1304 These anchors doesn't have size restrictions, that will be enforced by
1305 other anchors and items in the layout.
1306*/
1307void QGraphicsAnchorLayoutPrivate::createLayoutEdges()
1308{
1309 Q_Q(QGraphicsAnchorLayout);
1310 QGraphicsLayoutItem *layout = q;
1311
1312 // Horizontal
1313 AnchorData *data = new AnchorData;
1314 addAnchor_helper(layout, Qt::AnchorLeft, layout,
1315 Qt::AnchorRight, data);
1316 data->maxSize = QWIDGETSIZE_MAX;
1317
1318 // Save a reference to layout vertices
1319 layoutFirstVertex[Qt::Horizontal] = internalVertex(layout, Qt::AnchorLeft);
1320 layoutCentralVertex[Qt::Horizontal] = nullptr;
1321 layoutLastVertex[Qt::Horizontal] = internalVertex(layout, Qt::AnchorRight);
1322
1323 // Vertical
1324 data = new AnchorData;
1325 addAnchor_helper(layout, Qt::AnchorTop, layout,
1326 Qt::AnchorBottom, data);
1327 data->maxSize = QWIDGETSIZE_MAX;
1328
1329 // Save a reference to layout vertices
1330 layoutFirstVertex[Qt::Vertical] = internalVertex(layout, Qt::AnchorTop);
1331 layoutCentralVertex[Qt::Vertical] = nullptr;
1332 layoutLastVertex[Qt::Vertical] = internalVertex(layout, Qt::AnchorBottom);
1333}
1334
1335void QGraphicsAnchorLayoutPrivate::deleteLayoutEdges()
1336{
1337 Q_Q(QGraphicsAnchorLayout);
1338
1339 Q_ASSERT(!internalVertex(q, Qt::AnchorHorizontalCenter));
1340 Q_ASSERT(!internalVertex(q, Qt::AnchorVerticalCenter));
1341
1342 removeAnchor_helper(internalVertex(q, Qt::AnchorLeft),
1343 internalVertex(q, Qt::AnchorRight));
1344 removeAnchor_helper(internalVertex(q, Qt::AnchorTop),
1345 internalVertex(q, Qt::AnchorBottom));
1346}
1347
1348void QGraphicsAnchorLayoutPrivate::createItemEdges(QGraphicsLayoutItem *item)
1349{
1350 items.append(item);
1351
1352 // Create horizontal and vertical internal anchors for the item and
1353 // refresh its size hint / policy values.
1354 AnchorData *data = new AnchorData;
1355 addAnchor_helper(item, Qt::AnchorLeft, item, Qt::AnchorRight, data);
1356 data->refreshSizeHints();
1357
1358 data = new AnchorData;
1359 addAnchor_helper(item, Qt::AnchorTop, item, Qt::AnchorBottom, data);
1360 data->refreshSizeHints();
1361}
1362
1363/*!
1364 \internal
1365
1366 By default, each item in the layout is represented internally as
1367 a single anchor in each direction. For instance, from Left to Right.
1368
1369 However, to support anchorage of items to the center of items, we
1370 must split this internal anchor into two half-anchors. From Left
1371 to Center and then from Center to Right, with the restriction that
1372 these anchors must have the same time at all times.
1373*/
1374void QGraphicsAnchorLayoutPrivate::createCenterAnchors(
1375 QGraphicsLayoutItem *item, Qt::AnchorPoint centerEdge)
1376{
1377 Q_Q(QGraphicsAnchorLayout);
1378
1379 Qt::Orientation orientation;
1380 switch (centerEdge) {
1381 case Qt::AnchorHorizontalCenter:
1382 orientation = Qt::Horizontal;
1383 break;
1384 case Qt::AnchorVerticalCenter:
1385 orientation = Qt::Vertical;
1386 break;
1387 default:
1388 // Don't create center edges unless needed
1389 return;
1390 }
1391
1392 // Check if vertex already exists
1393 if (internalVertex(item, centerEdge))
1394 return;
1395
1396 // Orientation code
1397 Qt::AnchorPoint firstEdge;
1398 Qt::AnchorPoint lastEdge;
1399
1400 if (orientation == Qt::Horizontal) {
1401 firstEdge = Qt::AnchorLeft;
1402 lastEdge = Qt::AnchorRight;
1403 } else {
1404 firstEdge = Qt::AnchorTop;
1405 lastEdge = Qt::AnchorBottom;
1406 }
1407
1408 AnchorVertex *first = internalVertex(item, firstEdge);
1409 AnchorVertex *last = internalVertex(item, lastEdge);
1410 Q_ASSERT(first && last);
1411
1412 // Create new anchors
1413 QSimplexConstraint *c = new QSimplexConstraint;
1414
1415 AnchorData *data = new AnchorData;
1416 c->variables.insert(data, 1.0);
1417 addAnchor_helper(item, firstEdge, item, centerEdge, data);
1418 data->isCenterAnchor = true;
1419 data->dependency = AnchorData::Master;
1420 data->refreshSizeHints();
1421
1422 data = new AnchorData;
1423 c->variables.insert(data, -1.0);
1424 addAnchor_helper(item, centerEdge, item, lastEdge, data);
1425 data->isCenterAnchor = true;
1426 data->dependency = AnchorData::Slave;
1427 data->refreshSizeHints();
1428
1429 itemCenterConstraints[orientation].append(c);
1430
1431 // Remove old one
1432 removeAnchor_helper(first, last);
1433
1434 if (item == q) {
1435 layoutCentralVertex[orientation] = internalVertex(q, centerEdge);
1436 }
1437}
1438
1439void QGraphicsAnchorLayoutPrivate::removeCenterAnchors(
1440 QGraphicsLayoutItem *item, Qt::AnchorPoint centerEdge,
1441 bool substitute)
1442{
1443 Q_Q(QGraphicsAnchorLayout);
1444
1445 Qt::Orientation orientation;
1446 switch (centerEdge) {
1447 case Qt::AnchorHorizontalCenter:
1448 orientation = Qt::Horizontal;
1449 break;
1450 case Qt::AnchorVerticalCenter:
1451 orientation = Qt::Vertical;
1452 break;
1453 default:
1454 // Don't remove edges that not the center ones
1455 return;
1456 }
1457
1458 // Orientation code
1459 Qt::AnchorPoint firstEdge;
1460 Qt::AnchorPoint lastEdge;
1461
1462 if (orientation == Qt::Horizontal) {
1463 firstEdge = Qt::AnchorLeft;
1464 lastEdge = Qt::AnchorRight;
1465 } else {
1466 firstEdge = Qt::AnchorTop;
1467 lastEdge = Qt::AnchorBottom;
1468 }
1469
1470 AnchorVertex *center = internalVertex(item, centerEdge);
1471 if (!center)
1472 return;
1473 AnchorVertex *first = internalVertex(item, firstEdge);
1474
1475 Q_ASSERT(first);
1476 Q_ASSERT(center);
1477
1478 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
1479
1480
1481 AnchorData *oldData = g.edgeData(first, center);
1482 // Remove center constraint
1483 for (int i = itemCenterConstraints[orientation].size() - 1; i >= 0; --i) {
1484 if (itemCenterConstraints[orientation].at(i)->variables.contains(oldData)) {
1485 delete itemCenterConstraints[orientation].takeAt(i);
1486 break;
1487 }
1488 }
1489
1490 if (substitute) {
1491 // Create the new anchor that should substitute the left-center-right anchors.
1492 AnchorData *data = new AnchorData;
1493 addAnchor_helper(item, firstEdge, item, lastEdge, data);
1494 data->refreshSizeHints();
1495
1496 // Remove old anchors
1497 removeAnchor_helper(first, center);
1498 removeAnchor_helper(center, internalVertex(item, lastEdge));
1499
1500 } else {
1501 // this is only called from removeAnchors()
1502 // first, remove all non-internal anchors
1503 const QList<AnchorVertex*> adjacents = g.adjacentVertices(center);
1504 for (AnchorVertex *v : adjacents) {
1505 if (v->m_item != item)
1506 removeAnchor_helper(center, internalVertex(v->m_item, v->m_edge));
1507 }
1508 // when all non-internal anchors is removed it will automatically merge the
1509 // center anchor into a left-right (or top-bottom) anchor. We must also delete that.
1510 // by this time, the center vertex is deleted and merged into a non-centered internal anchor
1511 removeAnchor_helper(first, internalVertex(item, lastEdge));
1512 }
1513
1514 if (item == q) {
1515 layoutCentralVertex[orientation] = nullptr;
1516 }
1517}
1518
1519
1520void QGraphicsAnchorLayoutPrivate::removeCenterConstraints(QGraphicsLayoutItem *item,
1521 Qt::Orientation orientation)
1522{
1523 // Remove the item center constraints associated to this item
1524 // ### This is a temporary solution. We should probably use a better
1525 // data structure to hold items and/or their associated constraints
1526 // so that we can remove those easily
1527
1528 AnchorVertex *first = internalVertex(item, orientation == Qt::Horizontal ?
1529 Qt::AnchorLeft :
1530 Qt::AnchorTop);
1531 AnchorVertex *center = internalVertex(item, orientation == Qt::Horizontal ?
1532 Qt::AnchorHorizontalCenter :
1533 Qt::AnchorVerticalCenter);
1534
1535 // Skip if no center constraints exist
1536 if (!center)
1537 return;
1538
1539 Q_ASSERT(first);
1540 AnchorData *internalAnchor = graph[orientation].edgeData(first, center);
1541
1542 // Look for our anchor in all item center constraints, then remove it
1543 for (int i = 0; i < itemCenterConstraints[orientation].size(); ++i) {
1544 if (itemCenterConstraints[orientation].at(i)->variables.contains(internalAnchor)) {
1545 delete itemCenterConstraints[orientation].takeAt(i);
1546 break;
1547 }
1548 }
1549}
1550
1551/*!
1552 * \internal
1553 * Implements the high level "addAnchor" feature. Called by the public API
1554 * addAnchor method.
1555 *
1556 * The optional \a spacing argument defines the size of the anchor. If not provided,
1557 * the anchor size is either 0 or not-set, depending on type of anchor created (see
1558 * matrix below).
1559 *
1560 * All anchors that remain with size not-set will assume the standard spacing,
1561 * set either by the layout style or through the "setSpacing" layout API.
1562 */
1563QGraphicsAnchor *QGraphicsAnchorLayoutPrivate::addAnchor(QGraphicsLayoutItem *firstItem,
1564 Qt::AnchorPoint firstEdge,
1565 QGraphicsLayoutItem *secondItem,
1566 Qt::AnchorPoint secondEdge,
1567 qreal *spacing)
1568{
1569 Q_Q(QGraphicsAnchorLayout);
1570 if ((firstItem == nullptr) || (secondItem == nullptr)) {
1571 qWarning("QGraphicsAnchorLayout::addAnchor(): "
1572 "Cannot anchor NULL items");
1573 return nullptr;
1574 }
1575
1576 if (firstItem == secondItem) {
1577 qWarning("QGraphicsAnchorLayout::addAnchor(): "
1578 "Cannot anchor the item to itself");
1579 return nullptr;
1580 }
1581
1582 if (edgeOrientation(secondEdge) != edgeOrientation(firstEdge)) {
1583 qWarning("QGraphicsAnchorLayout::addAnchor(): "
1584 "Cannot anchor edges of different orientations");
1585 return nullptr;
1586 }
1587
1588 const QGraphicsLayoutItem *parentWidget = q->parentLayoutItem();
1589 if (firstItem == parentWidget || secondItem == parentWidget) {
1590 qWarning("QGraphicsAnchorLayout::addAnchor(): "
1591 "You cannot add the parent of the layout to the layout.");
1592 return nullptr;
1593 }
1594
1595 // In QGraphicsAnchorLayout, items are represented in its internal
1596 // graph as four anchors that connect:
1597 // - Left -> HCenter
1598 // - HCenter-> Right
1599 // - Top -> VCenter
1600 // - VCenter -> Bottom
1601
1602 // Ensure that the internal anchors have been created for both items.
1603 if (firstItem != q && !items.contains(firstItem)) {
1604 createItemEdges(firstItem);
1605 addChildLayoutItem(firstItem);
1606 }
1607 if (secondItem != q && !items.contains(secondItem)) {
1608 createItemEdges(secondItem);
1609 addChildLayoutItem(secondItem);
1610 }
1611
1612 // Create center edges if needed
1613 createCenterAnchors(firstItem, firstEdge);
1614 createCenterAnchors(secondItem, secondEdge);
1615
1616 // Use heuristics to find out what the user meant with this anchor.
1617 correctEdgeDirection(firstItem, firstEdge, secondItem, secondEdge);
1618
1619 AnchorData *data = new AnchorData;
1620 QGraphicsAnchor *graphicsAnchor = acquireGraphicsAnchor(data);
1621
1622 addAnchor_helper(firstItem, firstEdge, secondItem, secondEdge, data);
1623
1624 if (spacing) {
1625 graphicsAnchor->setSpacing(*spacing);
1626 } else {
1627 // If firstItem or secondItem is the layout itself, the spacing will default to 0.
1628 // Otherwise, the following matrix is used (questionmark means that the spacing
1629 // is queried from the style):
1630 // from
1631 // to Left HCenter Right
1632 // Left 0 0 ?
1633 // HCenter 0 0 0
1634 // Right ? 0 0
1635 if (firstItem == q
1636 || secondItem == q
1637 || pickEdge(firstEdge, Qt::Horizontal) == Qt::AnchorHorizontalCenter
1638 || oppositeEdge(firstEdge) != secondEdge) {
1639 graphicsAnchor->setSpacing(0);
1640 } else {
1641 graphicsAnchor->unsetSpacing();
1642 }
1643 }
1644
1645 return graphicsAnchor;
1646}
1647
1648/*
1649 \internal
1650
1651 This method adds an AnchorData to the internal graph. It is responsible for doing
1652 the boilerplate part of such task.
1653
1654 If another AnchorData exists between the mentioned vertices, it is deleted and
1655 the new one is inserted.
1656*/
1657void QGraphicsAnchorLayoutPrivate::addAnchor_helper(QGraphicsLayoutItem *firstItem,
1658 Qt::AnchorPoint firstEdge,
1659 QGraphicsLayoutItem *secondItem,
1660 Qt::AnchorPoint secondEdge,
1661 AnchorData *data)
1662{
1663 Q_Q(QGraphicsAnchorLayout);
1664
1665 const Qt::Orientation orientation = edgeOrientation(firstEdge);
1666
1667 // Create or increase the reference count for the related vertices.
1668 AnchorVertex *v1 = addInternalVertex(firstItem, firstEdge);
1669 AnchorVertex *v2 = addInternalVertex(secondItem, secondEdge);
1670
1671 // Remove previous anchor
1672 if (graph[orientation].edgeData(v1, v2)) {
1673 removeAnchor_helper(v1, v2);
1674 }
1675
1676 // If its an internal anchor, set the associated item
1677 if (firstItem == secondItem)
1678 data->item = firstItem;
1679
1680 data->isVertical = orientation == Qt::Vertical;
1681
1682 // Create a bi-directional edge in the sense it can be transversed both
1683 // from v1 or v2. "data" however is shared between the two references
1684 // so we still know that the anchor direction is from 1 to 2.
1685 data->from = v1;
1686 data->to = v2;
1687#ifdef QT_DEBUG
1688 data->name = QString::fromLatin1("%1 --to--> %2").arg(v1->toString(), v2->toString());
1689#endif
1690 // ### bit to track internal anchors, since inside AnchorData methods
1691 // we don't have access to the 'q' pointer.
1692 data->isLayoutAnchor = (data->item == q);
1693
1694 graph[orientation].createEdge(v1, v2, data);
1695}
1696
1697QGraphicsAnchor *QGraphicsAnchorLayoutPrivate::getAnchor(QGraphicsLayoutItem *firstItem,
1698 Qt::AnchorPoint firstEdge,
1699 QGraphicsLayoutItem *secondItem,
1700 Qt::AnchorPoint secondEdge)
1701{
1702 // Do not expose internal anchors
1703 if (firstItem == secondItem)
1704 return nullptr;
1705
1706 const Qt::Orientation orientation = edgeOrientation(firstEdge);
1707 AnchorVertex *v1 = internalVertex(firstItem, firstEdge);
1708 AnchorVertex *v2 = internalVertex(secondItem, secondEdge);
1709
1710 QGraphicsAnchor *graphicsAnchor = nullptr;
1711
1712 AnchorData *data = graph[orientation].edgeData(v1, v2);
1713 if (data) {
1714 // We could use "acquireGraphicsAnchor" here, but to avoid a regression where
1715 // an internal anchor was wrongly exposed, I want to ensure no new
1716 // QGraphicsAnchor instances are created by this call.
1717 // This assumption must hold because anchors are either user-created (and already
1718 // have their public object created), or they are internal (and must not reach
1719 // this point).
1720 Q_ASSERT(data->graphicsAnchor);
1721 graphicsAnchor = data->graphicsAnchor;
1722 }
1723 return graphicsAnchor;
1724}
1725
1726/*!
1727 * \internal
1728 *
1729 * Implements the high level "removeAnchor" feature. Called by
1730 * the QAnchorData destructor.
1731 */
1732void QGraphicsAnchorLayoutPrivate::removeAnchor(AnchorVertex *firstVertex,
1733 AnchorVertex *secondVertex)
1734{
1735 Q_Q(QGraphicsAnchorLayout);
1736
1737 // Save references to items while it's safe to assume the vertices exist
1738 QGraphicsLayoutItem *firstItem = firstVertex->m_item;
1739 QGraphicsLayoutItem *secondItem = secondVertex->m_item;
1740
1741 // Delete the anchor (may trigger deletion of center vertices)
1742 removeAnchor_helper(firstVertex, secondVertex);
1743
1744 // Ensure no dangling pointer is left behind
1745 firstVertex = secondVertex = nullptr;
1746
1747 // Checking if the item stays in the layout or not
1748 bool keepFirstItem = false;
1749 bool keepSecondItem = false;
1750
1751 std::pair<AnchorVertex *, int> v;
1752 int refcount = -1;
1753
1754 if (firstItem != q) {
1755 for (int i = Qt::AnchorLeft; i <= Qt::AnchorBottom; ++i) {
1756 v = m_vertexList.value(std::pair(firstItem, static_cast<Qt::AnchorPoint>(i)));
1757 if (v.first) {
1758 if (i == Qt::AnchorHorizontalCenter || i == Qt::AnchorVerticalCenter)
1759 refcount = 2;
1760 else
1761 refcount = 1;
1762
1763 if (v.second > refcount) {
1764 keepFirstItem = true;
1765 break;
1766 }
1767 }
1768 }
1769 } else
1770 keepFirstItem = true;
1771
1772 if (secondItem != q) {
1773 for (int i = Qt::AnchorLeft; i <= Qt::AnchorBottom; ++i) {
1774 v = m_vertexList.value(std::pair(secondItem, static_cast<Qt::AnchorPoint>(i)));
1775 if (v.first) {
1776 if (i == Qt::AnchorHorizontalCenter || i == Qt::AnchorVerticalCenter)
1777 refcount = 2;
1778 else
1779 refcount = 1;
1780
1781 if (v.second > refcount) {
1782 keepSecondItem = true;
1783 break;
1784 }
1785 }
1786 }
1787 } else
1788 keepSecondItem = true;
1789
1790 if (!keepFirstItem)
1791 q->removeAt(items.indexOf(firstItem));
1792
1793 if (!keepSecondItem)
1794 q->removeAt(items.indexOf(secondItem));
1795
1796 // Removing anchors invalidates the layout
1797 q->invalidate();
1798}
1799
1800/*
1801 \internal
1802
1803 Implements the low level "removeAnchor" feature. Called by
1804 private methods.
1805*/
1806void QGraphicsAnchorLayoutPrivate::removeAnchor_helper(AnchorVertex *v1, AnchorVertex *v2)
1807{
1808 Q_ASSERT(v1 && v2);
1809
1810 // Remove edge from graph
1811 const Qt::Orientation o = edgeOrientation(v1->m_edge);
1812 graph[o].removeEdge(v1, v2);
1813
1814 // Decrease vertices reference count (may trigger a deletion)
1815 removeInternalVertex(v1->m_item, v1->m_edge);
1816 removeInternalVertex(v2->m_item, v2->m_edge);
1817}
1818
1819AnchorVertex *QGraphicsAnchorLayoutPrivate::addInternalVertex(QGraphicsLayoutItem *item,
1820 Qt::AnchorPoint edge)
1821{
1822 std::pair<QGraphicsLayoutItem *, Qt::AnchorPoint> pair(item, edge);
1823 std::pair<AnchorVertex *, int> v = m_vertexList.value(pair);
1824
1825 if (!v.first) {
1826 Q_ASSERT(v.second == 0);
1827 v.first = new AnchorVertex(item, edge);
1828 }
1829 v.second++;
1830 m_vertexList.insert(pair, v);
1831 return v.first;
1832}
1833
1834/**
1835 * \internal
1836 *
1837 * returns the AnchorVertex that was dereferenced, also when it was removed.
1838 * returns 0 if it did not exist.
1839 */
1840void QGraphicsAnchorLayoutPrivate::removeInternalVertex(QGraphicsLayoutItem *item,
1841 Qt::AnchorPoint edge)
1842{
1843 std::pair<QGraphicsLayoutItem *, Qt::AnchorPoint> pair(item, edge);
1844 std::pair<AnchorVertex *, int> v = m_vertexList.value(pair);
1845
1846 if (!v.first) {
1847 qWarning("This item with this edge is not in the graph");
1848 return;
1849 }
1850
1851 v.second--;
1852 if (v.second == 0) {
1853 // Remove reference and delete vertex
1854 m_vertexList.remove(pair);
1855 delete v.first;
1856 } else {
1857 // Update reference count
1858 m_vertexList.insert(pair, v);
1859
1860 if ((v.second == 2) &&
1861 ((edge == Qt::AnchorHorizontalCenter) ||
1862 (edge == Qt::AnchorVerticalCenter))) {
1863 removeCenterAnchors(item, edge, true);
1864 }
1865 }
1866}
1867
1868void QGraphicsAnchorLayoutPrivate::removeVertex(QGraphicsLayoutItem *item, Qt::AnchorPoint edge)
1869{
1870 if (AnchorVertex *v = internalVertex(item, edge)) {
1871 Graph<AnchorVertex, AnchorData> &g = graph[edgeOrientation(edge)];
1872 const auto allVertices = g.adjacentVertices(v);
1873 for (auto *v2 : allVertices) {
1874 g.removeEdge(v, v2);
1875 removeInternalVertex(item, edge);
1876 removeInternalVertex(v2->m_item, v2->m_edge);
1877 }
1878 }
1879}
1880
1881void QGraphicsAnchorLayoutPrivate::removeAnchors(QGraphicsLayoutItem *item)
1882{
1883 // remove the center anchor first!!
1884 removeCenterAnchors(item, Qt::AnchorHorizontalCenter, false);
1885 removeVertex(item, Qt::AnchorLeft);
1886 removeVertex(item, Qt::AnchorRight);
1887
1888 removeCenterAnchors(item, Qt::AnchorVerticalCenter, false);
1889 removeVertex(item, Qt::AnchorTop);
1890 removeVertex(item, Qt::AnchorBottom);
1891}
1892
1893/*!
1894 \internal
1895
1896 Use heuristics to determine the correct orientation of a given anchor.
1897
1898 After API discussions, we decided we would like expressions like
1899 anchor(A, Left, B, Right) to mean the same as anchor(B, Right, A, Left).
1900 The problem with this is that anchors could become ambiguous, for
1901 instance, what does the anchor A, B of size X mean?
1902
1903 "pos(B) = pos(A) + X" or "pos(A) = pos(B) + X" ?
1904
1905 To keep the API user friendly and at the same time, keep our algorithm
1906 deterministic, we use an heuristic to determine a direction for each
1907 added anchor and then keep it. The heuristic is based on the fact
1908 that people usually avoid overlapping items, therefore:
1909
1910 "A, RIGHT to B, LEFT" means that B is to the LEFT of A.
1911 "B, LEFT to A, RIGHT" is corrected to the above anchor.
1912
1913 Special correction is also applied when one of the items is the
1914 layout. We handle Layout Left as if it was another items's Right
1915 and Layout Right as another item's Left.
1916*/
1917void QGraphicsAnchorLayoutPrivate::correctEdgeDirection(QGraphicsLayoutItem *&firstItem,
1918 Qt::AnchorPoint &firstEdge,
1919 QGraphicsLayoutItem *&secondItem,
1920 Qt::AnchorPoint &secondEdge)
1921{
1922 Q_Q(QGraphicsAnchorLayout);
1923
1924 if ((firstItem != q) && (secondItem != q)) {
1925 // If connection is between widgets (not the layout itself)
1926 // Ensure that "right-edges" sit to the left of "left-edges".
1927 if (firstEdge < secondEdge) {
1928 qSwap(firstItem, secondItem);
1929 qSwap(firstEdge, secondEdge);
1930 }
1931 } else if (firstItem == q) {
1932 // If connection involves the right or bottom of a layout, ensure
1933 // the layout is the second item.
1934 if ((firstEdge == Qt::AnchorRight) || (firstEdge == Qt::AnchorBottom)) {
1935 qSwap(firstItem, secondItem);
1936 qSwap(firstEdge, secondEdge);
1937 }
1938 } else if ((secondEdge != Qt::AnchorRight) && (secondEdge != Qt::AnchorBottom)) {
1939 // If connection involves the left, center or top of layout, ensure
1940 // the layout is the first item.
1941 qSwap(firstItem, secondItem);
1942 qSwap(firstEdge, secondEdge);
1943 }
1944}
1945
1946QLayoutStyleInfo &QGraphicsAnchorLayoutPrivate::styleInfo() const
1947{
1948 if (styleInfoDirty) {
1949 Q_Q(const QGraphicsAnchorLayout);
1950 //### Fix this if QGV ever gets support for Metal style or different Aqua sizes.
1951 QWidget *wid = nullptr;
1952
1953 QGraphicsLayoutItem *parent = q->parentLayoutItem();
1954 while (parent && parent->isLayout()) {
1955 parent = parent->parentLayoutItem();
1956 }
1957 QGraphicsWidget *w = nullptr;
1958 if (parent) {
1959 QGraphicsItem *parentItem = parent->graphicsItem();
1960 if (parentItem && parentItem->isWidget())
1961 w = static_cast<QGraphicsWidget*>(parentItem);
1962 }
1963
1964 QStyle *style = w ? w->style() : QApplication::style();
1965 cachedStyleInfo = QLayoutStyleInfo(style, wid);
1966 cachedStyleInfo.setDefaultSpacing(Qt::Horizontal, spacings[Qt::Horizontal]);
1967 cachedStyleInfo.setDefaultSpacing(Qt::Vertical, spacings[Qt::Vertical]);
1968
1969 styleInfoDirty = false;
1970 }
1971 return cachedStyleInfo;
1972}
1973
1974/*!
1975 \internal
1976
1977 Called on activation. Uses Linear Programming to define minimum, preferred
1978 and maximum sizes for the layout. Also calculates the sizes that each item
1979 should assume when the layout is in one of such situations.
1980*/
1981void QGraphicsAnchorLayoutPrivate::calculateGraphs()
1982{
1983 if (!calculateGraphCacheDirty)
1984 return;
1985 calculateGraphs(Qt::Horizontal);
1986 calculateGraphs(Qt::Vertical);
1987 calculateGraphCacheDirty = false;
1988}
1989
1990// ### Maybe getGraphParts could return the variables when traversing, at least
1991// for trunk...
1992QList<AnchorData *> getVariables(const QList<QSimplexConstraint *> &constraints)
1993{
1994 QSet<AnchorData *> variableSet;
1995 for (QSimplexConstraint *c : constraints) {
1996 for (auto it = c->variables.cbegin(), end = c->variables.cend(); it != end; ++it)
1997 variableSet.insert(static_cast<AnchorData *>(it.key()));
1998 }
1999 return variableSet.values();
2000}
2001
2002/*!
2003 \internal
2004
2005 Calculate graphs is the method that puts together all the helper routines
2006 so that the AnchorLayout can calculate the sizes of each item.
2007
2008 In a nutshell it should do:
2009
2010 1) Refresh anchor nominal sizes, that is, the size that each anchor would
2011 have if no other restrictions applied. This is done by querying the
2012 layout style and the sizeHints of the items belonging to the layout.
2013
2014 2) Simplify the graph by grouping together parallel and sequential anchors
2015 into "group anchors". These have equivalent minimum, preferred and maximum
2016 sizeHints as the anchors they replace.
2017
2018 3) Check if we got to a trivial case. In some cases, the whole graph can be
2019 simplified into a single anchor. If so, use this information. If not,
2020 then call the Simplex solver to calculate the anchors sizes.
2021
2022 4) Once the root anchors had its sizes calculated, propagate that to the
2023 anchors they represent.
2024*/
2025void QGraphicsAnchorLayoutPrivate::calculateGraphs(Qt::Orientation orientation)
2026{
2027#if defined(QT_DEBUG) || defined(QT_BUILD_INTERNAL)
2028 lastCalculationUsedSimplex[orientation] = false;
2029#endif
2030
2031 static bool simplificationEnabled = qEnvironmentVariableIsEmpty("QT_ANCHORLAYOUT_NO_SIMPLIFICATION");
2032
2033 // Reset the nominal sizes of each anchor based on the current item sizes
2034 refreshAllSizeHints(orientation);
2035
2036 // Simplify the graph
2037 if (simplificationEnabled && !simplifyGraph(orientation)) {
2038 qWarning("QGraphicsAnchorLayout: anchor setup is not feasible.");
2039 graphHasConflicts[orientation] = true;
2040 return;
2041 }
2042
2043 // Traverse all graph edges and store the possible paths to each vertex
2044 findPaths(orientation);
2045
2046 // From the paths calculated above, extract the constraints that the current
2047 // anchor setup impose, to our Linear Programming problem.
2048 constraintsFromPaths(orientation);
2049
2050 // Split the constraints and anchors into groups that should be fed to the
2051 // simplex solver independently. Currently we find two groups:
2052 //
2053 // 1) The "trunk", that is, the set of anchors (items) that are connected
2054 // to the two opposite sides of our layout, and thus need to stretch in
2055 // order to fit in the current layout size.
2056 //
2057 // 2) The floating or semi-floating anchors (items) that are those which
2058 // are connected to only one (or none) of the layout sides, thus are not
2059 // influenced by the layout size.
2060 const auto parts = getGraphParts(orientation);
2061
2062 // Now run the simplex solver to calculate Minimum, Preferred and Maximum sizes
2063 // of the "trunk" set of constraints and variables.
2064 // ### does trunk always exist? empty = trunk is the layout left->center->right
2065 const QList<AnchorData *> trunkVariables = getVariables(parts.trunkConstraints);
2066
2067 // For minimum and maximum, use the path between the two layout sides as the
2068 // objective function.
2069 AnchorVertex *v = layoutLastVertex[orientation];
2070 GraphPath trunkPath = graphPaths[orientation].value(v);
2071
2072 bool feasible = calculateTrunk(orientation, trunkPath, parts.trunkConstraints, trunkVariables);
2073
2074 // For the other parts that not the trunk, solve only for the preferred size
2075 // that is the size they will remain at, since they are not stretched by the
2076 // layout.
2077
2078 if (feasible && !parts.nonTrunkConstraints.isEmpty()) {
2079 const QList<AnchorData *> partVariables = getVariables(parts.nonTrunkConstraints);
2080 Q_ASSERT(!partVariables.isEmpty());
2081 feasible = calculateNonTrunk(parts.nonTrunkConstraints, partVariables);
2082 }
2083
2084 // Propagate the new sizes down the simplified graph, ie. tell the
2085 // group anchors to set their children anchors sizes.
2086 updateAnchorSizes(orientation);
2087
2088 graphHasConflicts[orientation] = !feasible;
2089
2090 // Clean up our data structures. They are not needed anymore since
2091 // distribution uses just interpolation.
2092 qDeleteAll(constraints[orientation]);
2093 constraints[orientation].clear();
2094 graphPaths[orientation].clear(); // ###
2095
2096 if (simplificationEnabled)
2097 restoreSimplifiedGraph(orientation);
2098}
2099
2100/*!
2101 \internal
2102
2103 Shift all the constraints by a certain amount. This allows us to deal with negative values in
2104 the linear program if they are bounded by a certain limit. Functions should be careful to
2105 call it again with a negative amount, to shift the constraints back.
2106*/
2107static void shiftConstraints(const QList<QSimplexConstraint *> &constraints, qreal amount)
2108{
2109 for (QSimplexConstraint *c : constraints) {
2110 const qreal multiplier = std::accumulate(c->variables.cbegin(), c->variables.cend(), qreal(0));
2111 c->constant += multiplier * amount;
2112 }
2113}
2114
2115/*!
2116 \internal
2117
2118 Calculate the sizes for all anchors which are part of the trunk. This works
2119 on top of a (possibly) simplified graph.
2120*/
2121bool QGraphicsAnchorLayoutPrivate::calculateTrunk(Qt::Orientation orientation, const GraphPath &path,
2122 const QList<QSimplexConstraint *> &constraints,
2123 const QList<AnchorData *> &variables)
2124{
2125 bool feasible = true;
2126 bool needsSimplex = !constraints.isEmpty();
2127
2128#if 0
2129 qDebug("Simplex %s for trunk of %s", needsSimplex ? "used" : "NOT used",
2130 orientation == Qt::Horizontal ? "Horizontal" : "Vertical");
2131#endif
2132
2133 if (needsSimplex) {
2134
2135 QList<QSimplexConstraint *> sizeHintConstraints = constraintsFromSizeHints(variables);
2136 QList<QSimplexConstraint *> allConstraints = constraints + sizeHintConstraints;
2137
2138 shiftConstraints(allConstraints, g_offset);
2139
2140 // Solve min and max size hints
2141 qreal min, max;
2142 feasible = solveMinMax(allConstraints, path, &min, &max);
2143
2144 if (feasible) {
2145 solvePreferred(constraints, variables);
2146
2147 // Calculate and set the preferred size for the layout,
2148 // from the edge sizes that were calculated above.
2149 qreal pref(0.0);
2150 for (const AnchorData *ad : path.positives)
2151 pref += ad->sizeAtPreferred;
2152 for (const AnchorData *ad : path.negatives)
2153 pref -= ad->sizeAtPreferred;
2154
2155 sizeHints[orientation][Qt::MinimumSize] = min;
2156 sizeHints[orientation][Qt::PreferredSize] = pref;
2157 sizeHints[orientation][Qt::MaximumSize] = max;
2158 }
2159
2160 qDeleteAll(sizeHintConstraints);
2161 shiftConstraints(constraints, -g_offset);
2162
2163 } else {
2164 // No Simplex is necessary because the path was simplified all the way to a single
2165 // anchor.
2166 Q_ASSERT(path.positives.size() == 1);
2167 Q_ASSERT(path.negatives.size() == 0);
2168
2169 AnchorData *ad = *path.positives.cbegin();
2170 ad->sizeAtMinimum = ad->minSize;
2171 ad->sizeAtPreferred = ad->prefSize;
2172 ad->sizeAtMaximum = ad->maxSize;
2173
2174 sizeHints[orientation][Qt::MinimumSize] = ad->sizeAtMinimum;
2175 sizeHints[orientation][Qt::PreferredSize] = ad->sizeAtPreferred;
2176 sizeHints[orientation][Qt::MaximumSize] = ad->sizeAtMaximum;
2177 }
2178
2179#if defined(QT_DEBUG) || defined(QT_BUILD_INTERNAL)
2180 lastCalculationUsedSimplex[orientation] = needsSimplex;
2181#endif
2182
2183 return feasible;
2184}
2185
2186/*!
2187 \internal
2188*/
2189bool QGraphicsAnchorLayoutPrivate::calculateNonTrunk(const QList<QSimplexConstraint *> &constraints,
2190 const QList<AnchorData *> &variables)
2191{
2192 shiftConstraints(constraints, g_offset);
2193 bool feasible = solvePreferred(constraints, variables);
2194
2195 if (feasible) {
2196 // Propagate size at preferred to other sizes. Semi-floats always will be
2197 // in their sizeAtPreferred.
2198 for (AnchorData *ad : variables) {
2199 Q_ASSERT(ad);
2200 ad->sizeAtMinimum = ad->sizeAtPreferred;
2201 ad->sizeAtMaximum = ad->sizeAtPreferred;
2202 }
2203 }
2204
2205 shiftConstraints(constraints, -g_offset);
2206 return feasible;
2207}
2208
2209/*!
2210 \internal
2211
2212 Traverse the graph refreshing the size hints. Edges will query their associated
2213 item or graphicsAnchor for their size hints.
2214*/
2215void QGraphicsAnchorLayoutPrivate::refreshAllSizeHints(Qt::Orientation orientation)
2216{
2217 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
2218 const QList<std::pair<AnchorVertex *, AnchorVertex *>> vertices = g.connections();
2219
2220 QLayoutStyleInfo styleInf = styleInfo();
2221 for (const auto &p : vertices) {
2222 AnchorData *data = g.edgeData(p.first, p.second);
2223 data->refreshSizeHints(&styleInf);
2224 }
2225}
2226
2227/*!
2228 \internal
2229
2230 This method walks the graph using a breadth-first search to find paths
2231 between the root vertex and each vertex on the graph. The edges
2232 directions in each path are considered and they are stored as a
2233 positive edge (left-to-right) or negative edge (right-to-left).
2234
2235 The list of paths is used later to generate a list of constraints.
2236 */
2237void QGraphicsAnchorLayoutPrivate::findPaths(Qt::Orientation orientation)
2238{
2239 QQueue<std::pair<AnchorVertex *, AnchorVertex *> > queue;
2240
2241 QSet<AnchorData *> visited;
2242
2243 AnchorVertex *root = layoutFirstVertex[orientation];
2244
2245 graphPaths[orientation].insert(root, GraphPath());
2246
2247 const auto adjacentVertices = graph[orientation].adjacentVertices(root);
2248 for (AnchorVertex *v : adjacentVertices)
2249 queue.enqueue(std::pair(root, v));
2250
2251 while(!queue.isEmpty()) {
2252 std::pair<AnchorVertex *, AnchorVertex *> pair = queue.dequeue();
2253 AnchorData *edge = graph[orientation].edgeData(pair.first, pair.second);
2254
2255 if (visited.contains(edge))
2256 continue;
2257
2258 visited.insert(edge);
2259 GraphPath current = graphPaths[orientation].value(pair.first);
2260
2261 if (edge->from == pair.first)
2262 current.positives.insert(edge);
2263 else
2264 current.negatives.insert(edge);
2265
2266 graphPaths[orientation].insert(pair.second, current);
2267
2268 const auto adjacentVertices = graph[orientation].adjacentVertices(pair.second);
2269 for (AnchorVertex *v : adjacentVertices)
2270 queue.enqueue(std::pair(pair.second, v));
2271 }
2272
2273 // We will walk through every reachable items (non-float) store them in a temporary set.
2274 // We them create a set of all items and subtract the non-floating items from the set in
2275 // order to get the floating items. The floating items is then stored in m_floatItems
2276 identifyFloatItems(visited, orientation);
2277}
2278
2279/*!
2280 \internal
2281
2282 Each vertex on the graph that has more than one path to it
2283 represents a contra int to the sizes of the items in these paths.
2284
2285 This method walks the list of paths to each vertex, generate
2286 the constraints and store them in a list so they can be used later
2287 by the Simplex solver.
2288*/
2289void QGraphicsAnchorLayoutPrivate::constraintsFromPaths(Qt::Orientation orientation)
2290{
2291 const auto vertices = graphPaths[orientation].uniqueKeys();
2292 for (AnchorVertex *vertex : vertices) {
2293 const qsizetype valueCount = graphPaths[orientation].count(vertex);
2294 if (valueCount == 1)
2295 continue;
2296
2297 QList<GraphPath> pathsToVertex = graphPaths[orientation].values(vertex);
2298 for (qsizetype i = 1; i < valueCount; ++i)
2299 constraints[orientation] += pathsToVertex[0].constraint(pathsToVertex.at(i));
2300 }
2301}
2302
2303/*!
2304 \internal
2305*/
2306void QGraphicsAnchorLayoutPrivate::updateAnchorSizes(Qt::Orientation orientation)
2307{
2308 Graph<AnchorVertex, AnchorData> &g = graph[orientation];
2309 const QList<std::pair<AnchorVertex *, AnchorVertex *>> &vertices = g.connections();
2310
2311 for (const auto &p :vertices) {
2312 AnchorData *ad = g.edgeData(p.first, p.second);
2313 ad->updateChildrenSizes();
2314 }
2315}
2316
2317/*!
2318 \internal
2319
2320 Create LP constraints for each anchor based on its minimum and maximum
2321 sizes, as specified in its size hints
2322*/
2323QList<QSimplexConstraint *> QGraphicsAnchorLayoutPrivate::constraintsFromSizeHints(
2324 const QList<AnchorData *> &anchors)
2325{
2326 if (anchors.isEmpty())
2327 return QList<QSimplexConstraint *>();
2328
2329 // Look for the layout edge. That can be either the first half in case the
2330 // layout is split in two, or the whole layout anchor.
2331 const Qt::Orientation orient = anchors.first()->isVertical ? Qt::Vertical : Qt::Horizontal;
2332 AnchorData *layoutEdge = nullptr;
2333 if (layoutCentralVertex[orient]) {
2334 layoutEdge = graph[orient].edgeData(layoutFirstVertex[orient], layoutCentralVertex[orient]);
2335 } else {
2336 layoutEdge = graph[orient].edgeData(layoutFirstVertex[orient], layoutLastVertex[orient]);
2337 }
2338
2339 // If maxSize is less then "infinite", that means there are other anchors
2340 // grouped together with this one. We can't ignore its maximum value so we
2341 // set back the variable to NULL to prevent the continue condition from being
2342 // satisfied in the loop below.
2343 const qreal expectedMax = layoutCentralVertex[orient] ? QWIDGETSIZE_MAX / 2 : QWIDGETSIZE_MAX;
2344 qreal actualMax;
2345 if (layoutEdge->from == layoutFirstVertex[orient]) {
2346 actualMax = layoutEdge->maxSize;
2347 } else {
2348 actualMax = -layoutEdge->minSize;
2349 }
2350 if (actualMax != expectedMax) {
2351 layoutEdge = nullptr;
2352 }
2353
2354 // For each variable, create constraints based on size hints
2355 QList<QSimplexConstraint *> anchorConstraints;
2356 bool unboundedProblem = true;
2357 for (AnchorData *ad : anchors) {
2358
2359 // Anchors that have their size directly linked to another one don't need constraints
2360 // For exammple, the second half of an item has exactly the same size as the first half
2361 // thus constraining the latter is enough.
2362 if (ad->dependency == AnchorData::Slave)
2363 continue;
2364
2365 // To use negative variables inside simplex, we shift them so the minimum negative value is
2366 // mapped to zero before solving. To make sure that it works, we need to guarantee that the
2367 // variables are all inside a certain boundary.
2368 qreal boundedMin = qBound(-g_offset, ad->minSize, g_offset);
2369 qreal boundedMax = qBound(-g_offset, ad->maxSize, g_offset);
2370
2371 if ((boundedMin == boundedMax) || qFuzzyCompare(boundedMin, boundedMax)) {
2372 QSimplexConstraint *c = new QSimplexConstraint;
2373 c->variables.insert(ad, 1.0);
2374 c->constant = boundedMin;
2375 c->ratio = QSimplexConstraint::Equal;
2376 anchorConstraints += c;
2377 unboundedProblem = false;
2378 } else {
2379 QSimplexConstraint *c = new QSimplexConstraint;
2380 c->variables.insert(ad, 1.0);
2381 c->constant = boundedMin;
2382 c->ratio = QSimplexConstraint::MoreOrEqual;
2383 anchorConstraints += c;
2384
2385 // We avoid adding restrictions to the layout internal anchors. That's
2386 // to prevent unnecessary fair distribution from happening due to this
2387 // artificial restriction.
2388 if (ad == layoutEdge)
2389 continue;
2390
2391 c = new QSimplexConstraint;
2392 c->variables.insert(ad, 1.0);
2393 c->constant = boundedMax;
2394 c->ratio = QSimplexConstraint::LessOrEqual;
2395 anchorConstraints += c;
2396 unboundedProblem = false;
2397 }
2398 }
2399
2400 // If no upper boundary restriction was added, add one to avoid unbounded problem
2401 if (unboundedProblem) {
2402 QSimplexConstraint *c = new QSimplexConstraint;
2403 c->variables.insert(layoutEdge, 1.0);
2404 // The maximum size that the layout can take
2405 c->constant = g_offset;
2406 c->ratio = QSimplexConstraint::LessOrEqual;
2407 anchorConstraints += c;
2408 }
2409
2410 return anchorConstraints;
2411}
2412
2413/*!
2414 \internal
2415*/
2416QGraphicsAnchorLayoutPrivate::GraphParts
2417QGraphicsAnchorLayoutPrivate::getGraphParts(Qt::Orientation orientation)
2418{
2419 GraphParts result;
2420
2421 Q_ASSERT(layoutFirstVertex[orientation] && layoutLastVertex[orientation]);
2422
2423 AnchorData *edgeL1 = nullptr;
2424 AnchorData *edgeL2 = nullptr;
2425
2426 // The layout may have a single anchor between Left and Right or two half anchors
2427 // passing through the center
2428 if (layoutCentralVertex[orientation]) {
2429 edgeL1 = graph[orientation].edgeData(layoutFirstVertex[orientation], layoutCentralVertex[orientation]);
2430 edgeL2 = graph[orientation].edgeData(layoutCentralVertex[orientation], layoutLastVertex[orientation]);
2431 } else {
2432 edgeL1 = graph[orientation].edgeData(layoutFirstVertex[orientation], layoutLastVertex[orientation]);
2433 }
2434
2435 result.nonTrunkConstraints = constraints[orientation] + itemCenterConstraints[orientation];
2436
2437 QSet<QSimplexVariable *> trunkVariables;
2438
2439 trunkVariables += edgeL1;
2440 if (edgeL2)
2441 trunkVariables += edgeL2;
2442
2443 bool dirty;
2444 auto end = result.nonTrunkConstraints.end();
2445 do {
2446 dirty = false;
2447
2448 auto isMatch = [&result, &trunkVariables](QSimplexConstraint *c) -> bool {
2449 bool match = false;
2450
2451 // Check if this constraint have some overlap with current
2452 // trunk variables...
2453 for (QSimplexVariable *ad : std::as_const(trunkVariables)) {
2454 if (c->variables.contains(ad)) {
2455 match = true;
2456 break;
2457 }
2458 }
2459
2460 // If so, we add it to trunk, and erase it from the
2461 // remaining constraints.
2462 if (match) {
2463 result.trunkConstraints += c;
2464 for (auto jt = c->variables.cbegin(), end = c->variables.cend(); jt != end; ++jt)
2465 trunkVariables.insert(jt.key());
2466 return true;
2467 } else {
2468 // Note that we don't erase the constraint if it's not
2469 // a match, since in a next iteration of a do-while we
2470 // can pass on it again and it will be a match.
2471 //
2472 // For example: if trunk share a variable with
2473 // remainingConstraints[1] and it shares with
2474 // remainingConstraints[0], we need a second iteration
2475 // of the do-while loop to match both.
2476 return false;
2477 }
2478 };
2479 const auto newEnd = std::remove_if(result.nonTrunkConstraints.begin(), end, isMatch);
2480 dirty = newEnd != end;
2481 end = newEnd;
2482 } while (dirty);
2483
2484 result.nonTrunkConstraints.erase(end, result.nonTrunkConstraints.end());
2485
2486 return result;
2487}
2488
2489/*!
2490 \internal
2491
2492 Use all visited Anchors on findPaths() so we can identify non-float Items.
2493*/
2494void QGraphicsAnchorLayoutPrivate::identifyFloatItems(const QSet<AnchorData *> &visited, Qt::Orientation orientation)
2495{
2496 QSet<QGraphicsLayoutItem *> nonFloating;
2497
2498 for (const AnchorData *ad : visited)
2499 identifyNonFloatItems_helper(ad, &nonFloating);
2500
2501 QSet<QGraphicsLayoutItem *> floatItems;
2502 for (QGraphicsLayoutItem *item : std::as_const(items)) {
2503 if (!nonFloating.contains(item))
2504 floatItems.insert(item);
2505 }
2506 m_floatItems[orientation] = std::move(floatItems);
2507}
2508
2509
2510/*!
2511 \internal
2512
2513 Given an anchor, if it is an internal anchor and Normal we must mark it's item as non-float.
2514 If the anchor is Sequential or Parallel, we must iterate on its children recursively until we reach
2515 internal anchors (items).
2516*/
2517void QGraphicsAnchorLayoutPrivate::identifyNonFloatItems_helper(const AnchorData *ad, QSet<QGraphicsLayoutItem *> *nonFloatingItemsIdentifiedSoFar)
2518{
2519 Q_Q(QGraphicsAnchorLayout);
2520
2521 switch(ad->type) {
2522 case AnchorData::Normal:
2523 if (ad->item && ad->item != q)
2524 nonFloatingItemsIdentifiedSoFar->insert(ad->item);
2525 break;
2526 case AnchorData::Sequential:
2527 for (const AnchorData *d : static_cast<const SequentialAnchorData *>(ad)->m_edges)
2528 identifyNonFloatItems_helper(d, nonFloatingItemsIdentifiedSoFar);
2529 break;
2530 case AnchorData::Parallel:
2531 identifyNonFloatItems_helper(static_cast<const ParallelAnchorData *>(ad)->firstEdge, nonFloatingItemsIdentifiedSoFar);
2532 identifyNonFloatItems_helper(static_cast<const ParallelAnchorData *>(ad)->secondEdge, nonFloatingItemsIdentifiedSoFar);
2533 break;
2534 }
2535}
2536
2537/*!
2538 \internal
2539
2540 Use the current vertices distance to calculate and set the geometry of
2541 each item.
2542*/
2543void QGraphicsAnchorLayoutPrivate::setItemsGeometries(const QRectF &geom)
2544{
2545 Q_Q(QGraphicsAnchorLayout);
2546 AnchorVertex *firstH, *secondH, *firstV, *secondV;
2547
2548 qreal top;
2549 qreal left;
2550 qreal right;
2551
2552 q->getContentsMargins(&left, &top, &right, nullptr);
2553 const Qt::LayoutDirection visualDir = visualDirection();
2554 if (visualDir == Qt::RightToLeft)
2555 qSwap(left, right);
2556
2557 left += geom.left();
2558 top += geom.top();
2559 right = geom.right() - right;
2560
2561 for (QGraphicsLayoutItem *item : std::as_const(items)) {
2562 QRectF newGeom;
2563 QSizeF itemPreferredSize = item->effectiveSizeHint(Qt::PreferredSize);
2564 if (m_floatItems[Qt::Horizontal].contains(item)) {
2565 newGeom.setLeft(0);
2566 newGeom.setRight(itemPreferredSize.width());
2567 } else {
2568 firstH = internalVertex(item, Qt::AnchorLeft);
2569 secondH = internalVertex(item, Qt::AnchorRight);
2570
2571 if (visualDir == Qt::LeftToRight) {
2572 newGeom.setLeft(left + firstH->distance);
2573 newGeom.setRight(left + secondH->distance);
2574 } else {
2575 newGeom.setLeft(right - secondH->distance);
2576 newGeom.setRight(right - firstH->distance);
2577 }
2578 }
2579
2580 if (m_floatItems[Qt::Vertical].contains(item)) {
2581 newGeom.setTop(0);
2582 newGeom.setBottom(itemPreferredSize.height());
2583 } else {
2584 firstV = internalVertex(item, Qt::AnchorTop);
2585 secondV = internalVertex(item, Qt::AnchorBottom);
2586
2587 newGeom.setTop(top + firstV->distance);
2588 newGeom.setBottom(top + secondV->distance);
2589 }
2590
2591 item->setGeometry(newGeom);
2592 }
2593}
2594
2595/*!
2596 \internal
2597
2598 Calculate the position of each vertex based on the paths to each of
2599 them as well as the current edges sizes.
2600*/
2601void QGraphicsAnchorLayoutPrivate::calculateVertexPositions(Qt::Orientation orientation)
2602{
2603 QQueue<std::pair<AnchorVertex *, AnchorVertex *> > queue;
2604 QSet<AnchorVertex *> visited;
2605
2606 // Get root vertex
2607 AnchorVertex *root = layoutFirstVertex[orientation];
2608
2609 root->distance = 0;
2610 visited.insert(root);
2611
2612 // Add initial edges to the queue
2613 const auto adjacentVertices = graph[orientation].adjacentVertices(root);
2614 for (AnchorVertex *v : adjacentVertices)
2615 queue.enqueue(std::pair(root, v));
2616
2617 // Do initial calculation required by "interpolateEdge()"
2618 setupEdgesInterpolation(orientation);
2619
2620 // Traverse the graph and calculate vertex positions
2621 while (!queue.isEmpty()) {
2622 std::pair<AnchorVertex *, AnchorVertex *> pair = queue.dequeue();
2623 AnchorData *edge = graph[orientation].edgeData(pair.first, pair.second);
2624
2625 if (visited.contains(pair.second))
2626 continue;
2627
2628 visited.insert(pair.second);
2629 interpolateEdge(pair.first, edge);
2630
2631 const QList<AnchorVertex *> adjacents = graph[orientation].adjacentVertices(pair.second);
2632 for (AnchorVertex *av : adjacents) {
2633 if (!visited.contains(av))
2634 queue.enqueue(std::pair(pair.second, av));
2635 }
2636 }
2637}
2638
2639/*!
2640 \internal
2641
2642 Calculate interpolation parameters based on current Layout Size.
2643 Must be called once before calling "interpolateEdgeSize()" for
2644 the edges.
2645*/
2646void QGraphicsAnchorLayoutPrivate::setupEdgesInterpolation(
2647 Qt::Orientation orientation)
2648{
2649 Q_Q(QGraphicsAnchorLayout);
2650
2651 qreal current;
2652 current = (orientation == Qt::Horizontal) ? q->contentsRect().width() : q->contentsRect().height();
2653
2654 std::pair<Interval, qreal> result;
2655 result = getFactor(current,
2656 sizeHints[orientation][Qt::MinimumSize],
2657 sizeHints[orientation][Qt::PreferredSize],
2658 sizeHints[orientation][Qt::PreferredSize],
2659 sizeHints[orientation][Qt::PreferredSize],
2660 sizeHints[orientation][Qt::MaximumSize]);
2661
2662 interpolationInterval[orientation] = result.first;
2663 interpolationProgress[orientation] = result.second;
2664}
2665
2666/*!
2667 \internal
2668
2669 Calculate the current Edge size based on the current Layout size and the
2670 size the edge is supposed to have when the layout is at its:
2671
2672 - minimum size,
2673 - preferred size,
2674 - maximum size.
2675
2676 These three key values are calculated in advance using linear
2677 programming (more expensive) or the simplification algorithm, then
2678 subsequential resizes of the parent layout require a simple
2679 interpolation.
2680*/
2681void QGraphicsAnchorLayoutPrivate::interpolateEdge(AnchorVertex *base, AnchorData *edge)
2682{
2683 const Qt::Orientation orientation = edge->isVertical ? Qt::Vertical : Qt::Horizontal;
2684 const std::pair<Interval, qreal> factor(interpolationInterval[orientation],
2685 interpolationProgress[orientation]);
2686
2687 qreal edgeDistance = interpolate(factor, edge->sizeAtMinimum, edge->sizeAtPreferred,
2688 edge->sizeAtPreferred, edge->sizeAtPreferred,
2689 edge->sizeAtMaximum);
2690
2691 Q_ASSERT(edge->from == base || edge->to == base);
2692
2693 // Calculate the distance for the vertex opposite to the base
2694 if (edge->from == base) {
2695 edge->to->distance = base->distance + edgeDistance;
2696 } else {
2697 edge->from->distance = base->distance - edgeDistance;
2698 }
2699}
2700
2701bool QGraphicsAnchorLayoutPrivate::solveMinMax(const QList<QSimplexConstraint *> &constraints,
2702 const GraphPath &path, qreal *min, qreal *max)
2703{
2704 QSimplex simplex;
2705 bool feasible = simplex.setConstraints(constraints);
2706 if (feasible) {
2707 // Obtain the objective constraint
2708 QSimplexConstraint objective;
2709 for (AnchorData * ad: path.positives)
2710 objective.variables.insert(ad, 1.0);
2711
2712 for (AnchorData *ad : path.negatives)
2713 objective.variables.insert(ad, -1.0);
2714
2715 const qreal objectiveOffset = (path.positives.size() - path.negatives.size()) * g_offset;
2716 simplex.setObjective(&objective);
2717
2718 // Calculate minimum values
2719 *min = simplex.solveMin() - objectiveOffset;
2720
2721 // Save sizeAtMinimum results
2722 const QList<AnchorData *> variables = getVariables(constraints);
2723 for (AnchorData *ad : variables)
2724 ad->sizeAtMinimum = ad->result - g_offset;
2725
2726 // Calculate maximum values
2727 *max = simplex.solveMax() - objectiveOffset;
2728
2729 // Save sizeAtMaximum results
2730 for (AnchorData *ad : variables)
2731 ad->sizeAtMaximum = ad->result - g_offset;
2732 }
2733 return feasible;
2734}
2735
2736enum slackType { Grower = -1, Shrinker = 1 };
2737static auto createSlack(QSimplexConstraint *sizeConstraint, qreal interval, slackType type)
2738{
2739 struct R {
2740 QConcreteSimplexVariable *slack;
2741 QSimplexConstraint *limit;
2742 };
2743
2744 auto slack = new QConcreteSimplexVariable;
2745 sizeConstraint->variables.insert(slack, type);
2746
2748 limit->variables.insert(slack, 1.0);
2749 limit->ratio = QSimplexConstraint::LessOrEqual;
2750 limit->constant = interval;
2751
2752 return R{slack, limit};
2753}
2754
2755bool QGraphicsAnchorLayoutPrivate::solvePreferred(const QList<QSimplexConstraint *> &constraints,
2756 const QList<AnchorData *> &variables)
2757{
2758 QList<QSimplexConstraint *> preferredConstraints;
2759 QList<QConcreteSimplexVariable *> preferredVariables;
2760 QSimplexConstraint objective;
2761
2762 // Fill the objective coefficients for this variable. In the
2763 // end the objective function will be
2764 //
2765 // z = n * (A_shrinker_hard + A_grower_hard + B_shrinker_hard + B_grower_hard + ...) +
2766 // (A_shrinker_soft + A_grower_soft + B_shrinker_soft + B_grower_soft + ...)
2767 //
2768 // where n is the number of variables that have
2769 // slacks. Note that here we use the number of variables
2770 // as coefficient, this is to mark the "shrinker slack
2771 // variable" less likely to get value than the "grower
2772 // slack variable".
2773
2774 // This will fill the values for the structural constraints
2775 // and we now fill the values for the slack constraints (one per variable),
2776 // which have this form (the constant A_pref was set when creating the slacks):
2777 //
2778 // A + A_shrinker_hard + A_shrinker_soft - A_grower_hard - A_grower_soft = A_pref
2779 //
2780 for (AnchorData *ad : variables) {
2781 // The layout original structure anchors are not relevant in preferred size calculation
2782 if (ad->isLayoutAnchor)
2783 continue;
2784
2785 // By default, all variables are equal to their preferred size. If they have room to
2786 // grow or shrink, such flexibility will be added by the additional variables below.
2787 QSimplexConstraint *sizeConstraint = new QSimplexConstraint;
2788 preferredConstraints += sizeConstraint;
2789 sizeConstraint->variables.insert(ad, 1.0);
2790 sizeConstraint->constant = ad->prefSize + g_offset;
2791
2792 // Can easily shrink
2793 const qreal softShrinkInterval = ad->prefSize - ad->minPrefSize;
2794 if (softShrinkInterval) {
2795 auto r = createSlack(sizeConstraint, softShrinkInterval, Shrinker);
2796 preferredVariables += r.slack;
2797 preferredConstraints += r.limit;
2798
2799 // Add to objective with ratio == 1 (soft)
2800 objective.variables.insert(r.slack, 1.0);
2801 }
2802
2803 // Can easily grow
2804 const qreal softGrowInterval = ad->maxPrefSize - ad->prefSize;
2805 if (softGrowInterval) {
2806 auto r = createSlack(sizeConstraint, softGrowInterval, Grower);
2807 preferredVariables += r.slack;
2808 preferredConstraints += r.limit;
2809
2810 // Add to objective with ratio == 1 (soft)
2811 objective.variables.insert(r.slack, 1.0);
2812 }
2813
2814 // Can shrink if really necessary
2815 const qreal hardShrinkInterval = ad->minPrefSize - ad->minSize;
2816 if (hardShrinkInterval) {
2817 auto r = createSlack(sizeConstraint, hardShrinkInterval, Shrinker);
2818 preferredVariables += r.slack;
2819 preferredConstraints += r.limit;
2820
2821 // Add to objective with ratio == N (hard)
2822 objective.variables.insert(r.slack, variables.size());
2823 }
2824
2825 // Can grow if really necessary
2826 const qreal hardGrowInterval = ad->maxSize - ad->maxPrefSize;
2827 if (hardGrowInterval) {
2828 auto r = createSlack(sizeConstraint, hardGrowInterval, Grower);
2829 preferredVariables += r.slack;
2830 preferredConstraints += r.limit;
2831
2832 // Add to objective with ratio == N (hard)
2833 objective.variables.insert(r.slack, variables.size());
2834 }
2835 }
2836
2837 QSimplex *simplex = new QSimplex;
2838 bool feasible = simplex->setConstraints(constraints + preferredConstraints);
2839 if (feasible) {
2840 simplex->setObjective(&objective);
2841
2842 // Calculate minimum values
2843 simplex->solveMin();
2844
2845 // Save sizeAtPreferred results
2846 for (AnchorData *ad : variables)
2847 ad->sizeAtPreferred = ad->result - g_offset;
2848 }
2849
2850 // Make sure we delete the simplex solver -before- we delete the
2851 // constraints used by it.
2852 delete simplex;
2853
2854 // Delete constraints and variables we created.
2855 qDeleteAll(preferredConstraints);
2856 qDeleteAll(preferredVariables);
2857
2858 return feasible;
2859}
2860
2861/*!
2862 \internal
2863 Returns \c true if there are no arrangement that satisfies all constraints.
2864 Otherwise returns \c false.
2865
2866 \sa addAnchor()
2867*/
2868bool QGraphicsAnchorLayoutPrivate::hasConflicts() const
2869{
2870 QGraphicsAnchorLayoutPrivate *that = const_cast<QGraphicsAnchorLayoutPrivate*>(this);
2871 that->calculateGraphs();
2872
2873 bool floatConflict = !m_floatItems[Qt::Horizontal].isEmpty() || !m_floatItems[Qt::Vertical].isEmpty();
2874
2875 return graphHasConflicts[Qt::Horizontal] || graphHasConflicts[Qt::Vertical] || floatConflict;
2876}
2877
2878#ifdef QT_DEBUG
2879void QGraphicsAnchorLayoutPrivate::dumpGraph(const QString &name)
2880{
2881 QFile file(QString::fromLatin1("anchorlayout.%1.dot").arg(name));
2882 if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
2883 qWarning("Could not write to %ls", qUtf16Printable(file.fileName()));
2884
2885 QString str = QString::fromLatin1("digraph anchorlayout {\nnode [shape=\"rect\"]\n%1}");
2886 QString dotContents = graph[Qt::Horizontal].serializeToDot();
2887 dotContents += graph[Qt::Vertical].serializeToDot();
2888 file.write(str.arg(dotContents).toLocal8Bit());
2889
2890 file.close();
2891}
2892#endif
2893
2894QT_END_NAMESPACE
void setSizePolicy(QSizePolicy::Policy policy)
QGraphicsAnchorLayoutPrivate * layoutPrivate
QSimplexConstraint * constraint(const GraphPath &path) const
static auto createSlack(QSimplexConstraint *sizeConstraint, qreal interval, slackType type)
static AnchorData * createSequence(Graph< AnchorVertex, AnchorData > *graph, AnchorVertex *before, const QList< AnchorVertex * > &vertices, AnchorVertex *after)
const qreal g_offset
static void applySizePolicy(QSizePolicy::Policy policy, qreal minSizeHint, qreal prefSizeHint, qreal maxSizeHint, qreal *minSize, qreal *prefSize, qreal *maxSize)
static AnchorVertex * replaceVertex_helper(AnchorData *data, AnchorVertex *oldV, AnchorVertex *newV)
static void shiftConstraints(const QList< QSimplexConstraint * > &constraints, qreal amount)
static qreal interpolate(const std::pair< QGraphicsAnchorLayoutPrivate::Interval, qreal > &factor, qreal min, qreal minPref, qreal pref, qreal maxPref, qreal max)
static std::pair< QGraphicsAnchorLayoutPrivate::Interval, qreal > getFactor(qreal value, qreal min, qreal minPref, qreal pref, qreal maxPref, qreal max)
QList< AnchorData * > getVariables(const QList< QSimplexConstraint * > &constraints)
void refreshSizeHints(const QLayoutStyleInfo *styleInfo=nullptr)