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

#include "cmakeeditor.h"

33
#include "cmakefilecompletionassist.h"
34
#include "cmakeprojectconstants.h"
35
#include "cmakeproject.h"
36 37
#include "cmakeindenter.h"
#include "cmakeautocompleter.h"
38

39 40
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
41 42 43 44
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/infobar.h>

45
#include <extensionsystem/pluginmanager.h>
46

47 48
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
49 50

#include <texteditor/highlighterutils.h>
51 52
#include <texteditor/texteditoractionhandler.h>
#include <texteditor/texteditorconstants.h>
53 54

#include <utils/qtcassert.h>
55

56
#include <QFileInfo>
57
#include <QTextBlock>
58

59
using namespace Core;
60
using namespace ProjectExplorer;
61 62 63 64
using namespace TextEditor;

namespace CMakeProjectManager {
namespace Internal {
65 66

//
67
// CMakeEditor
68 69
//

70
CMakeEditor::CMakeEditor()
71
{
72 73
}

74
void CMakeEditor::finalizeInitialization()
75
{
76
    connect(document(), &IDocument::changed, [this]() {
77
        BaseTextDocument *document = textDocument();
78 79 80 81 82 83 84 85 86
        if (!document->isModified())
            return;
        InfoBar *infoBar = document->infoBar();
        Id infoRunCmake("CMakeEditor.RunCMake");
        if (!infoBar->canInfoBeAdded(infoRunCmake))
            return;
        InfoBarEntry info(infoRunCmake,
                          tr("Changes to cmake files are shown in the project tree after building."),
                          InfoBarEntry::GlobalSuppressionEnabled);
87 88 89
        info.setCustomButtonInfo(tr("Build now"), [document]() {
            foreach (Project *p, SessionManager::projects()) {
                if (CMakeProject *cmakeProject = qobject_cast<CMakeProject *>(p)) {
90
                    if (cmakeProject->isProjectFile(document->filePath())) {
91
                        ProjectExplorerPlugin::buildProject(cmakeProject);
92 93 94 95 96
                        break;
                    }
                }
            }
        });
97 98
        infoBar->addInfo(info);
    });
99 100
}

101 102 103 104 105 106 107 108 109
QString CMakeEditor::contextHelpId() const
{
    int pos = position();

    QChar chr;
    do {
        --pos;
        if (pos < 0)
            break;
110
        chr = characterAt(pos);
111 112 113 114 115
        if (chr == QLatin1Char('('))
            return QString();
    } while (chr.unicode() != QChar::ParagraphSeparator);

    ++pos;
116
    chr = characterAt(pos);
117 118
    while (chr.isSpace()) {
        ++pos;
119
        chr = characterAt(pos);
120 121 122 123 124
    }
    int begin = pos;

    do {
        ++pos;
125
        chr = characterAt(pos);
126 127 128 129 130
    } while (chr.isLetterOrNumber() || chr == QLatin1Char('_'));
    int end = pos;

    while (chr.isSpace()) {
        ++pos;
131
        chr = characterAt(pos);
132 133 134 135 136 137
    }

    // Not a command
    if (chr != QLatin1Char('('))
        return QString();

138
    QString command = textAt(begin, end - begin).toLower();
139 140 141
    return QLatin1String("command/") + command;
}

142
//
143
// CMakeEditorWidget
144 145
//

146
class CMakeEditorWidget : public TextEditorWidget
147 148
{
public:
hjk's avatar
hjk committed
149
    CMakeEditorWidget() {}
150 151 152

private:
    bool save(const QString &fileName = QString());
153 154
    Link findLinkAt(const QTextCursor &cursor, bool resolveTarget = true, bool inNextSplit = false) override;
    void contextMenuEvent(QContextMenuEvent *e) override;
155 156
};

157 158
void CMakeEditorWidget::contextMenuEvent(QContextMenuEvent *e)
{
159
    showDefaultContextMenu(e, Constants::M_CONTEXT);
160 161 162 163
}

static bool isValidFileNameChar(const QChar &c)
{
164
    return c.isLetterOrNumber()
165 166 167 168
            || c == QLatin1Char('.')
            || c == QLatin1Char('_')
            || c == QLatin1Char('-')
            || c == QLatin1Char('/')
169
            || c == QLatin1Char('\\');
170 171 172
}

CMakeEditorWidget::Link CMakeEditorWidget::findLinkAt(const QTextCursor &cursor,
173
                                                      bool/* resolveTarget*/, bool /*inNextSplit*/)
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
{
    Link link;

    int lineNumber = 0, positionInBlock = 0;
    convertPosition(cursor.position(), &lineNumber, &positionInBlock);

    const QString block = cursor.block().text();

    // check if the current position is commented out
    const int hashPos = block.indexOf(QLatin1Char('#'));
    if (hashPos >= 0 && hashPos < positionInBlock)
        return link;

    // find the beginning of a filename
    QString buffer;
    int beginPos = positionInBlock - 1;
    while (beginPos >= 0) {
        QChar c = block.at(beginPos);
        if (isValidFileNameChar(c)) {
            buffer.prepend(c);
            beginPos--;
        } else {
            break;
        }
    }

    // find the end of a filename
    int endPos = positionInBlock;
    while (endPos < block.count()) {
        QChar c = block.at(endPos);
        if (isValidFileNameChar(c)) {
            buffer.append(c);
            endPos++;
        } else {
            break;
        }
    }

    if (buffer.isEmpty())
        return link;

    // TODO: Resolve variables

217
    QDir dir(textDocument()->filePath().toFileInfo().absolutePath());
218 219 220 221 222
    QString fileName = dir.filePath(buffer);
    QFileInfo fi(fileName);
    if (fi.exists()) {
        if (fi.isDir()) {
            QDir subDir(fi.absoluteFilePath());
223
            QString subProject = subDir.filePath(QLatin1String("CMakeLists.txt"));
224
            if (QFileInfo::exists(subProject))
225 226 227 228
                fileName = subProject;
            else
                return link;
        }
David Schulz's avatar
David Schulz committed
229 230 231
        link.targetFileName = fileName;
        link.linkTextStart = cursor.position() - positionInBlock + beginPos + 1;
        link.linkTextEnd = cursor.position() - positionInBlock + endPos;
232 233 234 235
    }
    return link;
}

236
//
237
// CMakeDocument
238
//
239

240
class CMakeDocument : public TextDocument
241 242 243 244
{
public:
    CMakeDocument();

245 246
    QString fallbackSaveAsPath() const override;
    QString fallbackSaveAsFileName() const override;
247 248
};

249 250
CMakeDocument::CMakeDocument()
{
251 252
    setId(Constants::CMAKE_EDITOR_ID);
    setMimeType(QLatin1String(Constants::CMAKEMIMETYPE));
253 254
}

255
QString CMakeDocument::fallbackSaveAsPath() const
256
{
257
    return filePath().toFileInfo().absolutePath();
258 259
}

260
QString CMakeDocument::fallbackSaveAsFileName() const
261
{
262
    return filePath().fileName();
263
}
264 265 266 267 268

//
// CMakeEditorFactory
//

269
CMakeEditorFactory::CMakeEditorFactory()
270 271 272 273 274 275
{
    setId(Constants::CMAKE_EDITOR_ID);
    setDisplayName(tr(Constants::CMAKE_EDITOR_DISPLAY_NAME));
    addMimeType(Constants::CMAKEMIMETYPE);
    addMimeType(Constants::CMAKEPROJECTMIMETYPE);

276 277 278
    setEditorCreator([]() { return new CMakeEditor; });
    setEditorWidgetCreator([]() { return new CMakeEditorWidget; });
    setDocumentCreator([]() { return new CMakeDocument; });
279
    setIndenterCreator([]() { return new CMakeIndenter; });
280
    setUseGenericHighlighter(true);
281
    setCommentStyle(Utils::CommentDefinition::HashStyle);
hjk's avatar
hjk committed
282
    setCodeFoldingSupported(true);
283

284
    setCompletionAssistProvider(new CMakeFileCompletionAssistProvider);
285
    setAutoCompleterCreator([]() { return new CMakeAutoCompleter; });
286

287
    setEditorActionHandlers(TextEditorActionHandler::UnCommentSelection
288 289
            | TextEditorActionHandler::JumpToFileUnderCursor
            | TextEditorActionHandler::Format);
290 291 292

    ActionContainer *contextMenu = ActionManager::createMenu(Constants::M_CONTEXT);
    contextMenu->addAction(ActionManager::command(TextEditor::Constants::JUMP_TO_FILE_UNDER_CURSOR));
293
    contextMenu->addSeparator(Context(Constants::CMAKE_EDITOR_ID));
294 295 296 297 298
    contextMenu->addAction(ActionManager::command(TextEditor::Constants::UN_COMMENT_SELECTION));
}

} // namespace Internal
} // namespace CMakeProjectManager