qmlitemnode.cpp 20 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** 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 Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29 30 31 32 33

#include "qmlitemnode.h"
#include <metainfo.h>
#include "qmlchangeset.h"
#include "nodelistproperty.h"
34
#include "variantproperty.h"
35
#include "bindingproperty.h"
36 37
#include "qmlanchors.h"
#include "invalidmodelnodeexception.h"
38 39 40 41 42 43 44 45 46 47 48
#include "itemlibraryinfo.h"

#include "plaintexteditmodifier.h"
#include "rewriterview.h"
#include "modelmerger.h"
#include "rewritingexception.h"

#include <QUrl>
#include <QPlainTextEdit>
#include <QFileInfo>
#include <QDir>
49 50 51

namespace QmlDesigner {

52
bool QmlItemNode::isItemOrWindow(const ModelNode &modelNode)
53 54 55 56 57 58 59 60 61 62
{
    if (modelNode.metaInfo().isSubclassOf("QtQuick.Item", -1, -1))
        return true;

    if (modelNode.metaInfo().isSubclassOf("QtQuick.Window.Window", -1, -1) && modelNode.isRootNode())
        return true;

    return false;
}

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
static QmlItemNode createQmlItemNodeFromSource(AbstractView *view, const QString &source, const QPointF &position)
{
    QScopedPointer<Model> inputModel(Model::create("QtQuick.Item", 1, 0, view->model()));
    inputModel->setFileUrl(view->model()->fileUrl());
    QPlainTextEdit textEdit;

    textEdit.setPlainText(source);
    NotIndentingTextEditModifier modifier(&textEdit);

    QScopedPointer<RewriterView> rewriterView(new RewriterView(RewriterView::Amend, 0));
    rewriterView->setCheckSemanticErrors(false);
    rewriterView->setTextModifier(&modifier);
    inputModel->setRewriterView(rewriterView.data());

    if (rewriterView->errors().isEmpty() && rewriterView->rootModelNode().isValid()) {
        ModelNode rootModelNode = rewriterView->rootModelNode();
        inputModel->detachView(rewriterView.data());

        rootModelNode.variantProperty("x").setValue(qRound(position.x()));
        rootModelNode.variantProperty("y").setValue(qRound(position.y()));

        ModelMerger merger(view);
        return merger.insertModel(rootModelNode);
    }

    return QmlItemNode();
}


92 93 94 95 96 97 98 99 100 101
QmlItemNode QmlItemNode::createQmlItemNode(AbstractView *view, const ItemLibraryEntry &itemLibraryEntry, const QPointF &position, QmlItemNode parentQmlItemNode)
{
    if (!parentQmlItemNode.isValid())
        parentQmlItemNode = QmlItemNode(view->rootModelNode());

    Q_ASSERT(parentQmlItemNode.isValid());

    QmlItemNode newQmlItemNode;

    try {
102
        RewriterTransaction transaction = view->beginRewriterTransaction(QByteArrayLiteral("QmlItemNode::createQmlItemNode"));
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

        NodeMetaInfo metaInfo = view->model()->metaInfo(itemLibraryEntry.typeName());

        int minorVersion = metaInfo.minorVersion();
        int majorVersion = metaInfo.majorVersion();

        if (itemLibraryEntry.typeName().contains('.')) {

            const QString newImportUrl = itemLibraryEntry.requiredImport();

            if (!itemLibraryEntry.requiredImport().isEmpty()) {
                const QString newImportVersion = QString("%1.%2").arg(QString::number(itemLibraryEntry.majorVersion()), QString::number(itemLibraryEntry.minorVersion()));

                Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
                if (itemLibraryEntry.majorVersion() == -1 && itemLibraryEntry.minorVersion() == -1)
                    newImport = Import::createFileImport(newImportUrl, QString());
                else
                    newImport = Import::createLibraryImport(newImportUrl, newImportVersion);

                foreach (const Import &import, view->model()->imports()) {
                    if (import.isLibraryImport()
                            && import.url() == newImport.url()
                            && import.version() == newImport.version()) {
                        // reuse this import
                        newImport = import;
                        break;
                    }
                }

                if (!view->model()->hasImport(newImport, true, true))
                    view->model()->changeImports(QList<Import>() << newImport, QList<Import>());
            }
        }

137 138
        typedef QPair<PropertyName, QString> PropertyBindingEntry;
        QList<PropertyBindingEntry> propertyBindingList;
Thomas Hartmann's avatar
Thomas Hartmann committed
139
        if (itemLibraryEntry.qmlSource().isEmpty()) {
140 141 142 143
            QList<QPair<PropertyName, QVariant> > propertyPairList;
            propertyPairList.append(qMakePair(PropertyName("x"), QVariant(qRound(position.x()))));
            propertyPairList.append(qMakePair(PropertyName("y"), QVariant(qRound(position.y()))));

144 145 146 147 148 149 150
            foreach (const PropertyContainer &property, itemLibraryEntry.properties()) {
                if (property.type() == QLatin1String("binding")) {
                    propertyBindingList.append(PropertyBindingEntry(property.name(), property.value().toString()));
                } else {
                    propertyPairList.append(qMakePair(property.name(), property.value()));
                }
            }
151 152 153

            newQmlItemNode = QmlItemNode(view->createModelNode(itemLibraryEntry.typeName(), majorVersion, minorVersion, propertyPairList));
        } else {
Thomas Hartmann's avatar
Thomas Hartmann committed
154
            newQmlItemNode = createQmlItemNodeFromSource(view, itemLibraryEntry.qmlSource(), position);
155 156
        }

157
        if (parentQmlItemNode.hasDefaultPropertyName())
158 159 160 161 162
            parentQmlItemNode.nodeAbstractProperty(parentQmlItemNode.defaultPropertyName()).reparentHere(newQmlItemNode);

        if (!newQmlItemNode.isValid())
            return newQmlItemNode;

Thomas Hartmann's avatar
Thomas Hartmann committed
163
        newQmlItemNode.setId(view->generateNewId(itemLibraryEntry.name()));
164

165
        if (!view->currentState().isBaseState()) {
166 167 168 169
            newQmlItemNode.modelNode().variantProperty("opacity").setValue(0);
            newQmlItemNode.setVariantProperty("opacity", 1);
        }

170 171 172
        foreach (const PropertyBindingEntry &propertyBindingEntry, propertyBindingList)
            newQmlItemNode.modelNode().bindingProperty(propertyBindingEntry.first).setExpression(propertyBindingEntry.second);

173 174 175
        Q_ASSERT(newQmlItemNode.isValid());
    }
    catch (RewritingException &e) {
176
        e.showException();
177 178 179 180 181 182 183
    }

    Q_ASSERT(newQmlItemNode.isValid());

    return newQmlItemNode;
}

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
static void checkImageImport(AbstractView *view)
{
    const QString newImportUrl = QLatin1String("QtQuick");
    const QString newImportVersion = QLatin1String("1.1");
    Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);

