glsleditor.cpp 12.8 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

#include "glsleditor.h"
#include "glsleditorconstants.h"
#include "glsleditorplugin.h"
33
#include "glslhighlighter.h"
34
#include "glslautocompleter.h"
Leandro Melo's avatar
Leandro Melo committed
35
#include "glslcompletionassist.h"
Daniel Teske's avatar
Daniel Teske committed
36
#include "glslindenter.h"
37

Roberto Raggi's avatar
Roberto Raggi committed
38 39 40
#include <glsl/glsllexer.h>
#include <glsl/glslparser.h>
#include <glsl/glslengine.h>
41
#include <glsl/glslsemantic.h>
Roberto Raggi's avatar
Roberto Raggi committed
42
#include <glsl/glslsymbols.h>
Roberto Raggi's avatar
Roberto Raggi committed
43

44 45 46 47 48
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
49
#include <coreplugin/id.h>
50
#include <coreplugin/mimedatabase.h>
51

52
#include <extensionsystem/pluginmanager.h>
53 54
#include <extensionsystem/pluginspec.h>

55
#include <texteditor/refactoroverlay.h>
56 57 58 59 60
#include <texteditor/syntaxhighlighter.h>
#include <texteditor/texteditoractionhandler.h>
#include <texteditor/texteditorconstants.h>
#include <texteditor/texteditorsettings.h>

61
#include <qmldesigner/qmldesignerconstants.h>
62

63
#include <utils/changeset.h>
64
#include <utils/qtcassert.h>
65 66
#include <utils/uncommentselection.h>

67 68
#include <QCoreApplication>
#include <QSettings>
69
#include <QComboBox>
70
#include <QFileInfo>
71
#include <QHeaderView>
72 73
#include <QTextBlock>
#include <QTimer>
74
#include <QTreeView>
75

76
using namespace TextEditor;
77
using namespace GLSL;
78 79 80 81
using namespace GLSLEditor::Constants;

namespace GLSLEditor {
namespace Internal {
82 83 84 85 86

enum {
    UPDATE_DOCUMENT_DEFAULT_INTERVAL = 150
};

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
class CreateRanges: protected GLSL::Visitor
{
    QTextDocument *textDocument;
    Document::Ptr glslDocument;

public:
    CreateRanges(QTextDocument *textDocument, Document::Ptr glslDocument)
        : textDocument(textDocument), glslDocument(glslDocument) {}

    void operator()(GLSL::AST *ast) { accept(ast); }

protected:
    using GLSL::Visitor::visit;

