aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/projectexplorer/projectfilewizardextension.cpp
blob: 74a767cc98948f1934fb449b599cfcc2d146ce99 (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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "projectfilewizardextension.h"

#include "editorconfiguration.h"
#include "project.h"
#include "projectexplorerconstants.h"
#include "projectexplorertr.h"
#include "projectmanager.h"
#include "projectnodes.h"
#include "projecttree.h"
#include "projectwizardpage.h"

#include <coreplugin/icore.h>

#include <texteditor/icodestylepreferences.h>
#include <texteditor/icodestylepreferencesfactory.h>
#include <texteditor/storagesettings.h>
#include <texteditor/tabsettings.h>
#include <texteditor/texteditorsettings.h>
#include <texteditor/textindenter.h>

#include <utils/algorithm.h>
#include <utils/mimeutils.h>
#include <utils/qtcassert.h>
#include <utils/stringutils.h>

#include <QDebug>
#include <QMessageBox>
#include <QPointer>
#include <QTextCursor>
#include <QTextDocument>

using namespace TextEditor;
using namespace Core;
using namespace Utils;

/*!
    \class ProjectExplorer::Internal::ProjectFileWizardExtension

    \brief The ProjectFileWizardExtension class implements the post-file
    generating steps of a project wizard.

    This class provides the following functions:
    \list
    \li Add to a project file (*.pri/ *.pro)
    \li Initialize a version control system repository (unless the path is already
        managed) and do 'add' if the VCS supports it.
    \endlist

    \sa ProjectExplorer::ProjectWizardPage
*/

enum { debugExtension = 0 };

namespace ProjectExplorer {
namespace Internal {

// --------- ProjectWizardContext

class ProjectWizardContext
{
public:
    void clear();

    QPointer<ProjectWizardPage> page = nullptr; // this is managed by the wizard!
    const IWizardFactory *wizard = nullptr;
};

void ProjectWizardContext::clear()
{
    page = nullptr;
    wizard = nullptr;
}

// ---- ProjectFileWizardExtension

ProjectFileWizardExtension::~ProjectFileWizardExtension()
{
    delete m_context;
}

static FilePath generatedProjectFilePath(const QList<GeneratedFile> &files)
{
    for (const GeneratedFile &file : files)
        if (file.attributes() & GeneratedFile::OpenProjectAttribute)
            return file.filePath();
    return {};
}

void ProjectFileWizardExtension::firstExtensionPageShown(
        const QList<GeneratedFile> &files,
        const QVariantMap &extraValues)
{
    if (debugExtension)
        qDebug() << Q_FUNC_INFO << files.size();

    const FilePaths fileNames = Utils::transform(files, &GeneratedFile::filePath);
    m_context->page->setFiles(fileNames);

    FilePaths filePaths;
    ProjectAction projectAction;
    const IWizardFactory::WizardKind kind = m_context->wizard->kind();
    if (kind == IWizardFactory::ProjectWizard) {
        projectAction = AddSubProject;
        filePaths << generatedProjectFilePath(files);
    } else {
        projectAction = AddNewFile;
        filePaths = Utils::transform(files, &GeneratedFile::filePath);
    }

    // Static cast from void * to avoid qobject_cast (which needs a valid object) in value().
    auto contextNode = static_cast<Node *>(extraValues.value(QLatin1String(Constants::PREFERRED_PROJECT_NODE)).value<void *>());
    auto project = static_cast<Project *>(extraValues.value(Constants::PROJECT_POINTER).value<void *>());
    const FilePath path = FilePath::fromVariant(extraValues.value(Constants::PREFERRED_PROJECT_NODE_PATH));

    m_context->page->initializeProjectTree(findWizardContextNode(contextNode, project, path),
                                           filePaths, m_context->wizard->kind(),
                                           projectAction);
    // Refresh combobox on project tree changes:
    connect(ProjectTree::instance(), &ProjectTree::treeChanged,
            m_context->page, [this, project, path, filePaths, kind, projectAction]() {
        m_context->page->initializeProjectTree(
                    findWizardContextNode(m_context->page->currentNode(), project, path), filePaths,
                    kind, projectAction);
    });

    m_context->page->initializeVersionControls();
}

Node *ProjectFileWizardExtension::findWizardContextNode(Node *contextNode, Project *project,
                                                        const FilePath &path)
{
    if (contextNode && !ProjectTree::hasNode(contextNode)) {
        if (ProjectManager::projects().contains(project) && project->rootProjectNode()) {
            contextNode = project->rootProjectNode()->findNode([path](const Node *n) {
                return path == n->filePath();
            });
        }
    }
    return contextNode;
}

QList<QWizardPage *> ProjectFileWizardExtension::extensionPages(const IWizardFactory *wizard)
{
    if (!m_context)
        m_context = new ProjectWizardContext;
    else
        m_context->clear();
    // Init context with page and projects
    m_context->page = new ProjectWizardPage;
    m_context->wizard = wizard;
    return {m_context->page};
}

bool ProjectFileWizardExtension::processFiles(
        const QList<GeneratedFile> &files,
        bool *removeOpenProjectAttribute, QString *errorMessage)
{
    if (!processProject(files, removeOpenProjectAttribute, errorMessage))
        return false;
    if (!m_context->page->runVersionControl(files, errorMessage)) {
        QString message;
        if (errorMessage) {
            message = *errorMessage;
            message.append(QLatin1String("\n\n"));
            errorMessage->clear();
        }
        message.append(Tr::tr("Open project anyway?"));
        if (QMessageBox::question(ICore::dialogParent(), Tr::tr("Version Control Failure"), message,
                                  QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
            return false;
    }
    return true;
}

// Add files to project && version control
bool ProjectFileWizardExtension::processProject(
        const QList<GeneratedFile> &files,
        bool *removeOpenProjectAttribute, QString *errorMessage)
{
    *removeOpenProjectAttribute = false;

    const FilePath generatedProject = generatedProjectFilePath(files);

    FolderNode *folder = m_context->page->currentNode();
    if (!folder)
        return true;
    if (m_context->wizard->kind() == IWizardFactory::ProjectWizard) {
        if (!static_cast<ProjectNode *>(folder)->addSubProject(generatedProject)) {
            *errorMessage = Tr::tr("Failed to add subproject \"%1\"\nto project \"%2\".")
                            .arg(generatedProject.toUserOutput()).arg(folder->filePath().toUserOutput());
            return false;
        }
        *removeOpenProjectAttribute = true;
    } else {
        FilePaths filePaths = Utils::transform(files, &GeneratedFile::filePath);
        if (!folder->addFiles(filePaths)) {
            *errorMessage = Tr::tr("Failed to add one or more files to project\n\"%1\" (%2).")
                    .arg(folder->filePath().toUserOutput())
                    .arg(FilePath::formatFilePaths(filePaths, ","));
            return false;
        }
    }
    return true;
}

static ICodeStylePreferences *codeStylePreferences(Project *project, Id languageId)
{
    if (!languageId.isValid())
        return nullptr;

    if (project)
        return project->editorConfiguration()->codeStyle(languageId);

    return TextEditorSettings::codeStyle(languageId);
}

void ProjectFileWizardExtension::applyCodeStyle(GeneratedFile *file) const
{
    if (file->isBinary() || file->contents().isEmpty())
        return; // nothing to do

    Id languageId = TextEditorSettings::languageId(Utils::mimeTypeForFile(file->filePath()).name());

    if (!languageId.isValid())
        return; // don't modify files like *.ui *.pro

    FolderNode *folder = m_context->page->currentNode();
    Project *baseProject = ProjectTree::projectForNode(folder);

    ICodeStylePreferencesFactory *factory = TextEditorSettings::codeStyleFactory(languageId);

    QTextDocument doc(file->contents());
    Indenter *indenter = nullptr;
    if (factory) {
        indenter = factory->createIndenter(&doc);
        indenter->setFileName(file->filePath());
    }
    if (!indenter)
        indenter = new TextIndenter(&doc);

    ICodeStylePreferences *codeStylePrefs = codeStylePreferences(baseProject, languageId);
    indenter->setCodeStylePreferences(codeStylePrefs);

    QTextCursor cursor(&doc);
    cursor.select(QTextCursor::Document);
    indenter->indent(cursor,
                     QChar::Null,
                     codeStylePrefs->currentTabSettings());
    delete indenter;
    if (globalStorageSettings().m_cleanWhitespace) {
        QTextBlock block = doc.firstBlock();
        while (block.isValid()) {
            TabSettings::removeTrailingWhitespace(cursor, block);
            block = block.next();
        }
    }
    file->setContents(doc.toPlainText());
}

} // namespace Internal
} // namespace ProjectExplorer