    foreach (const Import &import, view->model()->imports()) {
        if (import.isLibraryImport()
            && import.url() == newImport.url()) {
            // reuse this import
            newImport = import;
            break;
        }
    }

    if (!view->model()->hasImport(newImport, true, true))
        view->model()->changeImports(QList<Import>() << newImport, QList<Import>());
}

203 204
QmlItemNode QmlItemNode::createQmlItemNodeFromImage(AbstractView *view, const QString &imageName, const QPointF &position, QmlItemNode parentQmlItemNode)
{
205 206
    QmlItemNode newQmlItemNode;
    if (!parentQmlItemNode.isValid())
207 208
        parentQmlItemNode = QmlItemNode(view->rootModelNode());

209
    if (parentQmlItemNode.isValid()) {
210
        RewriterTransaction transaction = view->beginRewriterTransaction(QByteArrayLiteral("QmlItemNode::createQmlItemNodeFromImage"));
211

212
        checkImageImport(view);
213

214 215 216 217 218
        if (view->model()->hasNodeMetaInfo("QtQuick.Image")) {
            NodeMetaInfo metaInfo = view->model()->metaInfo("QtQuick.Image");
            QList<QPair<PropertyName, QVariant> > propertyPairList;
            propertyPairList.append(qMakePair(PropertyName("x"), QVariant(qRound(position.x()))));
            propertyPairList.append(qMakePair(PropertyName("y"), QVariant(qRound(position.y()))));
219

220
            QString relativeImageName = imageName;
221

222 223 224 225 226 227
            //use relative path
            if (QFileInfo(view->model()->fileUrl().toLocalFile()).exists()) {
                QDir fileDir(QFileInfo(view->model()->fileUrl().toLocalFile()).absolutePath());
                relativeImageName = fileDir.relativeFilePath(imageName);
                propertyPairList.append(qMakePair(PropertyName("source"), QVariant(relativeImageName)));
            }
228

229 230
            newQmlItemNode = QmlItemNode(view->createModelNode("QtQuick.Image", metaInfo.majorVersion(), metaInfo.minorVersion(), propertyPairList));
            parentQmlItemNode.defaultNodeAbstractProperty().reparentHere(newQmlItemNode);
231

232
            newQmlItemNode.setId(view->generateNewId("image"));
233

234
            if (!view->currentState().isBaseState()) {
235 236 237
                newQmlItemNode.modelNode().variantProperty("opacity").setValue(0);
                newQmlItemNode.setVariantProperty("opacity", 1);
            }
238

239
            Q_ASSERT(newQmlItemNode.isValid());
240 241 242 243 244 245 246 247
        }
        Q_ASSERT(newQmlItemNode.isValid());
    }


    return newQmlItemNode;
}

