cmakeeditor.cpp 8.59 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
** 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
Eike Ziller's avatar
Eike Ziller committed
13 14
** conditions see http://www.qt.io/licensing.  For further information
** 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 25 26
**
** 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
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 38
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
39 40 41 42
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/infobar.h>

43
#include <extensionsystem/pluginmanager.h>
44

45 46
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
47 48

#include <texteditor/highlighterutils.h>
49 50
#include <texteditor/texteditoractionhandler.h>
#include <texteditor/texteditorconstants.h>
51 52

#include <utils/qtcassert.h>
53

54
#include <QFileInfo>
55
#include <QTextBlock>
56

57
using namespace Core;
58
using namespace ProjectExplorer;
59 60 61 62
using namespace TextEditor;

namespace CMakeProjectManager {
namespace Internal {
63 64

//
65
// CMakeEditor
66 67
//

68
CMakeEditor::CMakeEditor()
69
{
70 71
}

72
void CMakeEditor::finalizeInitialization()
73
{
74
    connect(document(), &IDocument::changed, [this]() {
75
        BaseTextDocument *document = textDocument();
76 77 78 79 80 81 82 83 84
        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);
85 86 87 88
        info.setCustomButtonInfo(tr("Build now"), [document]() {
            foreach (Project *p, SessionManager::projects()) {
                if (CMakeProject *cmakeProject = qobject_cast<CMakeProject *>(p)) {
                    if (cmakeProject->isProjectFile(document->filePath())) {
89
                        ProjectExplorerPlugin::buildProject(cmakeProject);
90 91 92 93 94
                        break;
                    }
                }
            }
        });
95 96
        infoBar->addInfo(info);
    });
97 98
}

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

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

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

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

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

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

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

140
//
141
// CMakeEditorWidget
142 143
//

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

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

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

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

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

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

234
//
235
// CMakeDocument
236
//
237

238
class CMakeDocument : public TextDocument
239 240 241 242 243 244 245 246
{
public:
    CMakeDocument();

    QString defaultPath() const;
    QString suggestedFileName() const;
};

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

QString CMakeDocument::defaultPath() const
{
255
    QFileInfo fi(filePath());
256 257 258 259 260
    return fi.absolutePath();
}

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

//
// CMakeEditorFactory
//

269
CMakeEditorFactory::CMakeEditorFactory(CMakeSettingsPage *settingsPage)
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 279
    setEditorCreator([]() { return new CMakeEditor; });
    setEditorWidgetCreator([]() { return new CMakeEditorWidget; });
    setDocumentCreator([]() { return new CMakeDocument; });
    setGenericSyntaxHighlighter(QLatin1String(Constants::CMAKEMIMETYPE));
280
    setCommentStyle(Utils::CommentDefinition::HashStyle);
hjk's avatar
hjk committed
281
    setCodeFoldingSupported(true);
282

283 284
    setCompletionAssistProvider(new CMakeFileCompletionAssistProvider(settingsPage));

285
    setEditorActionHandlers(TextEditorActionHandler::UnCommentSelection
286 287 288 289
            | TextEditorActionHandler::JumpToFileUnderCursor);

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

} // namespace Internal
} // namespace CMakeProjectManager