Debian Codegraph @

src/imports/Layouts/plugin/ullayouts.cpp

raw
1 /*
2 * Copyright 2013 Canonical Ltd.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License as published by
6 * the Free Software Foundation; version 3.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 * Author: Zsombor Egri <[email protected]>
17 */
18
19 #include "ullayouts_p.h"
20
21 #include <QtQml/QQmlInfo>
22 #include <QtQuick/private/qquickitem_p.h>
23
24 #include "ulitemlayout.h"
25 #include "ulconditionallayout.h"
26 #include "propertychanges_p.h"
27
28 ULLayoutsPrivate::ULLayoutsPrivate(ULLayouts *qq)
29 : QQmlIncubator(Asynchronous)
30 , q_ptr(qq)
31 , currentLayoutItem(0)
32 , previousLayoutItem(0)
33 , contentItem(new QQuickItem)
34 , currentLayoutIndex(-1)
35 , ready(false)
36 {
37 // hidden container for the components that are not laid out
38 // any component not subject of layout is reparented into this component
39 contentItem->setParent(qq);
40 contentItem->setParentItem(qq);
41 }
42
43
44 /******************************************************************************
45 * QQmlListProperty functions
46 */
47 void ULLayoutsPrivate::append_layout(QQmlListProperty<ULConditionalLayout> *list, ULConditionalLayout *layout)
48 {
49 ULLayouts *_this = static_cast<ULLayouts*>(list->object);
50 if (layout) {
51 layout->setParent(_this);
52 _this->d_ptr->layouts.append(layout);
53 }
54 }
55
56 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
57 qsizetype ULLayoutsPrivate::count_layouts(QQmlListProperty<ULConditionalLayout> *list)
58 #else
59 int ULLayoutsPrivate::count_layouts(QQmlListProperty<ULConditionalLayout> *list)
60 #endif
61 {
62 ULLayouts *_this = static_cast<ULLayouts*>(list->object);
63 return _this->d_ptr->layouts.count();
64 }
65
66 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
67 ULConditionalLayout *ULLayoutsPrivate::at_layout(QQmlListProperty<ULConditionalLayout> *list, qsizetype index)
68 #else
69 ULConditionalLayout *ULLayoutsPrivate::at_layout(QQmlListProperty<ULConditionalLayout> *list, int index)
70 #endif
71 {
72 ULLayouts *_this = static_cast<ULLayouts*>(list->object);
73 return _this->d_ptr->layouts.at(index);
74 }
75
76 void ULLayoutsPrivate::clear_layouts(QQmlListProperty<ULConditionalLayout> *list)
77 {
78 ULLayouts *_this = static_cast<ULLayouts*>(list->object);
79 _this->d_ptr->layouts.clear();
80 }
81
82
83 /******************************************************************************
84 * ULLayoutsPrivate also acts as QQmlIncubator for the dynamically created layouts.
85 * QQmlIncubator stuff
86 */
87 void ULLayoutsPrivate::setInitialState(QObject *object)
88 {
89 Q_Q(ULLayouts);
90 // object context's parent is the creation context; link it to the object so we
91 // delete them together
92 qmlContext(object)->parentContext()->setParent(object);
93 // set parent
94 object->setParent(q);
95 QQuickItem *item = static_cast<QQuickItem*>(object);
96 // set disabled and invisible, and set its parent as last action
97 item->setVisible(false);
98 }
99
100 /*
101 * Called upon QQmlComponent::create() to notify the status of the component
102 * creation.
103 */
104 void ULLayoutsPrivate::statusChanged(Status status)
105 {
106 Q_Q(ULLayouts);
107 if (status == Ready) {
108 // complete layouting
109 previousLayoutItem = currentLayoutItem;
110
111 // reset the layout
112 currentLayoutItem = qobject_cast<QQuickItem*>(object());
113 Q_ASSERT(currentLayoutItem);
114
115 //reparent components to be laid out
116 reparentItems();
117 // set parent item, then enable and show layout
118 changes.addChange(new ParentChange(currentLayoutItem, q, false));
119
120 // hide default layout, then show the new one
121 // there's no need to queue these property changes as we do not need
122 // to back up their previosus states
123 contentItem->setVisible(false);
124 currentLayoutItem->setVisible(true);
125 // apply changes
126 changes.apply();
127 // clear previous layout
128 delete previousLayoutItem;
129 previousLayoutItem = 0;
130
131 Q_EMIT q->currentLayoutChanged();
132 } else if (status == Error) {
133 error(q, errors());
134 }
135 }
136
137 /*
138 * Re-parent items to the new layout.
139 */
140 void ULLayoutsPrivate::reparentItems()
141 {
142 // create copy of items list, to keep track of which ones we change
143 LaidOutItemsMap unusedItems = itemsToLayout;
144
145 // iterate through the Layout definition to find containers - ItemLayout items
146 QList<ULItemLayout*> containers = collectContainers(currentLayoutItem);
147
148 Q_FOREACH(ULItemLayout *container, containers) {
149 reparentToItemLayout(unusedItems, container);
150 }
151 }
152
153 QList<ULItemLayout*> ULLayoutsPrivate::collectContainers(QQuickItem *fromItem)
154 {
155 QList<ULItemLayout*> result;
156 // check first if the fromItem is also a container
157 ULItemLayout *container = qobject_cast<ULItemLayout*>(fromItem);
158 if (container) {
159 result.append(container);
160 }
161
162 // loop through children but exclude nested Layouts
163 QList<QQuickItem*> children = fromItem->childItems();
164 Q_FOREACH(QQuickItem *child, children) {
165 if (qobject_cast<ULLayouts*>(child)) {
166 continue;
167 }
168 result.append(collectContainers(child));
169 }
170 return result;
171 }
172
173 /*
174 * Re-parent to ItemLayout.
175 */
176 void ULLayoutsPrivate::reparentToItemLayout(LaidOutItemsMap &map, ULItemLayout *fragment)
177 {
178 QString itemName = fragment->item();
179 if (itemName.isEmpty()) {
180 warning(fragment, "item not specified for ItemLayout");
181 return;
182 }
183
184 QQuickItem *item = map.value(itemName);
185 if (!item) {
186 warning(fragment, "item \"" + itemName
187 + "\" not specified or has been specified for layout by"
188 " more than one active ItemLayout");
189 return;
190 }
191
192 // the component fills the parent
193 changes.addParentChange(item, fragment, true);
194 changes.addChange(new AnchorChange(item, "fill", fragment));
195 changes.addChange(new PropertyChange(item, "anchors.margins", 0));
196 changes.addChange(new PropertyChange(item, "anchors.leftMargin", 0));
197 changes.addChange(new PropertyChange(item, "anchors.topMargin", 0));
198 changes.addChange(new PropertyChange(item, "anchors.rightMargin", 0));
199 changes.addChange(new PropertyChange(item, "anchors.bottomMargin", 0));
200 // backup size
201 changes.addChange(new PropertyBackup(item, "width"));
202 changes.addChange(new PropertyBackup(item, "height"));
203 // break and backup anchors
204 changes.addChange(new AnchorBackup(item));
205
206 // remove from unused ones
207 map.remove(itemName);
208 }
209
210 /*
211 * Validates the declared conditional layouts by checking whether they have name
212 * property set and whether the value set is unique, and whether the conditional
213 * layout has container defined.
214 */
215 void ULLayoutsPrivate::validateConditionalLayouts()
216 {
217 Q_Q(ULLayouts);
218
219 QStringList names;
220 for (int i = 0; i < layouts.count(); i++) {
221 ULConditionalLayout *layout = layouts[i];
222 if (!layout) {
223 error(q, "Error in layout definitions!");
224 continue;
225 }
226
227 if (layout->layoutName().isEmpty()) {
228 warning(layout, "No name specified for layout. ConditionalLayout cannot be activated without name.");
229 continue;
230 }
231 if (names.contains(layout->layoutName())) {
232 warning(layout, "layout name \"" + layout->layoutName()
233 + "\" not unique. Layout may not behave as expected.");
234 }
235
236 if (!layout->layout()) {
237 error(layout, "no container specified for layout \"" + layout->layoutName() +
238 "\". ConditionalLayout cannot be activated without a container.");
239 continue;
240 }
241
242 }
243 }
244
245 /*
246 * Collect items to be laid out.
247 */
248 void ULLayoutsPrivate::getLaidOutItems(QQuickItem *container)
249 {
250 Q_FOREACH(QQuickItem *child, container->childItems()) {
251 // skip nested layouts
252 if (qobject_cast<ULLayouts*>(child)) {
253 continue;
254 }
255 ULLayoutsAttached *marker = qobject_cast<ULLayoutsAttached*>(
256 qmlAttachedPropertiesObject<ULLayouts>(child, false));
257 if (marker && !marker->item().isEmpty()) {
258 itemsToLayout.insert(marker->item(), child);
259 } else {
260 // continue to search in between the child's children
261 getLaidOutItems(child);
262 }
263 }
264 }
265
266 /*
267 * Apply layout change. The new layout creation will be completed in statusChange().
268 */
269 void ULLayoutsPrivate::reLayout()
270 {
271 if (!ready || (currentLayoutIndex < 0)) {
272 return;
273 }
274 if (!layouts[currentLayoutIndex]->layout()) {
275 return;
276 }
277
278 // redo changes
279 changes.revert();
280 changes.clear();
281
282 // clear the incubator before using it
283 clear();
284 QQmlComponent *component = layouts[currentLayoutIndex]->layout();
285 // create using incubation as it may be created asynchronously,
286 // case when the attached properties are not yet enumerated
287 Q_Q(ULLayouts);
288 QQmlContext *context = new QQmlContext(qmlContext(q), q);
289 component->create(*this, context);
290 }
291
292 /*
293 * Updates the current layout.
294 */
295 void ULLayoutsPrivate::updateLayout()
296 {
297 if (!ready) {
298 return;
299 }
300
301 // go through conditions and re-parent for the first valid one
302 for (int i = 0; i < layouts.count(); i++) {
303 ULConditionalLayout *layout = layouts[i];
304 if (!layout->layout()) {
305 warning(layout, "Cannot activate layout \"" + layout->layoutName() +
306 "\" with no container specified. Falling back to default layout.");
307 break;
308 }
309 if (!layout->layoutName().isEmpty() && layout->when()) {
310 if (currentLayoutIndex == i) {
311 return;
312 }
313 currentLayoutIndex = i;
314 // update layout
315 reLayout();
316 return;
317 }
318 }
319 // check if we need to switch back to default layout
320 if (currentLayoutIndex >= 0) {
321 // cancel any pending layout incubation
322 QQmlIncubator::clear();
323 // revert and clear changes
324 changes.revert();
325 changes.clear();
326 // make contentItem visible
327
328 contentItem->setVisible(true);
329 delete currentLayoutItem;
330 currentLayoutItem = 0;
331 currentLayoutIndex = -1;
332 Q_Q(ULLayouts);
333 Q_EMIT q->currentLayoutChanged();
334 }
335 }
336
337 void ULLayoutsPrivate::error(QObject *item, const QString &message)
338 {
339 qmlWarning(item) << "ERROR: " << message;
340 QQmlEngine *engine = qmlEngine(item);
341 if (engine) {
342 engine->quit();
343 }
344 }
345
346 void ULLayoutsPrivate::error(QObject *item, const QList<QQmlError> &errors)
347 {
348 qmlWarning(item, errors);
349 QQmlEngine *engine = qmlEngine(item);
350 if (engine) {
351 engine->quit();
352 }
353 }
354
355 void ULLayoutsPrivate::warning(QObject *item, const QString &message)
356 {
357 qmlWarning(item) << "WARNING: " << message;
358 }
359
360
361 /*!
362 * \qmltype Layouts
363 * \instantiates ULLayouts
364 * \inqmlmodule Lomiri.Layouts 1.0
365 * \ingroup lomiri-layouts
366 * \brief The Layouts component allows one to specify multiple different layouts for a
367 * fixed set of Items, and applies the desired layout to those Items.
368 *
369 * Layouts is a layout block component incorporating layout definitions and
370 * components to lay out. The layouts are defined in the \l layouts property, which
371 * is a list of ConditionalLayout components, each declaring the sizes and positions
372 * of the components specified to be laid out.
373 *
374 * \qml
375 * Layouts {
376 * id: layouts
377 * layouts: [
378 * ConditionalLayout {
379 * name: "flow"
380 * when: layouts.width > units.gu(60) && layouts.width <= units.gu(100)
381 * Flow {
382 * anchors.fill: parent
383 * //[...]
384 * }
385 * },
386 * ConditionalLayout {
387 * name: "column"
388 * when: layouts.width > units.gu(100)
389 * Flickable {
390 * anchors.fill: parent
391 * contentHeight: column.childrenRect.height
392 * Column {
393 * id: column
394 * //[...]
395 * }
396 * }
397 * }
398 * ]
399 * }
400 * \endqml
401 *
402 * The components to be laid out must be declared as children of the Layouts component,
403 * each set an attached property "Layouts.item" to be a unique string.
404 *
405 * \qml
406 * Layouts {
407 * id: layouts
408 * layouts: [
409 * ConditionalLayout {
410 * name: "flow"
411 * when: layouts.width > units.gu(60) && layouts.width <= units.gu(100)
412 * Flow {
413 * anchors.fill: parent
414 * //[...]
415 * }
416 * },
417 * ConditionalLayout {
418 * name: "column"
419 * when: layouts.width > units.gu(100)
420 * Flickable {
421 * anchors.fill: parent
422 * contentHeight: column.childrenRect.height
423 * Column {
424 * id: column
425 * //[...]
426 * }
427 * }
428 * }
429 * ]
430 *
431 * Row {
432 * anchors.fill: parent
433 * Button {
434 * text: "Press me"
435 * Layouts.item: "item1"
436 * }
437 * Button {
438 * text: "Cancel"
439 * Layouts.item: "item2"
440 * }
441 * }
442 * }
443 * \endqml
444 *
445 * The layout of the children of Layouts is considered the default layout, i.e.
446 * currentLayout is an empty string. So in the above example, the buttons arranged
447 * in a row is the default layout.
448 *
449 * The layouts defined by ConditionalLayout components are created and activated
450 * when at least one of the layout's condition is evaluated to true. In which
451 * case components marked for layout are re-parented to the components defined
452 * to lay out those defined in the ConditionalLayout. In case multiple conditions
453 * are evaluated to true, the first one in the list will be activated. The deactivated
454 * layout is destroyed, exception being the default layout, which is kept in memory for
455 * the entire lifetime of the Layouts component.
456 *
457 * Upon activation, the created component fills in the entire layout block.
458 *
459 * \qml
460 * Layouts {
461 * id: layouts
462 * layouts: [
463 * ConditionalLayout {
464 * name: "flow"
465 * when: layouts.width > units.gu(60) && layouts.width <= units.gu(100)
466 * Flow {
467 * anchors.fill: parent
468 * ItemLayout {
469 * item: "item1"
470 * }
471 * ItemLayout {
472 * item: "item2"
473 * }
474 * }
475 * },
476 * ConditionalLayout {
477 * name: "column"
478 * when: layouts.width > units.gu(100)
479 * Flickable {
480 * anchors.fill: parent
481 * contentHeight: column.childrenRect.height
482 * Column {
483 * id: column
484 * ItemLayout {
485 * item: "item1"
486 * }
487 * ItemLayout {
488 * item: "item2"
489 * }
490 * }
491 * }
492 * }
493 * ]
494 *
495 * Row {
496 * anchors.fill: parent
497 * Button {
498 * text: "Press me"
499 * Layouts.item: "item1"
500 * }
501 * Button {
502 * text: "Cancel"
503 * Layouts.item: "item2"
504 * }
505 * }
506 * }
507 * \endqml
508 *
509 * Conditional layouts must be named in order to be activatable. These names (strings)
510 * should be unique within a Layouts item and can be used to identify changes in
511 * between layouts in scripts, so additional layout specific customization on laid
512 * out items can be done. The current layout is presented by the currentLayout
513 * property.
514 *
515 * Extending the previous example by changing the button color to green when the
516 * current layout is "column", the code would look as follows:
517 * \qml
518 * Layouts {
519 * id: layouts
520 * layouts: [
521 * ConditionalLayout {
522 * name: "flow"
523 * when: layouts.width > units.gu(60) && layouts.width <= units.gu(100)
524 * Flow {
525 * anchors.fill: parent
526 * ItemLayout {
527 * item: "item1"
528 * }
529 * ItemLayout {
530 * item: "item2"
531 * }
532 * }
533 * },
534 * ConditionalLayout {
535 * name: "column"
536 * when: layouts.width > units.gu(100)
537 * Flickable {
538 * anchors.fill: parent
539 * contentHeight: column.childrenRect.height
540 * Column {
541 * id: column
542 * ItemLayout {
543 * item: "item1"
544 * }
545 * ItemLayout {
546 * item: "item2"
547 * }
548 * }
549 * }
550 * }
551 * ]
552 *
553 * Row {
554 * anchors.fill: parent
555 * Button {
556 * text: "Press me"
557 * Layouts.item: "item1"
558 * color: (layouts.currentLayout === "column") ? "green" : "gray"
559 * }
560 * Button {
561 * text: "Cancel"
562 * Layouts.item: "item2"
563 * color: (layouts.currentLayout === "column") ? "green" : "gray"
564 * }
565 * }
566 * }
567 * \endqml
568 */
569
570 ULLayouts::ULLayouts(QQuickItem *parent):
571 QQuickItem(parent),
572 d_ptr(new ULLayoutsPrivate(this))
573 {
574 }
575
576 ULLayouts::~ULLayouts()
577 {
578 }
579
580 ULLayoutsAttached * ULLayouts::qmlAttachedProperties(QObject *owner)
581 {
582 return new ULLayoutsAttached(owner);
583 }
584
585 void ULLayouts::componentComplete()
586 {
587 QQuickItem::componentComplete();
588 Q_D(ULLayouts);
589 d->ready = true;
590 d->validateConditionalLayouts();
591 d->getLaidOutItems(d->contentItem);
592 d->updateLayout();
593 }
594
595 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
596 void ULLayouts::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry)
597 {
598 Q_D(ULLayouts);
599 QQuickItem::geometryChange(newGeometry, oldGeometry);
600 #else
601 void ULLayouts::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
602 {
603 Q_D(ULLayouts);
604 QQuickItem::geometryChanged(newGeometry, oldGeometry);
605 #endif
606 // simply update the container's width/height to the new width/height
607 d->contentItem->setSize(newGeometry.size());
608 }
609
610 /*!
611 * \qmlproperty string Layouts::currentLayout
612 * The property holds the active layout name. The default layout is identified
613 * by an empty string. This property can be used for additional customization
614 * of the components which are not supported by the layouting.
615 */
616
617 QString ULLayouts::currentLayout() const
618 {
619 Q_D(const ULLayouts);
620 return d->currentLayoutIndex >= 0 ? d->layouts[d->currentLayoutIndex]->layoutName() : QString();
621 }
622
623 /*!
624 * \internal
625 * Provides a list of layouts for internal use.
626 */
627 QList<ULConditionalLayout*> ULLayouts::layoutList()
628 {
629 Q_D(ULLayouts);
630 return d->layouts;
631 }
632
633 /*!
634 * \internal
635 * Returns the contentItem for internal use.
636 */
637 QQuickItem *ULLayouts::contentItem() const
638 {
639 Q_D(const ULLayouts);
640 return d->contentItem;
641 }
642
643
644 /*!
645 * \qmlproperty list<ConditionalLayout> Layouts::layouts
646 * The property holds the list of different ConditionalLayout elements.
647 */
648 QQmlListProperty<ULConditionalLayout> ULLayouts::layouts()
649 {
650 Q_D(ULLayouts);
651 return QQmlListProperty<ULConditionalLayout>(this, &(d->layouts),
652 &ULLayoutsPrivate::append_layout,
653 &ULLayoutsPrivate::count_layouts,
654 &ULLayoutsPrivate::at_layout,
655 &ULLayoutsPrivate::clear_layouts);
656 }
657
658 /*!
659 * \internal
660 * Overrides the default data property.
661 */
662 QQmlListProperty<QObject> ULLayouts::data()
663 {
664 Q_D(ULLayouts);
665 return QQuickItemPrivate::get(d->contentItem)->data();
666 }
667
668 /*!
669 * \internal
670 * Overrides the default children property.
671 */
672 QQmlListProperty<QQuickItem> ULLayouts::children()
673 {
674 Q_D(ULLayouts);
675 return QQuickItemPrivate::get(d->contentItem)->children();
676 }
677
678
679 #include "moc_ullayouts.cpp"