248 249
bool QmlItemNode::isValid() const
{
250 251 252 253 254 255
    return isValidQmlItemNode(modelNode());
}

bool QmlItemNode::isValidQmlItemNode(const ModelNode &modelNode)
{
    return isValidQmlObjectNode(modelNode) && modelNode.metaInfo().isValid() && isItemOrWindow(modelNode);
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
}

bool QmlItemNode::isRootNode() const
{
    return modelNode().isValid() && modelNode().isRootNode();
}

QStringList QmlModelStateGroup::names() const
{
    QStringList returnList;

    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    if (modelNode().property("states").isNodeListProperty()) {
        foreach (const ModelNode &node, modelNode().nodeListProperty("states").toModelNodeList()) {
272
            if (QmlModelState::isValidQmlModelState(node))
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
                returnList.append(QmlModelState(node).name());
        }
    }
    return returnList;
}

/**
  \brief Returns list of states (without 'base state').
  The list contains all states defined by this item.
  */
QmlModelStateGroup QmlItemNode::states() const
{
    if (isValid())
        return QmlModelStateGroup(modelNode());
    else
        return QmlModelStateGroup();
}

QList<QmlItemNode> QmlItemNode::children() const
{
293
    QList<ModelNode> childrenList;
294 295 296

    if (isValid()) {

297 298
        if (modelNode().hasNodeListProperty("children"))
                childrenList.append(modelNode().nodeListProperty("children").toModelNodeList());
299

300 301 302 303 304
        if (modelNode().hasNodeListProperty("data")) {
            foreach (const ModelNode &node, modelNode().nodeListProperty("data").toModelNodeList()) {
                if (QmlItemNode::isValidQmlItemNode(node))
                    childrenList.append(node);
            }
305 306
        }
    }
307 308

    return toQmlItemNodeList(childrenList);
309 310 311 312
}

QList<QmlObjectNode> QmlItemNode::resources() const
{
313
    QList<ModelNode> resourcesList;
314 315 316

    if (isValid()) {

317 318
        if (modelNode().hasNodeListProperty("resources"))
                resourcesList.append(modelNode().nodeListProperty("resources").toModelNodeList());
319

320 321 322 323 324
        if (modelNode().hasNodeListProperty("data")) {
            foreach (const ModelNode &node, modelNode().nodeListProperty("data").toModelNodeList()) {
                if (!QmlItemNode::isValidQmlItemNode(node))
                    resourcesList.append(node);
            }
325 326
        }
    }
327 328

    return toQmlObjectNodeList(resourcesList);
329 330 331 332
}

QList<QmlObjectNode> QmlItemNode::allDirectSubNodes() const
{
333
    return toQmlObjectNodeList(modelNode().allDirectSubModelNodes());
334 335 336 337 338 339 340 341 342
}

QmlAnchors QmlItemNode::anchors() const
{
    return QmlAnchors(*this);
}

bool QmlItemNode::hasChildren() const
{
343 344 345
    if (modelNode().hasNodeListProperty("children"))
        return true;

346 347 348 349 350
    return !children().isEmpty();
}

bool QmlItemNode::hasResources() const
{
351 352 353
    if (modelNode().hasNodeListProperty("resources"))
        return true;

354 355 356 357 358 359 360 361
    return !resources().isEmpty();
}

bool QmlItemNode::instanceHasAnchors() const
{
    return anchors().instanceHasAnchors();
}

362
bool QmlItemNode::instanceHasShowContent() const
363 364 365 366
{
    return nodeInstance().hasContent();
}