    virtual void endVisit(GLSL::CompoundStatementAST *ast)
    {
        if (ast->symbol) {
            QTextCursor tc(textDocument);
            tc.setPosition(ast->start);
            tc.setPosition(ast->end, QTextCursor::KeepAnchor);
            glslDocument->addRange(tc, ast->symbol);
        }
    }
};

Document::Document()
    : _engine(0)
    , _ast(0)
    , _globalScope(0)
{
}

Document::~Document()
{
    delete _globalScope;
    delete _engine;
}

GLSL::Scope *Document::scopeAt(int position) const
{
    foreach (const Range &c, _cursors) {
        if (position >= c.cursor.selectionStart() && position <= c.cursor.selectionEnd())
            return c.scope;
    }
    return _globalScope;
}

void Document::addRange(const QTextCursor &cursor, GLSL::Scope *scope)
{
    Range c;
    c.cursor = cursor;
    c.scope = scope;
    _cursors.append(c);
}

142
GlslEditorWidget::GlslEditorWidget()
143
{
144
    setAutoCompleter(new GLSLCompleter);
145
    m_outlineCombo = 0;
146 147 148 149
    setParenthesesMatchingEnabled(true);
    setMarksVisible(true);
    setCodeFoldingSupported(true);

150 151 152 153
    m_updateDocumentTimer.setInterval(UPDATE_DOCUMENT_DEFAULT_INTERVAL);
    m_updateDocumentTimer.setSingleShot(true);
    connect(&m_updateDocumentTimer, &QTimer::timeout,
            this, &GlslEditorWidget::updateDocumentNow);
154

155 156
    connect(this, &QPlainTextEdit::textChanged,
            [this]() { m_updateDocumentTimer.start(); });
157

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    m_outlineCombo = new QComboBox;
    m_outlineCombo->setMinimumContentsLength(22);

    // ### m_outlineCombo->setModel(m_outlineModel);

    QTreeView *treeView = new QTreeView;
    treeView->header()->hide();
    treeView->setItemsExpandable(false);
    treeView->setRootIsDecorated(false);
    m_outlineCombo->setView(treeView);
    treeView->expandAll();

    //m_outlineCombo->setSizeAdjustPolicy(QComboBox::AdjustToContents);

    // Make the combo box prefer to expand
    QSizePolicy policy = m_outlineCombo->sizePolicy();
    policy.setHorizontalPolicy(QSizePolicy::Expanding);
    m_outlineCombo->setSizePolicy(policy);

177
    insertExtraToolBarWidget(BaseTextEditorWidget::Left, m_outlineCombo);
178

179 180 181 182 183 184 185 186 187 188
//    if (m_modelManager) {
//        m_semanticHighlighter->setModelManager(m_modelManager);
//        connect(m_modelManager, SIGNAL(documentUpdated(GLSL::Document::Ptr)),
//                this, SLOT(onDocumentUpdated(GLSL::Document::Ptr)));
//        connect(m_modelManager, SIGNAL(libraryInfoUpdated(QString,GLSL::LibraryInfo)),
//                this, SLOT(forceSemanticRehighlight()));
//        connect(this->document(), SIGNAL(modificationChanged(bool)), this, SLOT(modificationChanged(bool)));
//    }
}

189
int GlslEditorWidget::editorRevision() const
190 191 192 193 194
{
    //return document()->revision();
    return 0;
}

195
bool GlslEditorWidget::isOutdated() const
196 197 198 199 200 201 202
{
//    if (m_semanticInfo.revision() != editorRevision())
//        return true;

    return false;
}

203
bool GlslEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
204
{
205
    textDocument()->setMimeType(Core::MimeDatabase::findByFile(QFileInfo(fileName)).type());
206
    bool b = BaseTextEditor::open(errorString, fileName, realFileName);
207 208 209
    return b;
}

210
QString GlslEditorWidget::wordUnderCursor() const
211 212
{
    QTextCursor tc = textCursor();
213
    const QChar ch = document()->characterAt(tc.position() - 1);
214 215 216 217 218 219 220 221 222
    // make sure that we're not at the start of the next word.
    if (ch.isLetterOrNumber() || ch == QLatin1Char('_'))
        tc.movePosition(QTextCursor::Left);
    tc.movePosition(QTextCursor::StartOfWord);
    tc.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
    const QString word = tc.selectedText();
    return word;
}

223
BaseTextEditor *GlslEditorWidget::createEditor()
224
{
225
    QTC_ASSERT("should not happen anymore" && false, return 0);
226 227
}

228
void GlslEditorWidget::updateDocumentNow()
229
{
230
    m_updateDocumentTimer.stop();
Roberto Raggi's avatar
Roberto Raggi committed
231

232
    int variant = languageVariant(textDocument()->mimeType());
Roberto Raggi's avatar
Roberto Raggi committed
233 234 235
    const QString contents = toPlainText(); // get the code from the editor
    const QByteArray preprocessedCode = contents.toLatin1(); // ### use the QtCreator C++ preprocessor.

236
    Document::Ptr doc(new Document());
237
    Engine *engine = new GLSL::Engine();
238 239
    doc->_engine = new GLSL::Engine();
    Parser parser(doc->_engine, preprocessedCode.constData(), preprocessedCode.size(), variant);
240
    TranslationUnitAST *ast = parser.parse();
Roberto Raggi's avatar
Roberto Raggi committed
241 242
    if (ast != 0 || extraSelections(CodeWarningsSelection).isEmpty()) {
        Semantic sem;
243 244
        Scope *globalScope = engine->newNamespace();
        doc->_globalScope = globalScope;
hjk's avatar
hjk committed
245 246 247 248 249 250 251 252 253 254
        const GLSLEditorPlugin::InitFile *file = GLSLEditorPlugin::shaderInit(variant);
        sem.translationUnit(file->ast, globalScope, file->engine);
        if (variant & Lexer::Variant_VertexShader) {
            file = GLSLEditorPlugin::vertexShaderInit(variant);
            sem.translationUnit(file->ast, globalScope, file->engine);
        }
        if (variant & Lexer::Variant_FragmentShader) {
            file = GLSLEditorPlugin::fragmentShaderInit(variant);
            sem.translationUnit(file->ast, globalScope, file->engine);
        }
255 256 257 258
        sem.translationUnit(ast, globalScope, engine);

        CreateRanges createRanges(document(), doc);
        createRanges(ast);
Roberto Raggi's avatar
Roberto Raggi committed
259 260 261 262 263 264 265 266 267 268 269 270

        QTextCharFormat errorFormat;
        errorFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline);
        errorFormat.setUnderlineColor(Qt::red);

        QTextCharFormat warningFormat;
        warningFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline);
        warningFormat.setUnderlineColor(Qt::darkYellow);

        QList<QTextEdit::ExtraSelection> sels;
        QSet<int> errors;

271
        foreach (const DiagnosticMessage &m, engine->diagnosticMessages()) {
Roberto Raggi's avatar
Roberto Raggi committed
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
            if (! m.line())
                continue;
            else if (errors.contains(m.line()))
                continue;

            errors.insert(m.line());

            QTextCursor cursor(document()->findBlockByNumber(m.line() - 1));
            cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);

