summaryrefslogtreecommitdiffstats
path: root/tools/qqem/codehelper.cpp
blob: 2d55d355c15765d2f30b1aee929cbd11cf3221a0 (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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
// Qt-Security score:critical reason:data-parser

#include "codehelper.h"
#include "effectmanager.h"
#include "syntaxhighlighterdata.h"
#include <QString>

CodeHelper::CodeHelper(QObject *parent)
    : QObject{parent}
{
    m_effectManager = static_cast<EffectManager *>(parent);
    m_codeCompletionModel = new CodeCompletionModel(this);
    m_codeCompletionTimer.setInterval(500);
    m_codeCompletionTimer.setSingleShot(true);
    connect(&m_codeCompletionTimer, &QTimer::timeout, this, &CodeHelper::showCodeCompletion);

    // Cache syntax highlight data
    auto args = SyntaxHighlighterData::reservedArgumentNames();
    for (const auto &arg : args)
        m_reservedArgumentNames << QString::fromUtf8(arg);
    auto funcs = SyntaxHighlighterData::reservedFunctionNames();
    for (const auto &func : funcs)
        m_reservedFunctionNames << QString::fromUtf8(func);
    auto tags = SyntaxHighlighterData::reservedTagNames();
    for (const auto &tag : tags)
        m_reservedTagNames << QString::fromUtf8(tag);

    std::sort(m_reservedArgumentNames.begin(), m_reservedArgumentNames.end());
    std::sort(m_reservedFunctionNames.begin(), m_reservedFunctionNames.end());
    std::sort(m_reservedTagNames.begin(), m_reservedTagNames.end());
}

// Process the keyCode and return true if key was handled and
// TextEdit itself shouldn't append it.
bool CodeHelper::processKey(QQuickTextEdit *textEdit, int keyCode, int modifiers)
{
    int position = textEdit->cursorPosition();
    const QString &code = textEdit->text();
    if (m_codeCompletionVisible) {
        // When code completition is visible, some keys have special meening
        if (keyCode == Qt::Key_Escape || keyCode == Qt::Key_Left || keyCode == Qt::Key_Right) {
            setCodeCompletionVisible(false);
            return true;
        } else if (keyCode == Qt::Key_Tab || keyCode == Qt::Key_Return) {
            applyCodeCompletion(textEdit);
            return true;
        } else if (keyCode == Qt::Key_Down) {
            m_codeCompletionModel->nextItem();
            return true;
        } else if (keyCode == Qt::Key_Up) {
            m_codeCompletionModel->previousItem();
            return true;
        } else {
            updateCodeCompletion(textEdit);
        }
    }
    if (keyCode == Qt::Key_Return) {
        // See if we are inside multiline comments
        bool multilineComment = false;
        QString prevCode = code.left(position);
        int codeStartPos = prevCode.lastIndexOf("/*");
        int codeEndPos = prevCode.lastIndexOf("*/");
        if (codeStartPos > codeEndPos)
            multilineComment = true;

        // Get only the previous line before pressing return
        QString singleLine = code.left(position);
        int lineStartPos = singleLine.lastIndexOf('\n');
        if (lineStartPos > -1)
            singleLine = singleLine.remove(0, lineStartPos + 1);

        QString indent = autoIndentGLSLNextLine(singleLine, multilineComment);
        textEdit->insert(position, indent);
        return true;
    } else if (keyCode == Qt::Key_BraceRight) {
        // Get only the current line, without the last '}'
        QString singleLine = code.left(position);
        int lineStartPos = singleLine.lastIndexOf('\n');
        if (lineStartPos > -1)
            singleLine = singleLine.remove(0, lineStartPos + 1);

        if (singleLine.trimmed().isEmpty()) {
            // Line only had '}' so unindent it (max) one step
            int startPos = std::max(int(position - singleLine.size()), position - 4);
            textEdit->remove(startPos, position);
        }
        return false;
    } else if (keyCode == Qt::Key_Tab) {
        // Replace tabs with spaces
        QString indent = QStringLiteral("    ");
        textEdit->insert(position, indent);
        return true;
    } else if ((modifiers & Qt::ControlModifier) && keyCode == Qt::Key_Space) {
        updateCodeCompletion(textEdit, true);
    }
    return false;
}


// Formats GLSL code with simple indent rules.
// Not a full parser so doesn't work with more complex code.
// For that, consider ClangFormat etc.
QString CodeHelper::autoIndentGLSLCode(const QString &code)
{
    QStringList out;
    // Index (indent level) currently
    int index = 0;
    // Index (indent level) for previous line
    int prevIndex = 0;
    // Indent spaces
    QString indent;
    // True when we are inside multiline comments (/* .. */)
    bool multilineComment = false;
    // Increased when command continues to next line (e.g. "if ()")
    int nextLineIndents = 0;
    // Stores indent before nextLineIndents started
    int indentBeforeSingles = 0;

    QStringList codeList = code.split('\n');
    for (const auto &cOrig : codeList) {
        QString c = cOrig.trimmed();

        if (c.isEmpty()) {
            // Lines with only spaces are emptied but kept
            out << c;
            continue;
        }

        bool isPreprocessor = c.startsWith('#');
        if (isPreprocessor) {
            // Preprocesser lines have zero intent
            out << c;
            continue;
        }

        bool isTag = c.startsWith('@');

        // Separate content after "//" to commenPart
        QString commentPart;
        int lineCommentIndex = c.indexOf("//");
        if (lineCommentIndex > -1) {
            commentPart = c.last(c.length() - lineCommentIndex);
            c = c.first(lineCommentIndex);
            // Move spaces from c to comment part (to also trim c)
            while (!c.isEmpty() && c.endsWith(' ')) {
                commentPart.prepend(' ');
                c.chop(1);
            }
        }

        // Multiline comments state
        int startComments = c.count("/*");
        int endComments = c.count("*/");
        int commendsChange = startComments - endComments;
        if (commendsChange > 0)
            multilineComment = true;
        else if (commendsChange < 0)
            multilineComment = false;

        if (multilineComment || endComments > startComments) {
            // Lines inside /* .. */ are not touched
            out << cOrig;
            continue;
        }

        // Check indent for next line
        int indexChange = 0;
        int startBlocks = c.count('{');
        int endBlocks = c.count('}');
        indexChange += startBlocks - endBlocks;
        int startBrackets = c.count('(');
        int endBrackets = c.count(')');
        indexChange += startBrackets - endBrackets;
        index += indexChange;
        index = std::max(index, 0);
        indent.clear();
        int currentIndex = indexChange > 0 ? prevIndex : index;
        if (!isTag) {
            if (currentIndex > 0 && startBlocks > 0 && endBlocks > 0) {
                // Note: "} else {", "} else if () {"
                // Indent one step lower
                currentIndex--;
            } else if (endBrackets > startBrackets) {
                // Note: "variable)"
                // Indent one step higher
                currentIndex++;
            }
            if (!c.startsWith('{'))
                currentIndex += nextLineIndents;

            if (!c.isEmpty() && startBlocks == 0 && endBlocks == 0 && indexChange == 0 && !c.endsWith(';') && !c.endsWith(',') && !c.endsWith('(') && !c.endsWith("*/")) {
                // Note: "if ()", "else if ()", "else", "for (..)"
                // Something that should continue to next line
                nextLineIndents++;
            } else if (nextLineIndents > 0) {
                // Return to indent before e.g. "if (thing) \n if (thing2) \n something;"
                nextLineIndents = indentBeforeSingles;
                indentBeforeSingles = nextLineIndents;
            }
        }

        // Apply indent
        QString singleIndentStep = QStringLiteral("    ");
        for (int i = 0; i < currentIndex; i++)
            indent += singleIndentStep;
        c.prepend(indent);

        out << (c + commentPart);
        prevIndex = index;
    }
    return out.join('\n');
}

// Takes in the previous line (before pressing return key)
// and returns suitable indent string with spaces.
QString CodeHelper::autoIndentGLSLNextLine(const QString &codeLine, bool multilineComment)
{
    int spaces = 0;

    // Check how many spaces previous line had
    for (int i = 0; i < codeLine.size() ; i++) {
        if (codeLine.at(i) == ' ')
            spaces++;
        else
            break;
    }

    QString c = codeLine.trimmed();
    bool isPreprocessor = c.startsWith('#');
    bool isTag = c.startsWith('@');

    // Remove content after "//"
    int lineCommentIndex = c.indexOf("//");
    if (lineCommentIndex > -1) {
        c = c.first(lineCommentIndex);
        c = c.trimmed();
    }

    if (!c.isEmpty() && !isPreprocessor && !isTag && !multilineComment) {
        // Check indent for next line
        int index = 0;
        int indexChange = 0;
        int startBlocks = c.count('{');
        int endBlocks = c.count('}');
        indexChange += startBlocks - endBlocks;
        int startBrackets = c.count('(');
        int endBrackets = c.count(')');
        indexChange += startBrackets - endBrackets;
        if (indexChange > 0) {
            // Note: "{" "if () {", "vec4 x = vec4("
            index++;
        } else if (indexChange < 0 && c.trimmed().size() > 1) {
            // Note: "something; }", but NOT "}" as it has be unindented already
            index--;
        }

        if (index == 0 && !c.isEmpty() && !c.endsWith(';') && !c.endsWith("*/") && !c.endsWith('}')) {
            // Note: "if ()", "else if ()", "else", "for (..)"
            // Something that should continue to next line
            index++;
        }
        spaces += 4 * index;
    }

    QString indent;
    indent.fill(' ', spaces);
    return '\n' + indent;
}

// Get current word under the cursor
// Word is letters, digits and "_".
// Also if word starts with "//" that is included
QString CodeHelper::getCurrentWord(QQuickTextEdit *textEdit)
{
    if (!textEdit)
        return QString();
    int cursorPosition = textEdit->cursorPosition();
    int cPos = cursorPosition - 1;
    int maxPos = textEdit->text().size();
    QString currentWord;
    QChar c = textEdit->getText(cPos, cPos + 1).front();
    while (cPos >= 0 && (c.isLetterOrNumber() || c == '_')) {
        currentWord.prepend(c);
        cPos--;
        c = textEdit->getText(cPos, cPos + 1).front();
    }
    // Special case of "@" tags
    if (cPos >= 1) {
        QString s = textEdit->getText(cPos, cPos + 1);
        if (s == QStringLiteral("@"))
            currentWord.prepend(QStringLiteral("@"));
    }
    cPos = cursorPosition;
    c = textEdit->getText(cPos, cPos + 1).front();
    while (cPos <= maxPos && (c.isLetterOrNumber() || c == '_')) {
        currentWord.append(c);
        cPos++;
        c = textEdit->getText(cPos, cPos + 1).front();
    }
    return currentWord;
}

// Remove the current word under cursor
void CodeHelper::removeCurrentWord(QQuickTextEdit *textEdit)
{
    if (!textEdit)
        return;
    int cursorPosition = textEdit->cursorPosition();
    int cPos = cursorPosition - 1;
    int maxPos = textEdit->text().size();
    int firstPos = 0;
    int lastPos = 0;
    QChar c = textEdit->getText(cPos, cPos + 1).front();
    while (cPos >= 0 && (c.isLetterOrNumber() || c == '_')) {
        cPos--;
        c = textEdit->getText(cPos, cPos + 1).front();
    }
    // Special case of "@" tags
    if (cPos >= 1) {
        QString s = textEdit->getText(cPos, cPos + 1);
        if (s == QStringLiteral("@"))
            cPos--;
    }
    firstPos = cPos + 1;
    cPos = cursorPosition;
    c = textEdit->getText(cPos, cPos + 1).front();
    while (cPos <= maxPos && (c.isLetterOrNumber() || c == '_')) {
        cPos++;
        c = textEdit->getText(cPos, cPos + 1).front();
    }
    lastPos = cPos;
    textEdit->remove(firstPos, lastPos);
}

bool CodeHelper::codeCompletionVisible() const
{
    return m_codeCompletionVisible;
}

void CodeHelper::setCodeCompletionVisible(bool visible)
{
    if (m_codeCompletionVisible == visible)
        return;

    m_codeCompletionVisible = visible;
    if (!m_codeCompletionVisible)
        m_codeCompletionModel->setCurrentIndex(0);

    Q_EMIT codeCompletionVisibleChanged();
}

// Update and show code completion popup
// When force is true, do this without a delay.
void CodeHelper::updateCodeCompletion(QQuickTextEdit *textEdit, bool force)
{
    m_textEdit = textEdit;
    if (force)
        showCodeCompletion();
    else
        m_codeCompletionTimer.start();
}

void CodeHelper::showCodeCompletion()
{
    if (!m_textEdit)
        return;

    QString currentWord = getCurrentWord(m_textEdit);
    QString currentWordCleaned = currentWord;
    bool isComment = false;

    // Check if word is comment/tag
    if (currentWordCleaned.size() >= 2 && currentWordCleaned.left(2) == "//") {
        isComment = true;
        currentWordCleaned = currentWordCleaned.right(currentWordCleaned.size() - 2);
    }

    m_codeCompletionModel->beginResetModel();
    m_codeCompletionModel->clearItems();

    if (!isComment) {
        for (const auto &a : m_reservedArgumentNames) {
            if (a.startsWith(currentWordCleaned, Qt::CaseInsensitive) && a.size() > currentWordCleaned.size())
                m_codeCompletionModel->addItem(a, CodeCompletionModel::TypeArgument);
        }

        for (const auto &a : m_reservedFunctionNames) {
            if (a.startsWith(currentWordCleaned, Qt::CaseInsensitive) && a.size() > currentWordCleaned.size())
                m_codeCompletionModel->addItem(a, CodeCompletionModel::TypeFunction);
        }

        for (const auto &a : m_reservedTagNames) {
            if (a.startsWith(currentWord, Qt::CaseInsensitive) && a.size() > currentWord.size())
                m_codeCompletionModel->addItem(a, CodeCompletionModel::TypeTag);
        }
    }

    m_codeCompletionModel->endResetModel();

    if (!m_codeCompletionModel->m_modelList.isEmpty()) {
        m_codeCompletionModel->setCurrentIndex(0);
        setCodeCompletionVisible(true);
    } else {
        setCodeCompletionVisible(false);
    }
}

CodeCompletionModel *CodeHelper::codeCompletionModel() const
{
    return m_codeCompletionModel;
}

void CodeHelper::applyCodeCompletion(QQuickTextEdit *textEdit)
{
    CodeCompletionModel::ModelData t = m_codeCompletionModel->currentItem();
    if (!t.name.isEmpty()) {
        // Replace the current word with code completion one
        removeCurrentWord(textEdit);
        textEdit->insert(textEdit->cursorPosition(), t.name);
        if (t.type == CodeCompletionModel::TypeFunction) {
            // For functions, place cursor between parentheses, e.g. "sin(|)".
            textEdit->setCursorPosition(textEdit->cursorPosition() - 1);
        }
    }
    setCodeCompletionVisible(false);
}