aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmldesigner/components/componentcore/layoutingridlayout.cpp
blob: a1629c0b5bc95b221591ab7903225c116d03ec2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "layoutingridlayout.h"

#include <nodeabstractproperty.h>
#include <nodemetainfo.h>
#include <variantproperty.h>
#include <bindingproperty.h>
#include <rewritertransaction.h>

#include <utils/qtcassert.h>

#include <utils/algorithm.h>

namespace QmlDesigner {

static inline void reparentTo(const ModelNode &node, const QmlItemNode &parent)
{

    if (parent.isValid() && node.isValid()) {
        NodeAbstractProperty parentProperty;

        if (parent.hasDefaultPropertyName())
            parentProperty = parent.defaultNodeAbstractProperty();
        else
            parentProperty = parent.nodeAbstractProperty("data");

        parentProperty.reparentHere(node);
    }
}

static int findFirstBigger(const QVector<int> &v, int tolerance)
{
    if (v.isEmpty())
        return 0;

    int last = v.constFirst();
    for (int i = 0; i < v.length(); ++i) {
        if (v.value(i) > last + tolerance)
            return i;
        last = v.value(i);
    }
    return v.length();
}

static void  removeSimilarValues(QVector<int> &v, int tolerance)
{
    QVector<int> newVector;

    if (v.size() < 2)
        return;

    while (!v.isEmpty()) {
        int clusterLength = findFirstBigger(v, tolerance);
        int average = v.at(0);
        newVector.append(average);
        v.remove(0, clusterLength);
    }

    v = newVector;
}

static int getCell(const QVector<int> &offsets, int offset)
{
        for (int i = 0; i < offsets.length(); ++i) {
            if (offset < offsets.at(i))
                    return i;
        }
    return offsets.length();
}

static int lowerBound(int i)
{
    if (i < 15)
        return 16;

    return i;
}

static inline QPointF getUpperLeftPosition(const QList<ModelNode> &modelNodeList)
{
    QPointF postion(std::numeric_limits<qreal>::max(), std::numeric_limits<qreal>::max());
    foreach (const ModelNode &modelNode, modelNodeList) {
        if (QmlItemNode::isValidQmlItemNode(modelNode)) {
            QmlItemNode qmlIitemNode = QmlItemNode(modelNode);
            if (qmlIitemNode.instancePosition().x() < postion.x())
                postion.setX(qmlIitemNode.instancePosition().x());
            if (qmlIitemNode.instancePosition().y() < postion.y())
                postion.setY(qmlIitemNode.instancePosition().y());
        }
    }
    return postion;
}

static void setUpperLeftPostionToNode(const ModelNode &layoutNode, const QList<ModelNode> &modelNodeList)
{
    QPointF upperLeftPosition = getUpperLeftPosition(modelNodeList);
    layoutNode.variantProperty("x").setValue(qRound(upperLeftPosition.x()));
    layoutNode.variantProperty("y").setValue(qRound(upperLeftPosition.y()));
}

void LayoutInGridLayout::reparentToNodeAndRemovePositionForModelNodes(const ModelNode &parentModelNode,
                                                                             const QList<ModelNode> &modelNodeList)
{
    foreach (ModelNode modelNode, modelNodeList) {
        reparentTo(modelNode, parentModelNode);
        modelNode.removeProperty("x");
        modelNode.removeProperty("y");
        foreach (const VariantProperty &variantProperty, modelNode.variantProperties()) {
            if (variantProperty.name().contains("anchors."))
                modelNode.removeProperty(variantProperty.name());
        }
        foreach (const BindingProperty &bindingProperty, modelNode.bindingProperties()) {
            if (bindingProperty.name().contains("anchors."))
                modelNode.removeProperty(bindingProperty.name());
        }
    }
}

void LayoutInGridLayout::setSizeAsPreferredSize(const QList<ModelNode> &modelNodeList)
{
     foreach (ModelNode modelNode, modelNodeList) {
         if (modelNode.hasVariantProperty("width")) {
             modelNode.variantProperty("Layout.preferredWidth").setValue(modelNode.variantProperty("width").value());
             modelNode.removeProperty("width");
         }
         if (modelNode.hasVariantProperty("height")) {
             modelNode.variantProperty("Layout.preferredHeight").setValue(modelNode.variantProperty("height").value());
             modelNode.removeProperty("height");
         }
     }
}

LayoutInGridLayout::LayoutInGridLayout(const QmlDesigner::SelectionContext &selectionContext) :
    m_selectionContext(selectionContext)
  ,m_startX(0)
  ,m_startY(0)
{

}

void LayoutInGridLayout::doIt()
{
    const TypeName layoutType = "QtQuick.Layouts.GridLayout";

    if (!m_selectionContext.view()
            || !m_selectionContext.hasSingleSelectedModelNode()
            || !m_selectionContext.view()->model()->hasNodeMetaInfo(layoutType))
        return;

    collectItemNodes();
    collectOffsets();
    sortOffsets();
    calculateGridOffsets();
    removeEmtpyRowsAndColumns();
    initializeCells();
    markUsedCells();

    QTC_ASSERT(m_parentNode.isValid(), return);

    if (QmlItemNode::isValidQmlItemNode(m_selectionContext.firstSelectedModelNode())) {
        const QmlItemNode qmlItemNode = QmlItemNode(m_selectionContext.firstSelectedModelNode());

        if (qmlItemNode.hasInstanceParentItem()) {

            ModelNode layoutNode;

            m_selectionContext.view()->executeInTransaction("LayoutInGridLayout1",[this, &layoutNode, layoutType](){
                QTC_ASSERT(m_selectionContext.view()->model()->hasNodeMetaInfo(layoutType), return);

                NodeMetaInfo metaInfo = m_selectionContext.view()->model()->metaInfo(layoutType);
                layoutNode = m_selectionContext.view()->createModelNode(layoutType, metaInfo.majorVersion(), metaInfo.minorVersion());
                reparentTo(layoutNode, m_parentNode);
            });

            m_selectionContext.view()->executeInTransaction("LayoutInGridLayout2", [this, layoutNode](){

                fillEmptyCells();

                QList<ModelNode> sortedSelectedNodes = m_layoutedNodes;
                Utils::sort(sortedSelectedNodes, lessThan());

                removeSpacersBySpanning(sortedSelectedNodes);

                setUpperLeftPostionToNode(layoutNode, m_selectionContext.selectedModelNodes());
                reparentToNodeAndRemovePositionForModelNodes(layoutNode, sortedSelectedNodes);
                setSizeAsPreferredSize(sortedSelectedNodes);
                setSpanning(layoutNode);
            });
        }
    }
}

bool static hasQtQuickLayoutImport(const SelectionContext &context)
{
    if (context.view() && context.view()->model()) {
        Import import = Import::createLibraryImport(QStringLiteral("QtQuick.Layouts"), QStringLiteral("1.0"));
        return context.view()->model()->hasImport(import, true, true);
    }

    return false;
}

void LayoutInGridLayout::ensureLayoutImport(const SelectionContext &context)
{
    if (!hasQtQuickLayoutImport(context)) {
        Import layoutImport = Import::createLibraryImport("QtQuick.Layouts", "1.0");
        context.view()-> model()->changeImports({layoutImport}, {});
    }
}

void LayoutInGridLayout::layout(const SelectionContext &context)
{
    LayoutInGridLayout operation(context);
    operation.doIt();
}

int LayoutInGridLayout::columnCount() const
{
    return m_xTopOffsets.count();
}

int LayoutInGridLayout::rowCount() const
{
    return m_yTopOffsets.count();
}

void LayoutInGridLayout::collectItemNodes()
{
    foreach (const ModelNode &modelNode, m_selectionContext.selectedModelNodes()) {
        if (QmlItemNode::isValidQmlItemNode(modelNode)) {
            QmlItemNode itemNode = modelNode;
            if (itemNode.instanceSize().width() > 0
                    && itemNode.instanceSize().height() > 0)
                m_qmlItemNodes.append(itemNode);
        }
    }

    if (m_qmlItemNodes.isEmpty())
        return;

    m_parentNode = m_qmlItemNodes.constFirst().instanceParentItem();
}

void LayoutInGridLayout::collectOffsets()
{
    //We collect all different x and y offsets that define the cells
    foreach (const QmlItemNode &qmlItemNode, m_qmlItemNodes) {
        int x  = qRound((qmlItemNode.instancePosition().x()));
        m_xTopOffsets.append(x);
        x  = qRound((qmlItemNode.instancePosition().x() + lowerBound(qmlItemNode.instanceBoundingRect().width())));
        m_xBottomOffsets.append(x);

        int y  = qRound((qmlItemNode.instancePosition().y()) );
        m_yTopOffsets.append(y);
        y  = qRound((qmlItemNode.instancePosition().y() + lowerBound(qmlItemNode.instanceBoundingRect().height())));
        m_yBottomOffsets.append(y);
    }
}

void LayoutInGridLayout::sortOffsets()
{
    std::sort(m_xTopOffsets.begin(), m_xTopOffsets.end());
    std::sort(m_yTopOffsets.begin(), m_yTopOffsets.end());
    std::sort(m_xBottomOffsets.begin(), m_xBottomOffsets.end());
    std::sort(m_yBottomOffsets.begin(), m_yBottomOffsets.end());
}

void LayoutInGridLayout::calculateGridOffsets()
{
    if (!m_xTopOffsets.isEmpty())
        m_startX = m_xTopOffsets.constFirst();

    if (!m_yTopOffsets.isEmpty())
        m_startY = m_yTopOffsets.constFirst();

    const int defaultWidthTolerance = 64;
    const int defaultHeightTolerance = 64;

    int widthTolerance = defaultWidthTolerance;
    int heightTolerance = defaultHeightTolerance;

    //The tolerance cannot be bigger then the size of an item
    foreach (const auto &qmlItemNode, m_qmlItemNodes) {
        widthTolerance = qMin(qmlItemNode.instanceSize().toSize().width() - 1, widthTolerance);
        heightTolerance = qMin(qmlItemNode.instanceSize().toSize().height() - 1, heightTolerance);
    }

    //Now we create clusters of similar offsets and keep only the biggest offset for each cluster

    removeSimilarValues(m_xTopOffsets, widthTolerance);
    removeSimilarValues(m_yTopOffsets, heightTolerance);
    removeSimilarValues(m_xBottomOffsets, widthTolerance);
    removeSimilarValues(m_yBottomOffsets, heightTolerance);

    m_xTopOffsets += m_xBottomOffsets;
    m_yTopOffsets += m_yBottomOffsets;

    std::sort(m_xTopOffsets.begin(), m_xTopOffsets.end());
    std::sort(m_yTopOffsets.begin(), m_yTopOffsets.end());

    removeSimilarValues(m_xTopOffsets, widthTolerance);
    removeSimilarValues(m_yTopOffsets, heightTolerance);

    //The first offset is not important, because it just defines the beginning of the layout
    m_xTopOffsets.removeFirst();
    m_yTopOffsets.removeFirst();
}

void LayoutInGridLayout::removeEmtpyRowsAndColumns()
{
    //Allocate arrays for used rows and columns and rows
    m_rows = QVector<bool>(rowCount());
    m_rows.fill(false);

    m_columns = QVector<bool>(columnCount());
    m_columns.fill(false);

    foreach (const auto &qmlItemNode, m_qmlItemNodes) {
        int xCell = getCell(m_xTopOffsets, qmlItemNode.instancePosition().x());
        int yCell = getCell(m_yTopOffsets, qmlItemNode.instancePosition().y());

        int xCellRight = getCell(m_xTopOffsets, qmlItemNode.instancePosition().x() +  lowerBound(qmlItemNode.instanceSize().width()));
        int yCellbottom = getCell(m_yTopOffsets, qmlItemNode.instancePosition().y() +  lowerBound(qmlItemNode.instanceSize().height()));
        for (int x = xCell; x < xCellRight; ++x)
            for (int y = yCell; y < yCellbottom; ++y) {
                m_columns[x] = true;
                m_rows[y] = true;
            }
    }

    for (int i = m_columns.length() - 1; i >= 0; --i)
        if (!m_columns.at(i))
            m_xTopOffsets.remove(i);

    for (int i = m_rows.length() - 1; i >= 0; --i)
        if (!m_rows.at(i))
            m_yTopOffsets.remove(i);
}

void LayoutInGridLayout::initializeCells()
{
    //Allocate array and mark cells as false.
    m_cells = QVector<bool>(columnCount() * rowCount());
    m_cells.fill(false);
}

void LayoutInGridLayout::markUsedCells()
{
    //We mark cells which are covered by items with true
    foreach (const auto &qmlItemNode, m_qmlItemNodes) {
        int xCell = getCell(m_xTopOffsets, qmlItemNode.instancePosition().x());
        int yCell = getCell(m_yTopOffsets, qmlItemNode.instancePosition().y());

        int xCellRight = getCell(m_xTopOffsets, qmlItemNode.instancePosition().x() +  lowerBound(qmlItemNode.instanceSize().width()));
        int yCellbottom = getCell(m_yTopOffsets, qmlItemNode.instancePosition().y() +  lowerBound(qmlItemNode.instanceSize().height()));

        for (int x = xCell; x < xCellRight; ++x)
            for (int y = yCell; y < yCellbottom; ++y) {
                m_cells[y * columnCount()  + x] = true;
            }
    }
}

void LayoutInGridLayout::fillEmptyCells()
{
    //Cells which are not covered by items and are not marked as true have to be filled with a "spacer" item
    m_layoutedNodes = m_selectionContext.selectedModelNodes();

    foreach (const QmlItemNode &itemNode, m_qmlItemNodes) {
        m_layoutedNodes.append(itemNode);
    }

    for (int x = 0; x < columnCount(); ++x)
        for (int y = 0; y < rowCount(); ++y)
            if (!m_cells.at(y * columnCount() + x)) { //This cell does not contain an item.
                int xPos = m_startX;
                if (x > 0)
                    xPos = m_xTopOffsets.at(x-1);

                int yPos = m_startY;
                if (y > 0)
                    yPos = m_yTopOffsets.at(y-1);

                NodeMetaInfo metaInfo = m_selectionContext.view()->model()->metaInfo("QtQuick.Item");

                ModelNode newNode = m_selectionContext.view()->createModelNode("QtQuick.Item", metaInfo.majorVersion(), metaInfo.minorVersion());

                reparentTo(newNode, m_parentNode);

                m_spacerNodes.append(newNode);

                QmlItemNode newItemNode(newNode);
                newItemNode.setVariantProperty("x", xPos);
                newItemNode.setVariantProperty("y", yPos);
                newItemNode.setVariantProperty("width", 14);
                newItemNode.setVariantProperty("height", 14);
                newItemNode.setId(m_selectionContext.view()->generateNewId("spacer"));
            }
    m_layoutedNodes.append(m_spacerNodes);
}

void LayoutInGridLayout::setSpanning(const ModelNode &layoutNode)
{
    //Define a post layout operation to set columns/rows and the spanning
    if (layoutNode.isValid()) {
        layoutNode.variantProperty("columns").setValue(columnCount());
        layoutNode.variantProperty("rows").setValue(rowCount());

        foreach (const ModelNode &modelNode, m_layoutedNodes) {
            QmlItemNode qmlItemNode(modelNode);
            int xCell = getCell(m_xTopOffsets, qmlItemNode.instancePosition().x());
            int yCell = getCell(m_yTopOffsets, qmlItemNode.instancePosition().y());

            int xCellRight = getCell(m_xTopOffsets, qmlItemNode.instancePosition().x() +  qmlItemNode.instanceSize().width());
            int yCellbottom = getCell(m_yTopOffsets, qmlItemNode.instancePosition().y() +  qmlItemNode.instanceSize().height());

            int columnSpan = xCellRight - xCell;
            int rowSpan = yCellbottom - yCell;

            if (m_spacerNodes.contains(modelNode)) {
                columnSpan = 1;
                rowSpan = 1;
            }

            if (modelNode.hasAuxiliaryData("extraSpanning"))
                columnSpan += modelNode.auxiliaryData("extraSpanning").toInt();

            if (columnSpan > 1)
                qmlItemNode.setVariantProperty("Layout.columnSpan", columnSpan);

            if (rowSpan > 1)
                qmlItemNode.setVariantProperty("Layout.rowSpan", rowSpan);
        }
    }
}

void LayoutInGridLayout::removeSpacersBySpanning(QList<ModelNode> &nodes)
{
    foreach (const ModelNode &node, m_spacerNodes) {
        if (int index = nodes.indexOf(node)) {
            ModelNode before = nodes.at(index -1);
            if (m_spacerNodes.contains(before)) {
                m_spacerNodes.removeAll(node);
                m_layoutedNodes.removeAll(node);
                nodes.removeAll(node);
                ModelNode(node).destroy();
                if (before.hasAuxiliaryData("extraSpanning")) {
                    before.setAuxiliaryData("extraSpanning", before.auxiliaryData("extraSpanning").toInt() + 1);
                } else {
                    before.setAuxiliaryData("extraSpanning", 1);
                }
            }
        }

    }
}

LayoutInGridLayout::LessThan LayoutInGridLayout::lessThan()
{
    return [=](const ModelNode &node1, const ModelNode &node2)->bool {
        QmlItemNode itemNode1 = QmlItemNode(node1);
        QmlItemNode itemNode2 = QmlItemNode(node2);
        if (itemNode1.isValid() && itemNode2.isValid()) {

            int xPos1 = itemNode1.instancePosition().x();
            int yPos1 = itemNode1.instancePosition().y();

            int xPos2 = itemNode2.instancePosition().x();
            int yPos2 = itemNode2.instancePosition().y();

            /* The spacer items do not have proper instances, yet.
                 * Because of this get the position from the model instead
                 * from instances.
                 */
            if (m_spacerNodes.contains(itemNode1)) {
                xPos1 = itemNode1.modelValue("x").toInt();
                yPos1 = itemNode1.modelValue("y").toInt();

            }

            if (m_spacerNodes.contains(itemNode2)) {
                xPos2 = itemNode2.modelValue("x").toInt();
                yPos2 = itemNode2.modelValue("y").toInt();
            }

            int xCell1 = getCell(m_xTopOffsets, xPos1);
            int yCell1 = getCell(m_yTopOffsets, yPos1);

            int xCell2 = getCell(m_xTopOffsets, xPos2);
            int yCell2 = getCell(m_yTopOffsets, yPos2);

            //We have to compare the cells. First the rows then the columns.

            if (yCell1 < yCell2)
                return true;

            if ((yCell1 == yCell2) && xCell1 < xCell2)
                return true;
        }
        return false;
    };
}

} //QmlDesigner