            QTextEdit::ExtraSelection sel;
            sel.cursor = cursor;
            sel.format = m.isError() ? errorFormat : warningFormat;
            sel.format.setToolTip(m.message());
            sels.append(sel);
        }

        setExtraSelections(CodeWarningsSelection, sels);
290
        m_glslDocument = doc;
Roberto Raggi's avatar
Roberto Raggi committed
291
    }
292
}
Roberto Raggi's avatar
Roberto Raggi committed
293

294
int GlslEditorWidget::languageVariant(const QString &type)
Roberto Raggi's avatar
Roberto Raggi committed
295
{
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    int variant = 0;
    bool isVertex = false;
    bool isFragment = false;
    bool isDesktop = false;
    if (type.isEmpty()) {
        // ### Before file has been opened, so don't know the mime type.
        isVertex = true;
        isFragment = true;
    } else if (type == QLatin1String("text/x-glsl") ||
               type == QLatin1String("application/x-glsl")) {
        isVertex = true;
        isFragment = true;
        isDesktop = true;
    } else if (type == QLatin1String("text/x-glsl-vert")) {
        isVertex = true;
        isDesktop = true;
    } else if (type == QLatin1String("text/x-glsl-frag")) {
        isFragment = true;
        isDesktop = true;
    } else if (type == QLatin1String("text/x-glsl-es-vert")) {
        isVertex = true;
    } else if (type == QLatin1String("text/x-glsl-es-frag")) {
        isFragment = true;
    }
    if (isDesktop)
        variant |= Lexer::Variant_GLSL_120;
    else
323
        variant |= Lexer::Variant_GLSL_ES_100;
324 325 326 327 328
    if (isVertex)
        variant |= Lexer::Variant_VertexShader;
    if (isFragment)
        variant |= Lexer::Variant_FragmentShader;
    return variant;
Roberto Raggi's avatar
Roberto Raggi committed
329
}
330

331 332
IAssistInterface *GlslEditorWidget::createAssistInterface(
    AssistKind kind, AssistReason reason) const
Leandro Melo's avatar
Leandro Melo committed
333
{
334
    if (kind == Completion)
Leandro Melo's avatar
Leandro Melo committed
335 336
        return new GLSLCompletionAssistInterface(document(),
                                                 position(),
337
                                                 editor()->document()->filePath(),
Leandro Melo's avatar
Leandro Melo committed
338
                                                 reason,
339
                                                 textDocument()->mimeType(),
hjk's avatar
hjk committed
340
                                                 m_glslDocument);
Leandro Melo's avatar
Leandro Melo committed
341 342
    return BaseTextEditorWidget::createAssistInterface(kind, reason);
}
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398


//////////////////////////////////////////////////////////////////
//
//  GlslEditor
//
//////////////////////////////////////////////////////////////////

GlslEditor::GlslEditor()
{
    addContext(C_GLSLEDITOR_ID);
    setDuplicateSupported(true);
    setCommentStyle(Utils::CommentDefinition::CppStyle);
    setCompletionAssistProvider(ExtensionSystem::PluginManager::getObject<GLSLCompletionAssistProvider>());

    setEditorCreator([]() { return new GlslEditor; });
    setWidgetCreator([]() { return new GlslEditorWidget; });

    setDocumentCreator([]() -> BaseTextDocument * {
        auto doc = new BaseTextDocument(C_GLSLEDITOR_ID);
        doc->setIndenter(new GLSLIndenter);
        new Highlighter(doc);
        return doc;
    });
}


//////////////////////////////////////////////////////////////////
//
//  GlslEditorFactory
//
//////////////////////////////////////////////////////////////////

GlslEditorFactory::GlslEditorFactory()
{
    setId(C_GLSLEDITOR_ID);
    setDisplayName(qApp->translate("OpenWith::Editors", C_GLSLEDITOR_DISPLAY_NAME));
    addMimeType(GLSL_MIMETYPE);
    addMimeType(GLSL_MIMETYPE_VERT);
    addMimeType(GLSL_MIMETYPE_FRAG);
    addMimeType(GLSL_MIMETYPE_VERT_ES);
    addMimeType(GLSL_MIMETYPE_FRAG_ES);
    new TextEditorActionHandler(this, C_GLSLEDITOR_ID,
                                TextEditorActionHandler::Format
                                | TextEditorActionHandler::UnCommentSelection
                                | TextEditorActionHandler::UnCollapseAll);

}

Core::IEditor *GlslEditorFactory::createEditor()
{
    return new GlslEditor;
}

} // namespace Internal
} // namespace GLSLEditor