367
bool QmlItemNode::instanceCanReparent() const
368
{
369
    return QmlObjectNode::instanceCanReparent() && !anchors().instanceHasAnchors() && !instanceIsAnchoredBySibling();
370 371
}

372
bool QmlItemNode::instanceIsAnchoredBySibling() const
373
{
374 375 376 377 378 379
    return nodeInstance().isAnchoredBySibling();
}

bool QmlItemNode::instanceIsAnchoredByChildren() const
{
    return nodeInstance().isAnchoredByChildren();
380 381
}

382 383 384 385 386 387 388 389 390 391
bool QmlItemNode::instanceIsMovable() const
{
    return nodeInstance().isMovable();
}

bool QmlItemNode::instanceIsResizable() const
{
    return nodeInstance().isResizable();
}

392
bool QmlItemNode::instanceIsInLayoutable() const
393
{
394
     return nodeInstance().isInLayoutable();
395 396
}

397 398 399 400 401
bool QmlItemNode::instanceHasRotationTransform() const
{
    return nodeInstance().transform().type() > QTransform::TxScale;
}

402 403 404 405 406 407 408 409 410
bool itemIsMovable(const ModelNode &modelNode)
{
    if (modelNode.metaInfo().isSubclassOf("QtQuick.Controls.Tab", -1, -1))
        return false;

    return true;
}


411 412 413
bool QmlItemNode::modelIsMovable() const
{
    return !modelNode().hasBindingProperty("x")
414 415
            && !modelNode().hasBindingProperty("y")
            && itemIsMovable(modelNode());
416 417
}

418 419 420
bool QmlItemNode::modelIsResizable() const
{
    return !modelNode().hasBindingProperty("width")
421 422
            && !modelNode().hasBindingProperty("height")
            && itemIsMovable(modelNode());
423 424
}

425
QRectF  QmlItemNode::instanceBoundingRect() const
426 427 428 429 430
{
    return QRectF(QPointF(0, 0), nodeInstance().size());
}

QRectF QmlItemNode::instancePaintedBoundingRect() const
431 432 433 434
{
    return nodeInstance().boundingRect();
}

435 436 437 438 439
QRectF QmlItemNode::instanceContentItemBoundingRect() const
{
    return nodeInstance().contentItemBoundingRect();
}

440 441 442 443 444
QTransform  QmlItemNode::instanceTransform() const
{
    return nodeInstance().transform();
}

445 446 447 448 449 450 451 452 453 454
QTransform QmlItemNode::instanceTransformWithContentTransform() const
{
    return nodeInstance().transform() * nodeInstance().contentTransform();
}

QTransform QmlItemNode::instanceTransformWithContentItemTransform() const
{
    return nodeInstance().transform() * nodeInstance().contentItemTransform();
}

455 456 457 458 459
QTransform QmlItemNode::instanceSceneTransform() const
{
    return nodeInstance().sceneTransform();
}

460 461 462 463 464
QTransform QmlItemNode::instanceSceneContentItemTransform() const
{
    return nodeInstance().sceneTransform() * nodeInstance().contentItemTransform();
}

465 466
QPointF QmlItemNode::instanceScenePosition() const
{
467 468 469 470
    if (hasInstanceParentItem())
        return instanceParentItem().instanceSceneTransform().map(nodeInstance().position());
     else if (modelNode().hasParentProperty() && QmlItemNode::isValidQmlItemNode(modelNode().parentProperty().parentModelNode()))
        return QmlItemNode(modelNode().parentProperty().parentModelNode()).instanceSceneTransform().map(nodeInstance().position());
471 472 473 474

    return QPointF();
}

475 476 477 478 479 480 481 482 483 484
QPointF QmlItemNode::instancePosition() const
{
    return nodeInstance().position();
}

QSizeF QmlItemNode::instanceSize() const
{
    return nodeInstance().size();
}

Marco Bubke's avatar
Marco Bubke committed
485
int QmlItemNode::instancePenWidth() const
486
{
Marco Bubke's avatar
Marco Bubke committed
487
    return nodeInstance().penWidth();
488 489
}

490 491 492 493 494
bool QmlItemNode::instanceIsRenderPixmapNull() const
{
    return nodeInstance().renderPixmap().isNull();
}

495
QPixmap QmlItemNode::instanceRenderPixmap() const
Marco Bubke's avatar
Marco Bubke committed
496
{
497 498 499 500 501 502
    return nodeInstance().renderPixmap();
}

