configurationeditor.cpp 8.67 KB
Newer Older
1
/****************************************************************************
Lorenz Haas's avatar
Lorenz Haas committed
2
**
3 4
** Copyright (C) 2016 Lorenz Haas
** Contact: https://www.qt.io/licensing/
Lorenz Haas's avatar
Lorenz Haas committed
5 6 7 8 9 10 11
**
** This file is part of Qt Creator.
**
** 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
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
Lorenz Haas's avatar
Lorenz Haas committed
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
Lorenz Haas's avatar
Lorenz Haas committed
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
**
****************************************************************************/

#include "configurationeditor.h"

#include "abstractsettings.h"

#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>
#include <utils/qtcassert.h>

#include <QAbstractItemView>
#include <QCompleter>
#include <QScrollBar>
#include <QStringListModel>

namespace Beautifier {
namespace Internal {

ConfigurationSyntaxHighlighter::ConfigurationSyntaxHighlighter(QTextDocument *parent) :
    QSyntaxHighlighter(parent)
{
    const TextEditor::FontSettings fs = TextEditor::TextEditorSettings::instance()->fontSettings();
    m_formatKeyword = fs.toTextCharFormat(TextEditor::C_FIELD);
    m_formatComment = fs.toTextCharFormat(TextEditor::C_COMMENT);

49
    m_expressionComment.setPattern("#[^\\n]*");
Lorenz Haas's avatar
Lorenz Haas committed
50 51 52 53 54 55 56
}

void ConfigurationSyntaxHighlighter::setKeywords(const QStringList &keywords)
{
    if (keywords.isEmpty())
        return;

57
    // Check for empty keywords since they can cause an endless loop in highlightBlock().
Lorenz Haas's avatar
Lorenz Haas committed
58
    QStringList pattern;
59
    for (const QString &word : keywords) {
60
        if (!word.isEmpty())
Lorenz Haas's avatar
Lorenz Haas committed
61
            pattern << QRegularExpression::escape(word);
62
    }
Lorenz Haas's avatar
Lorenz Haas committed
63

64
    m_expressionKeyword.setPattern("(?:\\s|^)(" + pattern.join('|') + ")(?=\\s|\\:|\\=|\\,|$)");
Lorenz Haas's avatar
Lorenz Haas committed
65 66
}

Lorenz Haas's avatar
Lorenz Haas committed
67
void ConfigurationSyntaxHighlighter::setCommentExpression(const QRegularExpression &rx)
Lorenz Haas's avatar
Lorenz Haas committed
68 69 70 71 72 73
{
    m_expressionComment = rx;
}

void ConfigurationSyntaxHighlighter::highlightBlock(const QString &text)
{
Lorenz Haas's avatar
Lorenz Haas committed
74 75 76 77
    QRegularExpressionMatchIterator it = m_expressionKeyword.globalMatch(text);
    while (it.hasNext()) {
        const QRegularExpressionMatch match = it.next();
        setFormat(match.capturedStart(), match.capturedLength(), m_formatKeyword);
Lorenz Haas's avatar
Lorenz Haas committed
78 79
    }

Lorenz Haas's avatar
Lorenz Haas committed
80 81 82 83
    it = m_expressionComment.globalMatch(text);
    while (it.hasNext()) {
        const QRegularExpressionMatch match = it.next();
        setFormat(match.capturedStart(), match.capturedLength(), m_formatComment);
Lorenz Haas's avatar
Lorenz Haas committed
84 85 86
    }
}

87 88 89 90 91
ConfigurationEditor::ConfigurationEditor(QWidget *parent) :
    QPlainTextEdit(parent),
    m_completer(new QCompleter(this)),
    m_model(new QStringListModel(QStringList(), m_completer)),
    m_highlighter(new ConfigurationSyntaxHighlighter(document()))
Lorenz Haas's avatar
Lorenz Haas committed
92 93 94 95 96 97 98 99 100
{
    m_completer->setModel(m_model);
    m_completer->setModelSorting(QCompleter::CaseInsensitivelySortedModel);
    m_completer->setWrapAround(false);
    m_completer->setWidget(this);
    m_completer->setCompletionMode(QCompleter::PopupCompletion);
    m_completer->setCaseSensitivity(Qt::CaseInsensitive);
    m_completer->popup()->installEventFilter(this);

Montel Laurent's avatar
Montel Laurent committed
101 102 103 104
    connect(m_completer, static_cast<void (QCompleter::*)(const QString &)>(&QCompleter::activated),
            this, &ConfigurationEditor::insertCompleterText);
    connect(this, &ConfigurationEditor::cursorPositionChanged,
            this, &ConfigurationEditor::updateDocumentation);
Lorenz Haas's avatar
Lorenz Haas committed
105 106 107 108
}

void ConfigurationEditor::setSettings(AbstractSettings *settings)
{
109
    QTC_ASSERT(settings, return);
Lorenz Haas's avatar
Lorenz Haas committed
110 111 112 113 114 115 116 117 118
    m_settings = settings;

    QStringList keywords = m_settings->options();
    m_highlighter->setKeywords(keywords);
    keywords << m_settings->completerWords();
    keywords.sort(Qt::CaseInsensitive);
    m_model->setStringList(keywords);
}

Lorenz Haas's avatar
Lorenz Haas committed
119
void ConfigurationEditor::setCommentExpression(const QRegularExpression &rx)
Lorenz Haas's avatar
Lorenz Haas committed
120 121 122 123 124 125 126 127
{
    m_highlighter->setCommentExpression(rx);
}

// Workaround for handling "ESC" right when popup is shown.
bool ConfigurationEditor::eventFilter(QObject *object, QEvent *event)
{
    if (event->type() == QEvent::ShortcutOverride) {
128
        const QKeyEvent *key = static_cast<const QKeyEvent *>(event);
Lorenz Haas's avatar
Lorenz Haas committed
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
        if (key->key() == Qt::Key_Escape) {
            event->accept();
            m_completer->popup()->hide();
            return true;
        }
    }
    return QObject::eventFilter(object, event);
}

void ConfigurationEditor::keyPressEvent(QKeyEvent *event)
{
    const int key = event->key();

    if (key == Qt::Key_Escape) {
        event->ignore();
        return;
    }

    if (m_completer->popup()->isVisible()) {
        switch (key) {
        case Qt::Key_Backtab:
        case Qt::Key_Enter:
        case Qt::Key_Return:
        case Qt::Key_Tab:
            event->ignore();
            return;
        default:
            break;
        }
    }

Lorenz Haas's avatar
Lorenz Haas committed
160
    const bool isShortcut = (event->modifiers() & Qt::ControlModifier) && key == Qt::Key_Space;
Lorenz Haas's avatar
Lorenz Haas committed
161 162 163 164
    if (!isShortcut)
        QPlainTextEdit::keyPressEvent(event);

    const int cursorPosition = textCursor().position();
165
    const QTextCursor cursor = cursorForTextUnderCursor();
Lorenz Haas's avatar
Lorenz Haas committed
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
    const QString prefix = cursor.selectedText();

    if (!isShortcut && (prefix.length() < 2 || cursorPosition != cursor.position())) {
        m_completer->popup()->hide();
        return;
    }

    if (prefix != m_completer->completionPrefix()) {
        m_completer->setCompletionPrefix(prefix);
        m_completer->popup()->setCurrentIndex(m_completer->completionModel()->index(0, 0));
    }

    if (m_completer->completionCount() == 1 && prefix == m_completer->currentCompletion()) {
        m_completer->popup()->hide();
        return;
    }

    QRect popupRect = cursorRect();
    popupRect.setWidth(m_completer->popup()->sizeHintForColumn(0)
                       + m_completer->popup()->verticalScrollBar()->sizeHint().width());
    m_completer->complete(popupRect);
}

// Hack because '-' and '=' are treated as End/StartOfWord
QTextCursor ConfigurationEditor::cursorForTextUnderCursor(QTextCursor tc) const
{
    if (tc.isNull())
        tc = textCursor();

    tc.movePosition(QTextCursor::StartOfWord, QTextCursor::MoveAnchor);
    QChar ch = document()->characterAt(tc.position() - 1);
197
    while (!(ch.isNull() || ch.isSpace() || ch == ':' || ch == ',')) {
Lorenz Haas's avatar
Lorenz Haas committed
198 199 200 201 202
        tc.movePosition(QTextCursor::PreviousCharacter, QTextCursor::MoveAnchor);
        ch = document()->characterAt(tc.position() - 1);
    }
    tc.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
    ch = document()->characterAt(tc.position());
203
    while (!(ch.isNull() || ch.isSpace() || ch == ':' || ch == ',')) {
Lorenz Haas's avatar
Lorenz Haas committed
204 205 206 207 208 209 210 211
        tc.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
        ch = document()->characterAt(tc.position());
    }
    return tc;
}

void ConfigurationEditor::insertCompleterText(const QString &text)
{
Lorenz Haas's avatar
Lorenz Haas committed
212 213 214 215 216 217
    QTextCursor tc = textCursor();
    // Replace entire word to get case sensitivity right.
    tc.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor,
                    m_completer->completionPrefix().length());
    tc.insertText(text);
    setTextCursor(tc);
Lorenz Haas's avatar
Lorenz Haas committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
}

void ConfigurationEditor::updateDocumentation()
{
    QTC_CHECK(m_settings);
    QTextCursor cursor = textCursor();

    QString word = cursorForTextUnderCursor(cursor).selectedText();
    if (word == m_lastDocumentation)
        return;

    QString doc = m_settings->documentation(word);
    if (!doc.isEmpty()) {
        m_lastDocumentation = word;
        emit documentationChanged(word, doc);
        return;
    }

    // If the documentation was empty, then try to use the line's first word or the first word
    // in front of a colon for providing a documentation.
    cursor.movePosition(QTextCursor::PreviousWord);
    cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
240
    const int pos = cursor.selectedText().lastIndexOf(',');
Lorenz Haas's avatar
Lorenz Haas committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    if (-1 != pos) {
        cursor.setPosition(cursor.position() + pos);
        cursor.movePosition(QTextCursor::NextWord);
    }
    word = cursorForTextUnderCursor(cursor).selectedText();

    if (word == m_lastDocumentation)
        return;

    doc = m_settings->documentation(word);
    if (doc.isEmpty())
        return;

    m_lastDocumentation = word;
    emit documentationChanged(word, doc);
}

} // namespace Internal
} // namespace Beautifier