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
|
/*
SPDX-FileCopyrightText: 2022-2025 Laurent Montel <montel@kde.org>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "autocorrectiontextedit.h"
using namespace Qt::Literals::StringLiterals;
#include <TextAutoCorrectionCore/AutoCorrection>
#include <QKeyEvent>
using namespace TextAutoCorrectionWidgets;
class TextAutoCorrectionWidgets::AutoCorrectionTextEditPrivate
{
public:
AutoCorrectionTextEditPrivate()
: mAutoCorrection(new TextAutoCorrectionCore::AutoCorrection())
{
}
~AutoCorrectionTextEditPrivate()
{
if (mNeedToDelete) {
delete mAutoCorrection;
}
}
TextAutoCorrectionCore::AutoCorrection *mAutoCorrection = nullptr;
bool mNeedToDelete = true;
};
AutoCorrectionTextEdit::AutoCorrectionTextEdit(QWidget *parent)
: QTextEdit(parent)
, d(new TextAutoCorrectionWidgets::AutoCorrectionTextEditPrivate)
{
}
AutoCorrectionTextEdit::~AutoCorrectionTextEdit() = default;
void AutoCorrectionTextEdit::setAutocorrection(TextAutoCorrectionCore::AutoCorrection *autocorrect)
{
d->mNeedToDelete = false;
delete d->mAutoCorrection;
d->mAutoCorrection = autocorrect;
}
TextAutoCorrectionCore::AutoCorrection *AutoCorrectionTextEdit::autocorrection() const
{
return d->mAutoCorrection;
}
void AutoCorrectionTextEdit::setAutocorrectionLanguage(const QString &language)
{
TextAutoCorrectionCore::AutoCorrectionSettings *settings = d->mAutoCorrection->autoCorrectionSettings();
settings->setLanguage(language);
d->mAutoCorrection->setAutoCorrectionSettings(settings);
}
static bool isSpecial(const QTextCharFormat &charFormat)
{
return charFormat.isFrameFormat() || charFormat.isImageFormat() || charFormat.isListFormat() || charFormat.isTableFormat()
|| charFormat.isTableCellFormat();
}
void AutoCorrectionTextEdit::keyPressEvent(QKeyEvent *e)
{
if (d->mAutoCorrection && d->mAutoCorrection->autoCorrectionSettings()->isEnabledAutoCorrection()) {
if ((e->key() == Qt::Key_Space) || (e->key() == Qt::Key_Enter) || (e->key() == Qt::Key_Return)) {
if (!textCursor().hasSelection()) {
const QTextCharFormat initialTextFormat = textCursor().charFormat();
const bool richText = acceptRichText();
int position = textCursor().position();
const bool addSpace = d->mAutoCorrection->autocorrect(richText, *document(), position);
QTextCursor cur = textCursor();
cur.setPosition(position);
const bool spacePressed = (e->key() == Qt::Key_Space);
const QChar insertChar = spacePressed ? u' ' : u'\n';
if (richText && !isSpecial(initialTextFormat)) {
if (addSpace || !spacePressed) {
cur.insertText(insertChar, initialTextFormat);
}
} else {
if (addSpace || !spacePressed) {
cur.insertText(insertChar);
}
}
setTextCursor(cur);
return;
}
}
}
QTextEdit::keyPressEvent(e);
}
#include "moc_autocorrectiontextedit.cpp"
|