QPixmap QmlItemNode::instanceBlurredRenderPixmap() const
{
    return nodeInstance().blurredRenderPixmap();
Marco Bubke's avatar
Marco Bubke committed
503 504
}

505 506 507 508 509 510 511 512 513
QList<QmlModelState> QmlModelStateGroup::allStates() const
{
    QList<QmlModelState> returnList;

    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    if (modelNode().property("states").isNodeListProperty()) {
        foreach (const ModelNode &node, modelNode().nodeListProperty("states").toModelNodeList()) {
514 515
            if (QmlModelState::isValidQmlModelState(node))
                returnList.append(node);
516 517 518 519 520
        }
    }
    return returnList;
}

521
TypeName QmlItemNode::simplifiedTypeName() const
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
{
    return modelNode().simplifiedTypeName();
}

uint qHash(const QmlItemNode &node)
{
    return qHash(node.modelNode());
}

QmlModelState QmlModelStateGroup::addState(const QString &name)
{
    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);


    PropertyListType propertyList;
538
    propertyList.append(qMakePair(PropertyName("name"), QVariant(name)));
539

540
    ModelNode newState = QmlModelState::createQmlState(modelNode().view(), propertyList);
Marco Bubke's avatar
Marco Bubke committed
541
    modelNode().nodeListProperty("states").reparentHere(newState);
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583

    return newState;
}

void QmlModelStateGroup::removeState(const QString &name)
{
    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    if (state(name).isValid())
        state(name).modelNode().destroy();
}

QmlModelState QmlModelStateGroup::state(const QString &name) const
{
    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    if (modelNode().property("states").isNodeListProperty()) {
        foreach (const ModelNode &node, modelNode().nodeListProperty("states").toModelNodeList()) {
            if (QmlModelState(node).name() == name)
                return node;
        }
    }
    return QmlModelState();
}

QList<ModelNode> toModelNodeList(const QList<QmlItemNode> &qmlItemNodeList)
{
    QList<ModelNode> modelNodeList;

    foreach (const QmlItemNode &qmlItemNode, qmlItemNodeList)
        modelNodeList.append(qmlItemNode.modelNode());

    return modelNodeList;
}

QList<QmlItemNode> toQmlItemNodeList(const QList<ModelNode> &modelNodeList)
{
    QList<QmlItemNode> qmlItemNodeList;

    foreach (const ModelNode &modelNode, modelNodeList) {
584 585
        if (QmlItemNode::isValidQmlItemNode(modelNode))
            qmlItemNodeList.append(modelNode);
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
    }

    return qmlItemNodeList;
}

const QList<QmlItemNode> QmlItemNode::allDirectSubModelNodes() const
{
    return toQmlItemNodeList(modelNode().allDirectSubModelNodes());
}

const QList<QmlItemNode> QmlItemNode::allSubModelNodes() const
{
    return toQmlItemNodeList(modelNode().allSubModelNodes());
}

bool QmlItemNode::hasAnySubModelNodes() const
{
    return modelNode().hasAnySubModelNodes();
}

606 607
void QmlItemNode::setPosition(const QPointF &position)
{
608 609 610
    if (!hasBindingProperty("x")
            && !anchors().instanceHasAnchor(AnchorLine::Left)
            && !anchors().instanceHasAnchor(AnchorLine::HorizontalCenter))
611 612
        setVariantProperty("x", qRound(position.x()));

613 614 615
    if (!hasBindingProperty("y")
            && !anchors().instanceHasAnchor(AnchorLine::Top)
            && !anchors().instanceHasAnchor(AnchorLine::VerticalCenter))
616 617 618 619 620 621 622 623 624 625 626
        setVariantProperty("y", qRound(position.y()));
}

void QmlItemNode::setPostionInBaseState(const QPointF &position)
{
    modelNode().variantProperty("x").setValue(qRound(position.x()));
    modelNode().variantProperty("y").setValue(qRound(position.y()));
}

void QmlItemNode::setSize(const QSizeF &size)
{
627
    if (!hasBindingProperty("width") && !anchors().instanceHasAnchor(AnchorLine::Right))
628 629
        setVariantProperty("width", qRound(size.width()));

630
    if (!hasBindingProperty("height") && !anchors().instanceHasAnchor(AnchorLine::Bottom))
631 632 633
        setVariantProperty("height", qRound(size.height()));
}

634
} //QmlDesigner