glsleditor.cpp 13.8 KB
Newer Older
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
8 9 10 11
**
**
** GNU Lesser General Public License Usage
**
hjk's avatar
hjk committed
12 13 14 15 16 17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21 22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23 24 25 26 27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28
** If you have questions regarding the use of this file, please contact
Tobias Hunger's avatar
Tobias Hunger committed
29
** Nokia at info@qt.nokia.com.
30 31 32 33 34 35 36
**
**************************************************************************/

#include "glsleditor.h"
#include "glsleditoreditable.h"
#include "glsleditorconstants.h"
#include "glsleditorplugin.h"
37
#include "glslhighlighter.h"
38 39
#include "glslautocompleter.h"
#include "glslindenter.h"
Leandro Melo's avatar
Leandro Melo committed
40
#include "glslcompletionassist.h"
41

Roberto Raggi's avatar
Roberto Raggi committed
42 43 44
#include <glsl/glsllexer.h>
#include <glsl/glslparser.h>
#include <glsl/glslengine.h>
45
#include <glsl/glslsemantic.h>
Roberto Raggi's avatar
Roberto Raggi committed
46
#include <glsl/glslsymbols.h>
Roberto Raggi's avatar
Roberto Raggi committed
47

48 49
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
50
#include <coreplugin/id.h>
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <extensionsystem/pluginmanager.h>
#include <texteditor/basetextdocument.h>
#include <texteditor/fontsettings.h>
#include <texteditor/tabsettings.h>
#include <texteditor/texteditorconstants.h>
#include <texteditor/texteditorsettings.h>
#include <texteditor/syntaxhighlighter.h>
#include <texteditor/refactoroverlay.h>
#include <texteditor/tooltip/tooltip.h>
#include <qmldesigner/qmldesignerconstants.h>
#include <utils/changeset.h>
#include <utils/uncommentselection.h>

#include <QtCore/QFileInfo>
#include <QtCore/QSignalMapper>
#include <QtCore/QTimer>
Roberto Raggi's avatar
Roberto Raggi committed
71
#include <QtCore/QDebug>
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

#include <QtGui/QMenu>
#include <QtGui/QComboBox>
#include <QtGui/QHeaderView>
#include <QtGui/QInputDialog>
#include <QtGui/QMainWindow>
#include <QtGui/QToolBar>
#include <QtGui/QTreeView>

using namespace GLSL;
using namespace GLSLEditor;
using namespace GLSLEditor::Internal;

enum {
    UPDATE_DOCUMENT_DEFAULT_INTERVAL = 150
};

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
namespace {

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);
        }
    }
};

} // end of anonymous namespace

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);
}

149 150
GLSLTextEditorWidget::GLSLTextEditorWidget(QWidget *parent) :
    TextEditor::BaseTextEditorWidget(parent),
151 152 153 154 155
    m_outlineCombo(0)
{
    setParenthesesMatchingEnabled(true);
    setMarksVisible(true);
    setCodeFoldingSupported(true);
156 157
    setIndenter(new GLSLIndenter());
    setAutoCompleter(new GLSLCompleter());
158 159 160 161 162 163 164 165

    m_updateDocumentTimer = new QTimer(this);
    m_updateDocumentTimer->setInterval(UPDATE_DOCUMENT_DEFAULT_INTERVAL);
    m_updateDocumentTimer->setSingleShot(true);
    connect(m_updateDocumentTimer, SIGNAL(timeout()), this, SLOT(updateDocumentNow()));

    connect(this, SIGNAL(textChanged()), this, SLOT(updateDocument()));

166
    new Highlighter(baseTextDocument());
167 168 169 170 171 172 173 174 175 176 177

//    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)));
//    }
}

178
GLSLTextEditorWidget::~GLSLTextEditorWidget()
179 180 181
{
}

182
int GLSLTextEditorWidget::editorRevision() const
183 184 185 186 187
{
    //return document()->revision();
    return 0;
}

