aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/texteditor/syntaxhighlighterrunner.cpp
blob: bf53d90561bd286f2f8a5388d0462c9d1433c566 (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
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "syntaxhighlighterrunner.h"

#include "fontsettings.h"
#include "textdocumentlayout.h"
#include "texteditorsettings.h"
#include "highlighter.h"

#include <utils/algorithm.h>
#include <utils/textutils.h>

#include <QMetaObject>
#include <QTextCursor>
#include <QTextDocument>
#include <QThread>

namespace TextEditor {

struct BlockPreeditData {
    int position;
    QString text;
};

class SyntaxHighlighterRunnerPrivate : public QObject
{
    Q_OBJECT
public:
    SyntaxHighlighterRunnerPrivate(SyntaxHighlighter *highlighter,
                                   QTextDocument *document,
                                   bool async)
        : m_highlighter(highlighter)
    {
        if (async) {
            m_document = new QTextDocument(this);
            m_document->setDocumentLayout(new TextDocumentLayout(m_document));
            m_highlighter->setParent(m_document);
        } else {
            m_document = document;
        }

        m_highlighter->setDocument(m_document);

        connect(m_highlighter,
                &SyntaxHighlighter::resultsReady,
                this,
                &SyntaxHighlighterRunnerPrivate::resultsReady);
    }

    void changeDocument(int from,
                        int charsRemoved,
                        const QString textAdded,
                        const QMap<int, BlockPreeditData> &blocksPreedit)
    {
        QTextCursor cursor(m_document);
        cursor.setPosition(qMin(m_document->characterCount() - 1, from + charsRemoved));
        cursor.setPosition(from, QTextCursor::KeepAnchor);
        cursor.insertText(textAdded);

        for (auto it = blocksPreedit.cbegin(); it != blocksPreedit.cend(); ++it) {
            const QTextBlock block = m_document->findBlockByNumber(it.key());
            block.layout()->setPreeditArea(it.value().position, it.value().text);
        }
    }

    void setExtraFormats(const QMap<int, QList<QTextLayout::FormatRange>> &formatMap)
    {
        for (auto it = formatMap.cbegin(); it != formatMap.cend(); ++it)
            m_highlighter->setExtraFormats(m_document->findBlockByNumber(it.key()), it.value());
    }

    void clearExtraFormats(const QList<int> &blockNumbers)
    {
        for (auto it = blockNumbers.cbegin(); it != blockNumbers.cend(); ++it)
            m_highlighter->clearExtraFormats(m_document->findBlockByNumber(*it));
    }

    void clearAllExtraFormats() { m_highlighter->clearAllExtraFormats(); }

    void setFontSettings(const TextEditor::FontSettings &fontSettings)
    {
        m_highlighter->setFontSettings(fontSettings);
        rehighlight();
    }

    void setDefinitionName(const QString &name)
    {
        return m_highlighter->setDefinitionName(name);
    }

    void setLanguageFeaturesFlags(unsigned int flags)
    {
        m_highlighter->setLanguageFeaturesFlags(flags);
    }

    void setEnabled(bool enabled) { m_highlighter->setEnabled(enabled); }

    void rehighlight() { m_highlighter->rehighlight(); }

    SyntaxHighlighter *m_highlighter = nullptr;
    QTextDocument *m_document = nullptr;

signals:
    void resultsReady(const QList<SyntaxHighlighter::Result> &result);

};

SyntaxHighlighterRunner::SyntaxHighlighterRunner(SyntaxHighlighter *highlighter,
                                                 QTextDocument *document,
                                                 bool async)
    : d(new SyntaxHighlighterRunnerPrivate(highlighter, document, async))
    , m_document(document)
{
    m_useGenericHighlighter = qobject_cast<Highlighter *>(d->m_highlighter);

    if (async) {
        m_thread.emplace();
        d->moveToThread(&*m_thread);
        connect(&*m_thread, &QThread::finished, d, &QObject::deleteLater);
        m_thread->start();

        connect(d,
                &SyntaxHighlighterRunnerPrivate::resultsReady,
                this,
                &SyntaxHighlighterRunner::applyFormatRanges);

        changeDocument(0, 0, document->characterCount());
        connect(document,
                &QTextDocument::contentsChange,
                this,
                &SyntaxHighlighterRunner::changeDocument);
    } else {
        connect(d,
                &SyntaxHighlighterRunnerPrivate::resultsReady,
                this,
                [this](const QList<SyntaxHighlighter::Result> &result) {
                    auto done = std::find_if(result.cbegin(),
                                             result.cend(),
                                             [](const SyntaxHighlighter::Result &res) {
                                                 return res.m_state == SyntaxHighlighter::State::Done;
                                             });
                    if (done != result.cend()) {
                        m_syntaxInfoUpdated = SyntaxHighlighter::State::Done;
                        emit highlightingFinished();
                        return;
                    }
                    m_syntaxInfoUpdated = SyntaxHighlighter::State::InProgress;
                });
    }
}

SyntaxHighlighterRunner::~SyntaxHighlighterRunner()
{
    if (m_thread) {
        m_thread->requestInterruption();
        m_thread->quit();
        m_thread->wait();
    } else {
        delete d->m_highlighter;
        delete d;
    }
}

void SyntaxHighlighterRunner::applyFormatRanges(const QList<SyntaxHighlighter::Result> &results)
{
    if (m_document == nullptr)
        return;

    for (const SyntaxHighlighter::Result &result : results) {
        m_syntaxInfoUpdated = result.m_state;
        if (m_syntaxInfoUpdated == SyntaxHighlighter::State::Done) {
            emit highlightingFinished();
            return;
        }

        QTextBlock docBlock = m_document->findBlock(result.m_blockNumber);
        if (!docBlock.isValid())
            return;

        result.copyToBlock(docBlock);

        if (result.m_formatRanges != docBlock.layout()->formats()) {
            TextDocumentLayout::FoldValidator foldValidator;
            foldValidator.setup(qobject_cast<TextDocumentLayout *>(m_document->documentLayout()));
            docBlock.layout()->setFormats(result.m_formatRanges);
            m_document->markContentsDirty(docBlock.position(), docBlock.length());
            foldValidator.process(docBlock);
        }
    }
}

void SyntaxHighlighterRunner::changeDocument(int from, int charsRemoved, int charsAdded)
{
    QTC_ASSERT(m_document, return);
    m_syntaxInfoUpdated = SyntaxHighlighter::State::InProgress;
    QMap<int, BlockPreeditData> blocksPreedit;
    QTextBlock block = m_document->findBlock(from);
    const QTextBlock endBlock = m_document->findBlock(from + charsAdded);
    while (block.isValid() && block != endBlock) {
        if (QTextLayout *layout = block.layout()) {
            if (const int pos = layout->preeditAreaPosition(); pos != -1)
                blocksPreedit[block.blockNumber()] = {pos, layout->preeditAreaText()};
        }
        block = block.next();
    }
    const QString text = Utils::Text::textAt(QTextCursor(m_document), from, charsAdded);
    QMetaObject::invokeMethod(d, [this, from, charsRemoved, text, blocksPreedit] {
        d->changeDocument(from, charsRemoved, text, blocksPreedit);
    });
}

bool SyntaxHighlighterRunner::useGenericHighlighter() const
{
    return m_useGenericHighlighter;
}

void SyntaxHighlighterRunner::setExtraFormats(
    const QMap<int, QList<QTextLayout::FormatRange>> &formatMap)
{
    QMetaObject::invokeMethod(d, [this, formatMap] { d->setExtraFormats(formatMap); });
}

void SyntaxHighlighterRunner::clearExtraFormats(const QList<int> &blockNumbers)
{
    QMetaObject::invokeMethod(d, [this, blockNumbers] { d->clearExtraFormats(blockNumbers); });
}

void SyntaxHighlighterRunner::clearAllExtraFormats()
{
    QMetaObject::invokeMethod(d, [this] { d->clearAllExtraFormats(); });
}

void SyntaxHighlighterRunner::setFontSettings(const TextEditor::FontSettings &fontSettings)
{
    QMetaObject::invokeMethod(d, [this, fontSettings] { d->setFontSettings(fontSettings); });
}

void SyntaxHighlighterRunner::setLanguageFeaturesFlags(unsigned int flags)
{
    QMetaObject::invokeMethod(d, [this, flags] { d->setLanguageFeaturesFlags(flags); });
}

void SyntaxHighlighterRunner::setEnabled(bool enabled)
{
    QMetaObject::invokeMethod(d, [this, enabled] { d->setEnabled(enabled); });
}

void SyntaxHighlighterRunner::rehighlight()
{
    QMetaObject::invokeMethod(d, [this] { d->rehighlight(); });
}

QString SyntaxHighlighterRunner::definitionName()
{
    return m_definitionName;
}

void SyntaxHighlighterRunner::setDefinitionName(const QString &name)
{
    if (name.isEmpty())
        return;

    m_definitionName = name;
    QMetaObject::invokeMethod(d, [this, name] { d->setDefinitionName(name); });
}

} // namespace TextEditor

#include "syntaxhighlighterrunner.moc"