aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmljseditor/qmljswrapinloader.cpp
blob: 5f0ef4bb05a61fc36d93d6b9e60fdbff83b310b0 (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
/****************************************************************************
**
** 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 "qmljswrapinloader.h"
#include "qmljsquickfixassist.h"

#include <coreplugin/idocument.h>

#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/qmljsdocument.h>
#include <qmljs/qmljsscopechain.h>
#include <qmljs/qmljsutils.h>
#include <qmljs/qmljsbind.h>
#include <qmljstools/qmljsrefactoringchanges.h>

#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QCoreApplication>

using namespace QmlJS;
using namespace QmlJS::AST;
using namespace QmlJSTools;

namespace QmlJSEditor {

using namespace Internal;

namespace {

class FindIds : protected Visitor
{
public:
    using Result = QHash<QString, SourceLocation>;

    Result operator()(Node *node)
    {
        result.clear();
        Node::accept(node, this);
        return result;
    }

protected:
    bool visit(UiObjectInitializer *ast) override
    {
        UiScriptBinding *idBinding;
        QString id = idOfObject(ast, &idBinding);
        if (!id.isEmpty())
            result[id] = locationFromRange(idBinding->statement);
        return true;
    }

    void throwRecursionDepthError() override
    {
        qWarning("Warning: Hit maximum recursion depth while visitin AST in FindIds");
    }

    Result result;
};

template <typename T>
class Operation: public QmlJSQuickFixOperation
{
    Q_DECLARE_TR_FUNCTIONS(QmlJSEditor::Internal::Operation)

    T *m_objDef;

public:
    Operation(const QSharedPointer<const QmlJSQuickFixAssistInterface> &interface,
              T *objDef)
        : QmlJSQuickFixOperation(interface, 0)
        , m_objDef(objDef)
    {
        Q_ASSERT(m_objDef);

        setDescription(tr("Wrap Component in Loader"));
    }

    QString findFreeName(const QString &base)
    {
        QString tryName = base;
        int extraNumber = 1;
        const ObjectValue *found = nullptr;
        const ScopeChain &scope = assistInterface()->semanticInfo().scopeChain();
        forever {
            scope.lookup(tryName, &found);
            if (!found || extraNumber > 1000)
                break;
            tryName = base + QString::number(extraNumber++);
        }
        return tryName;
    }

    void performChanges(QmlJSRefactoringFilePtr currentFile,
                        const QmlJSRefactoringChanges &) override
    {
        UiScriptBinding *idBinding;
        const QString id = idOfObject(m_objDef, &idBinding);
        QString baseName = id;
        if (baseName.isEmpty()) {
            for (UiQualifiedId *it = m_objDef->qualifiedTypeNameId; it; it = it->next) {
                if (!it->next)
                    baseName = it->name.toString();
            }
        }

        // find ids
        const QString componentId = findFreeName(QLatin1String("component_") + baseName);
        const QString loaderId = findFreeName(QLatin1String("loader_") + baseName);

        Utils::ChangeSet changes;

        FindIds::Result innerIds = FindIds()(m_objDef);
        innerIds.remove(id);

        QString comment = tr("// TODO: Move position bindings from the component to the Loader.\n"
                             "//       Check all uses of 'parent' inside the root element of the component.")
                          + QLatin1Char('\n');
        if (idBinding) {
            comment += tr("//       Rename all outer uses of the id \"%1\" to \"%2.item\".").arg(
                        id, loaderId) + QLatin1Char('\n');
        }

        // handle inner ids
        QString innerIdForwarders;
        for (auto it = innerIds.cbegin(), end = innerIds.cend(); it != end; ++it) {
            const QString innerId = it.key();
            comment += tr("//       Rename all outer uses of the id \"%1\" to \"%2.item.%1\".\n").arg(
                        innerId, loaderId);
            changes.replace(it.value().begin(), it.value().end(), QString::fromLatin1("inner_%1").arg(innerId));
            innerIdForwarders += QString::fromLatin1("\nproperty alias %1: inner_%1").arg(innerId);
        }
        if (!innerIdForwarders.isEmpty()) {
            innerIdForwarders.append(QLatin1Char('\n'));
            const int afterOpenBrace = m_objDef->initializer->lbraceToken.end();
            changes.insert(afterOpenBrace, innerIdForwarders);
        }

        const int objDefStart = m_objDef->qualifiedTypeNameId->firstSourceLocation().begin();
        const int objDefEnd = m_objDef->lastSourceLocation().end();
        changes.insert(objDefStart, comment +
                       QString::fromLatin1("Component {\n"
                                           "    id: %1\n").arg(componentId));
        changes.insert(objDefEnd, QString::fromLatin1("\n"
                                                      "}\n"
                                                      "Loader {\n"
                                                      "    id: %2\n"
                                                      "    sourceComponent: %1\n"
                                                      "}\n").arg(componentId, loaderId));
        currentFile->setChangeSet(changes);
        currentFile->appendIndentRange(Range(objDefStart, objDefEnd));
        currentFile->apply();
    }
};

} // end of anonymous namespace


void matchWrapInLoaderQuickFix(const QmlJSQuickFixInterface &interface, QuickFixOperations &result)
{
    const int pos = interface->currentFile()->cursor().position();

    QList<Node *> path = interface->semanticInfo().rangePath(pos);
    for (int i = path.size() - 1; i >= 0; --i) {
        Node *node = path.at(i);
        if (auto objDef = cast<UiObjectDefinition *>(node)) {
            if (!interface->currentFile()->isCursorOn(objDef->qualifiedTypeNameId))
                return;
             // check that the node is not the root node
            if (i > 0 && !cast<UiProgram*>(path.at(i - 1))) {
                result << new Operation<UiObjectDefinition>(interface, objDef);
                return;
            }
        } else if (auto objBinding = cast<UiObjectBinding *>(node)) {
            if (!interface->currentFile()->isCursorOn(objBinding->qualifiedTypeNameId))
                return;
            result << new Operation<UiObjectBinding>(interface, objBinding);
            return;
        }
    }
}

} // namespace QmlJSEditor