188
bool GLSLTextEditorWidget::isOutdated() const
189 190 191 192 193 194 195 196 197
{
//    if (m_semanticInfo.revision() != editorRevision())
//        return true;

    return false;
}

Core::IEditor *GLSLEditorEditable::duplicate(QWidget *parent)
{
198 199
    GLSLTextEditorWidget *newEditor = new GLSLTextEditorWidget(parent);
    newEditor->duplicateFrom(editorWidget());
200
    GLSLEditorPlugin::instance()->initializeEditor(newEditor);
201
    return newEditor->editor();
202 203 204 205 206 207 208
}

QString GLSLEditorEditable::id() const
{
    return QLatin1String(GLSLEditor::Constants::C_GLSLEDITOR_ID);
}

209
bool GLSLEditorEditable::open(QString *errorString, const QString &fileName, const QString &realFileName)
210
{
211
    editorWidget()->setMimeType(Core::ICore::instance()->mimeDatabase()->findByFile(QFileInfo(fileName)).type());
212
    bool b = TextEditor::BaseTextEditor::open(errorString, fileName, realFileName);
213 214 215
    return b;
}

216
void GLSLTextEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
217
{
218
    TextEditor::BaseTextEditorWidget::setFontSettings(fs);
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    Highlighter *highlighter = qobject_cast<Highlighter*>(baseTextDocument()->syntaxHighlighter());
    if (!highlighter)
        return;

    /*
        NumberFormat,
        StringFormat,
        TypeFormat,
        KeywordFormat,
        LabelFormat,
        CommentFormat,
        VisualWhitespace,
     */
    static QVector<QString> categories;
    if (categories.isEmpty()) {
        categories << QLatin1String(TextEditor::Constants::C_NUMBER)
                   << QLatin1String(TextEditor::Constants::C_STRING)
                   << QLatin1String(TextEditor::Constants::C_TYPE)
                   << QLatin1String(TextEditor::Constants::C_KEYWORD)
238 239 240
                   << QLatin1String(TextEditor::Constants::C_OPERATOR)
                   << QLatin1String(TextEditor::Constants::C_PREPROCESSOR)
                   << QLatin1String(TextEditor::Constants::C_LABEL)
241
                   << QLatin1String(TextEditor::Constants::C_COMMENT)
242 243 244 245
                   << QLatin1String(TextEditor::Constants::C_DOXYGEN_COMMENT)
                   << QLatin1String(TextEditor::Constants::C_DOXYGEN_TAG)
                   << QLatin1String(TextEditor::Constants::C_VISUAL_WHITESPACE)
                   << QLatin1String(TextEditor::Constants::C_REMOVED_LINE);
246 247 248 249 250 251
    }

    highlighter->setFormats(fs.toTextCharFormats(categories));
    highlighter->rehighlight();
}

252
QString GLSLTextEditorWidget::wordUnderCursor() const
253 254 255 256 257 258 259 260 261 262 263 264
{
    QTextCursor tc = textCursor();
    const QChar ch = characterAt(tc.position() - 1);
    // 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;
}

265
TextEditor::BaseTextEditor *GLSLTextEditorWidget::createEditor()
266 267 268 269 270 271
{
    GLSLEditorEditable *editable = new GLSLEditorEditable(this);
    createToolBar(editable);
    return editable;
}

272
void GLSLTextEditorWidget::createToolBar(GLSLEditorEditable *editor)
273 274 275
{
    m_outlineCombo = new QComboBox;
    m_outlineCombo->setMinimumContentsLength(22);
Roberto Raggi's avatar
Roberto Raggi committed
276 277

    // ### m_outlineCombo->setModel(m_outlineModel);
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

    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);

293
    editor->insertExtraToolBarWidget(TextEditor::BaseTextEditor::Left, m_outlineCombo);
294 295
}

296
bool GLSLTextEditorWidget::event(QEvent *e)
297
{
298
    return BaseTextEditorWidget::event(e);
299 300
}

301
void GLSLTextEditorWidget::unCommentSelection()
302 303 304 305
{
    Utils::unCommentSelection(this);
}

306
void GLSLTextEditorWidget::updateDocument()
307
{
Roberto Raggi's avatar
Roberto Raggi committed
308
    m_updateDocumentTimer->start();
309 310
}

311
void GLSLTextEditorWidget::updateDocumentNow()
312
{
Roberto Raggi's avatar
Roberto Raggi committed
313 314
    m_updateDocumentTimer->stop();

315
    int variant = languageVariant(mimeType());
Roberto Raggi's avatar
Roberto Raggi committed
316 317 318
    const QString contents = toPlainText(); // get the code from the editor
    const QByteArray preprocessedCode = contents.toLatin1(); // ### use the QtCreator C++ preprocessor.

319 320 321 322
    Document::Ptr doc(new Document());
    GLSL::Engine *engine = new GLSL::Engine();
    doc->_engine = new GLSL::Engine();
    Parser parser(doc->_engine, preprocessedCode.constData(), preprocessedCode.size(), variant);
323
    TranslationUnitAST *ast = parser.parse();
Roberto Raggi's avatar
Roberto Raggi committed
324 325 326 327
    if (ast != 0 || extraSelections(CodeWarningsSelection).isEmpty()) {
        GLSLEditorPlugin *plugin = GLSLEditorPlugin::instance();

        Semantic sem;
328 329
        Scope *globalScope = engine->newNamespace();
        doc->_globalScope = globalScope;
330
        sem.translationUnit(plugin->shaderInit(variant)->ast, globalScope, plugin->shaderInit(variant)->engine);
Roberto Raggi's avatar
Roberto Raggi committed
331
        if (variant & Lexer::Variant_VertexShader)
332
            sem.translationUnit(plugin->vertexShaderInit(variant)->ast, globalScope, plugin->vertexShaderInit(variant)->engine);
Roberto Raggi's avatar
Roberto Raggi committed
333
        if (variant & Lexer::Variant_FragmentShader)
334
            sem.translationUnit(plugin->fragmentShaderInit(variant)->ast, globalScope, plugin->fragmentShaderInit(variant)->engine);
335 336 337 338
        sem.translationUnit(ast, globalScope, engine);

        CreateRanges createRanges(document(), doc);
        createRanges(ast);
Roberto Raggi's avatar
Roberto Raggi committed
339 340 341 342 343 344 345 346 347 348 349 350

        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;

351
        foreach (const DiagnosticMessage &m, engine->diagnosticMessages()) {
Roberto Raggi's avatar
Roberto Raggi committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
            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);
370
        m_glslDocument = doc;
Roberto Raggi's avatar
Roberto Raggi committed
371
    }
372
}
Roberto Raggi's avatar
Roberto Raggi committed
373

374
int GLSLTextEditorWidget::languageVariant(const QString &type)
Roberto Raggi's avatar
Roberto Raggi committed
375
{
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    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
403
        variant |= Lexer::Variant_GLSL_ES_100;
404 405 406 407 408
    if (isVertex)
        variant |= Lexer::Variant_VertexShader;
    if (isFragment)
        variant |= Lexer::Variant_FragmentShader;
    return variant;
Roberto Raggi's avatar
Roberto Raggi committed
409
}
410

411
Document::Ptr GLSLTextEditorWidget::glslDocument() const
412 413 414
{
    return m_glslDocument;
}
Leandro Melo's avatar
Leandro Melo committed
415 416 417 418 419 420 421 422 423 424 425 426 427 428

TextEditor::IAssistInterface *GLSLTextEditorWidget::createAssistInterface(
    TextEditor::AssistKind kind,
    TextEditor::AssistReason reason) const
{
    if (kind == TextEditor::Completion)
        return new GLSLCompletionAssistInterface(document(),
                                                 position(),
                                                 editor()->file(),
                                                 reason,
                                                 mimeType(),
                                                 glslDocument());
    return BaseTextEditorWidget::createAssistInterface(kind, reason);
}