plaintexteditor.cpp 29.1 KB
Newer Older
1
/*
Laurent Montel's avatar
Laurent Montel committed
2
   Copyright (C) 2013-2019 Laurent Montel <montel@kde.org>
3

Laurent Montel's avatar
Laurent Montel committed
4
5
6
7
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.
8

Laurent Montel's avatar
Laurent Montel committed
9
10
11
12
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.
13

Laurent Montel's avatar
Laurent Montel committed
14
15
16
17
   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
18
19
*/
#include "plaintexteditor.h"
Laurent Montel's avatar
Laurent Montel committed
20
#include "kpimtextedit_debug.h"
21

22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include "texteditor/commonwidget/textmessageindicator.h"
#include <KIO/KUriFilterSearchProviderActions>
#include <KLocalizedString>
#include <KStandardGuiItem>
#include <KStandardAction>
#include <KCursor>
#include <QIcon>
#include <KConfigGroup>
#include <KSharedConfig>
#include <KConfig>

#include <sonnet/backgroundchecker.h>
#include <Sonnet/Dialog>
#include "texttospeech/texttospeech.h"
Laurent Montel's avatar
Laurent Montel committed
36
#include <sonnet_version.h>
37
38
39
40
41
42
43
44

#include <QMenu>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QTextDocumentFragment>
#include <QScrollBar>
#include <QApplication>
#include <QClipboard>
45
#include <QShortcut>
46
47
48
49
50
51
52
53
54
55
56
57
58

#include <sonnet/spellcheckdecorator.h>

#include <SonnetCore/sonnet/speller.h>

#include <Sonnet/Highlighter>

using namespace KPIMTextEdit;

class Q_DECL_HIDDEN PlainTextEditor::PlainTextEditorPrivate
{
public:
    PlainTextEditorPrivate(PlainTextEditor *qq)
Laurent Montel's avatar
Laurent Montel committed
59
60
61
        : q(qq)
        , mTextIndicator(new KPIMTextEdit::TextMessageIndicator(q))
        , webshortcutMenuManager(new KIO::KUriFilterSearchProviderActions(q))
62
63
64
65
66
67
68
69
70
    {
        KConfig sonnetKConfig(QStringLiteral("sonnetrc"));
        KConfigGroup group(&sonnetKConfig, "Spelling");
        checkSpellingEnabled = group.readEntry("checkerEnabledByDefault", false);
        supportFeatures |= PlainTextEditor::Search;
        supportFeatures |= PlainTextEditor::SpellChecking;
        supportFeatures |= PlainTextEditor::TextToSpeech;
        supportFeatures |= PlainTextEditor::AllowWebShortcut;
    }
Laurent Montel's avatar
Laurent Montel committed
71

72
73
74
75
76
77
78
79
    ~PlainTextEditorPrivate()
    {
        delete richTextDecorator;
        delete speller;
    }

    QStringList ignoreSpellCheckingWords;
    PlainTextEditor *q;
Laurent Montel's avatar
Laurent Montel committed
80
81
82
83
    KPIMTextEdit::TextMessageIndicator *mTextIndicator = nullptr;
    KIO::KUriFilterSearchProviderActions *webshortcutMenuManager = nullptr;
    Sonnet::SpellCheckDecorator *richTextDecorator = nullptr;
    Sonnet::Speller *speller = nullptr;
84
85
86
87
88

    QString spellCheckingConfigFileName;
    QString spellCheckingLanguage;
    QTextDocumentFragment originalDoc;
    PlainTextEditor::SupportFeatures supportFeatures;
Laurent Montel's avatar
Laurent Montel committed
89
    int mInitialFontSize = 0;
Laurent Montel's avatar
Laurent Montel committed
90
91
92
    bool customPalette = false;
    bool activateLanguageMenu = true;
    bool checkSpellingEnabled = false;
93
94
95
};

PlainTextEditor::PlainTextEditor(QWidget *parent)
Laurent Montel's avatar
Laurent Montel committed
96
97
    : QPlainTextEdit(parent)
    , d(new PlainTextEditor::PlainTextEditorPrivate(this))
98
99
100
{
    KCursor::setAutoHideCursor(this, true, false);
    setSpellCheckingConfigFileName(QString());
Laurent Montel's avatar
Laurent Montel committed
101
    d->mInitialFontSize = font().pointSize();
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
}

PlainTextEditor::~PlainTextEditor()
{
    delete d;
}

void PlainTextEditor::addIgnoreWords(const QStringList &lst)
{
    d->ignoreSpellCheckingWords = lst;
    addIgnoreWordsToHighLighter();
}

void PlainTextEditor::slotDisplayMessageIndicator(const QString &message)
{
    d->mTextIndicator->display(message);
}

void PlainTextEditor::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu *popup = createStandardContextMenu();
    if (popup) {
        const bool emptyDocument = document()->isEmpty();
        if (!isReadOnly()) {
            QList<QAction *> actionList = popup->actions();
Laurent Montel's avatar
Laurent Montel committed
127
128
129
            enum {
                UndoAct, RedoAct, CutAct, CopyAct, PasteAct, ClearAct, SelectAllAct, NCountActs
            };
Laurent Montel's avatar
Laurent Montel committed
130
            QAction *separatorAction = nullptr;
131
132
133
134
135
            const int idx = actionList.indexOf(actionList[SelectAllAct]) + 1;
            if (idx < actionList.count()) {
                separatorAction = actionList.at(idx);
            }
            if (separatorAction) {
136
137
138
                if (!emptyDocument) {
                    QAction *clearAllAction = KStandardAction::clear(this, &PlainTextEditor::slotUndoableClear, popup);
                    popup->insertAction(separatorAction, clearAllAction);
139
140
141
142
143
                }
            }
        }
        if (d->supportFeatures & Search) {
            popup->addSeparator();
144
            if (!emptyDocument) {
Laurent Montel's avatar
Laurent Montel committed
145
                popup->addAction(KStandardGuiItem::find().icon(), KStandardGuiItem::find().text(), this, &PlainTextEditor::findText, Qt::Key_F + Qt::CTRL);
146
                popup->addSeparator();
147
148
            }
            if (!isReadOnly()) {
149
                if (!emptyDocument) {
Laurent Montel's avatar
Laurent Montel committed
150
                    popup->addAction(i18n("Replace..."), this, &PlainTextEditor::replaceText, Qt::Key_R + Qt::CTRL);
151
                    popup->addSeparator();
152
153
154
155
156
157
158
                }
            }
        } else {
            popup->addSeparator();
        }

        if (!isReadOnly() && spellCheckingSupport()) {
159
160
            if (!d->speller) {
                d->speller = new Sonnet::Speller();
161
            }
162
            if (!d->speller->availableBackends().isEmpty()) {
163
                if (!emptyDocument) {
Laurent Montel's avatar
Laurent Montel committed
164
                    popup->addAction(QIcon::fromTheme(QStringLiteral("tools-check-spelling")), i18n("Check Spelling..."), this, &PlainTextEditor::slotCheckSpelling);
165
                    popup->addSeparator();
166
                }
Laurent Montel's avatar
Laurent Montel committed
167
                QAction *autoSpellCheckAction = popup->addAction(i18n("Auto Spell Check"), this, &PlainTextEditor::slotToggleAutoSpellCheck);
168
169
170
171
                autoSpellCheckAction->setCheckable(true);
                autoSpellCheckAction->setChecked(checkSpellingEnabled());
                popup->addAction(autoSpellCheckAction);

Laurent Montel's avatar
Laurent Montel committed
172
                if (checkSpellingEnabled() && d->activateLanguageMenu) {
173
174
175
176
                    QMenu *languagesMenu = new QMenu(i18n("Spell Checking Language"), popup);
                    QActionGroup *languagesGroup = new QActionGroup(languagesMenu);
                    languagesGroup->setExclusive(true);

Laurent Montel's avatar
Laurent Montel committed
177
178
                    QString defaultSpellcheckingLanguage = spellCheckingLanguage();
                    if (defaultSpellcheckingLanguage.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
179
                        //TODO fix default value
Laurent Montel's avatar
Laurent Montel committed
180
181
                        defaultSpellcheckingLanguage = d->speller->defaultLanguage();
                    }
Laurent Montel's avatar
Laurent Montel committed
182
183

                    QMapIterator<QString, QString> i(d->speller->availableDictionaries());
Laurent Montel's avatar
Laurent Montel committed
184
                    while (i.hasNext()) {
Laurent Montel's avatar
Laurent Montel committed
185
                        i.next();
186
187
                        QAction *languageAction = languagesMenu->addAction(i.key());
                        languageAction->setCheckable(true);
Laurent Montel's avatar
Laurent Montel committed
188
                        languageAction->setChecked(defaultSpellcheckingLanguage == i.value());
189
190
191
192
193
                        languageAction->setData(i.value());
                        languageAction->setActionGroup(languagesGroup);
                        connect(languageAction, &QAction::triggered, this, &PlainTextEditor::slotLanguageSelected);
                    }
                    popup->addMenu(languagesMenu);
194
                }
195
                popup->addSeparator();
196
197
198
199
            }
        }
        if (d->supportFeatures & TextToSpeech) {
            if (KPIMTextEdit::TextToSpeech::self()->isReady()) {
200
201
202
203
204
                if (!emptyDocument) {
                    QAction *speakAction = popup->addAction(i18n("Speak Text"));
                    speakAction->setIcon(QIcon::fromTheme(QStringLiteral("preferences-desktop-text-to-speech")));
                    connect(speakAction, &QAction::triggered, this, &PlainTextEditor::slotSpeakText);
                }
205
206
207
208
209
210
211
212
            }
        }
        if (webShortcutSupport() && textCursor().hasSelection()) {
            popup->addSeparator();
            const QString selectedText = textCursor().selectedText();
            d->webshortcutMenuManager->setSelectedText(selectedText);
            d->webshortcutMenuManager->addWebShortcutsToMenu(popup);
        }
Laurent Montel's avatar
Laurent Montel committed
213

214
215
216
217
218
219
220
        addExtraMenuEntry(popup, event->pos());
        popup->exec(event->globalPos());

        delete popup;
    }
}

221
void PlainTextEditor::addExtraMenuEntry(QMenu *menu, QPoint pos)
222
223
224
225
226
227
228
229
230
231
232
233
234
{
    Q_UNUSED(menu);
    Q_UNUSED(pos);
}

void PlainTextEditor::slotSpeakText()
{
    QString text;
    if (textCursor().hasSelection()) {
        text = textCursor().selectedText();
    } else {
        text = toPlainText();
    }
Laurent Montel's avatar
Laurent Montel committed
235
    //qCDebug(KPIMTEXTEDIT_LOG) << " KPIMTextEdit::TextToSpeech::self()->isReady() :" << KPIMTextEdit::TextToSpeech::self()->isReady();
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
    Q_EMIT say(text);
}

void PlainTextEditor::slotUndoableClear()
{
    QTextCursor cursor = textCursor();
    cursor.beginEditBlock();
    cursor.movePosition(QTextCursor::Start);
    cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
    cursor.removeSelectedText();
    cursor.endEditBlock();
}

void PlainTextEditor::setSearchSupport(bool b)
{
    if (b) {
        d->supportFeatures |= Search;
    } else {
Laurent Montel's avatar
Laurent Montel committed
254
        d->supportFeatures = (d->supportFeatures & ~Search);
255
256
257
258
259
    }
}

bool PlainTextEditor::searchSupport() const
{
Laurent Montel's avatar
Laurent Montel committed
260
    return d->supportFeatures & Search;
261
262
263
264
265
266
267
}

void PlainTextEditor::setTextToSpeechSupport(bool b)
{
    if (b) {
        d->supportFeatures |= TextToSpeech;
    } else {
Laurent Montel's avatar
Laurent Montel committed
268
        d->supportFeatures = (d->supportFeatures & ~TextToSpeech);
269
270
271
272
273
    }
}

bool PlainTextEditor::textToSpeechSupport() const
{
Laurent Montel's avatar
Laurent Montel committed
274
    return d->supportFeatures & TextToSpeech;
275
276
277
278
}

bool PlainTextEditor::spellCheckingSupport() const
{
Laurent Montel's avatar
Laurent Montel committed
279
    return d->supportFeatures & SpellChecking;
280
281
282
283
284
285
286
}

void PlainTextEditor::setSpellCheckingSupport(bool check)
{
    if (check) {
        d->supportFeatures |= SpellChecking;
    } else {
Laurent Montel's avatar
Laurent Montel committed
287
        d->supportFeatures = (d->supportFeatures & ~SpellChecking);
288
289
290
291
292
293
294
295
    }
}

void PlainTextEditor::setWebShortcutSupport(bool b)
{
    if (b) {
        d->supportFeatures |= AllowWebShortcut;
    } else {
Laurent Montel's avatar
Laurent Montel committed
296
        d->supportFeatures = (d->supportFeatures & ~AllowWebShortcut);
297
298
299
300
301
    }
}

bool PlainTextEditor::webShortcutSupport() const
{
Laurent Montel's avatar
Laurent Montel committed
302
    return d->supportFeatures & AllowWebShortcut;
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
}

void PlainTextEditor::setReadOnly(bool readOnly)
{
    if (!readOnly && hasFocus() && d->checkSpellingEnabled && !d->richTextDecorator) {
        createHighlighter();
    }

    if (readOnly == isReadOnly()) {
        return;
    }

    if (readOnly) {
        clearDecorator();

        d->customPalette = testAttribute(Qt::WA_SetPalette);
        QPalette p = palette();
320
        QColor color = p.color(QPalette::Disabled, QPalette::Window);
321
        p.setColor(QPalette::Base, color);
322
        p.setColor(QPalette::Window, color);
323
324
325
326
327
328
        setPalette(p);
    } else {
        if (d->customPalette && testAttribute(Qt::WA_SetPalette)) {
            QPalette p = palette();
            QColor color = p.color(QPalette::Normal, QPalette::Base);
            p.setColor(QPalette::Base, color);
329
            p.setColor(QPalette::Window, color);
330
331
332
333
334
335
336
337
338
339
340
341
            setPalette(p);
        } else {
            setPalette(QPalette());
        }
    }

    QPlainTextEdit::setReadOnly(readOnly);
}

void PlainTextEditor::slotCheckSpelling()
{
    if (document()->isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
342
        slotDisplayMessageIndicator(i18n("Nothing to spell check."));
343
344
345
        return;
    }
    Sonnet::BackgroundChecker *backgroundSpellCheck = new Sonnet::BackgroundChecker;
346
347
348
349
350
    if (backgroundSpellCheck->speller().availableBackends().isEmpty()) {
        slotDisplayMessageIndicator(i18n("No backend available for spell checking."));
        delete backgroundSpellCheck;
        return;
    }
351
352
353
354
    if (!d->spellCheckingLanguage.isEmpty()) {
        backgroundSpellCheck->changeLanguage(d->spellCheckingLanguage);
    }
    if (!d->ignoreSpellCheckingWords.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
355
        for (const QString &word : qAsConst(d->ignoreSpellCheckingWords)) {
356
357
358
            backgroundSpellCheck->speller().addToSession(word);
        }
    }
Laurent Montel's avatar
Laurent Montel committed
359
    Sonnet::Dialog *spellDialog = new Sonnet::Dialog(backgroundSpellCheck, nullptr);
360
361
362
363
364
    backgroundSpellCheck->setParent(spellDialog);
    spellDialog->setAttribute(Qt::WA_DeleteOnClose, true);
    connect(spellDialog, &Sonnet::Dialog::replace, this, &PlainTextEditor::slotSpellCheckerCorrected);
    connect(spellDialog, &Sonnet::Dialog::misspelling, this, &PlainTextEditor::slotSpellCheckerMisspelling);
    connect(spellDialog, &Sonnet::Dialog::autoCorrect, this, &PlainTextEditor::slotSpellCheckerAutoCorrect);
Laurent Montel's avatar
Laurent Montel committed
365
#if SONNET_VERSION < QT_VERSION_CHECK(5, 65, 0)
366
    connect(spellDialog, QOverload<const QString &>::of(&Sonnet::Dialog::done),
Laurent Montel's avatar
Laurent Montel committed
367
            this, &PlainTextEditor::slotSpellCheckerFinished);
Laurent Montel's avatar
Laurent Montel committed
368
369
370
#else
    connect(spellDialog, &Sonnet::Dialog::spellCheckDone, this, &PlainTextEditor::slotSpellCheckerFinished);
#endif
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
    connect(spellDialog, &Sonnet::Dialog::cancel, this, &PlainTextEditor::slotSpellCheckerCanceled);
    connect(spellDialog, &Sonnet::Dialog::spellCheckStatus, this, &PlainTextEditor::spellCheckStatus);
    connect(spellDialog, &Sonnet::Dialog::languageChanged, this, &PlainTextEditor::languageChanged);
    d->originalDoc = QTextDocumentFragment(document());
    spellDialog->setBuffer(toPlainText());
    spellDialog->show();
}

void PlainTextEditor::slotSpellCheckerCanceled()
{
    QTextDocument *doc = document();
    doc->clear();
    QTextCursor cursor(doc);
    cursor.insertFragment(d->originalDoc);
    slotSpellCheckerFinished();
}

void PlainTextEditor::slotSpellCheckerAutoCorrect(const QString &currentWord, const QString &autoCorrectWord)
{
    Q_EMIT spellCheckerAutoCorrect(currentWord, autoCorrectWord);
}

void PlainTextEditor::slotSpellCheckerMisspelling(const QString &text, int pos)
{
    highlightWord(text.length(), pos);
}

void PlainTextEditor::slotSpellCheckerCorrected(const QString &oldWord, int pos, const QString &newWord)
{
    if (oldWord != newWord) {
        QTextCursor cursor(document());
        cursor.setPosition(pos);
        cursor.setPosition(pos + oldWord.length(), QTextCursor::KeepAnchor);
        cursor.insertText(newWord);
    }
}

void PlainTextEditor::slotSpellCheckerFinished()
{
    QTextCursor cursor(document());
    cursor.clearSelection();
    setTextCursor(cursor);
}

void PlainTextEditor::highlightWord(int length, int pos)
{
    QTextCursor cursor(document());
    cursor.setPosition(pos);
    cursor.setPosition(pos + length, QTextCursor::KeepAnchor);
    setTextCursor(cursor);
    ensureCursorVisible();
}

static void deleteWord(QTextCursor cursor, QTextCursor::MoveOperation op)
{
    cursor.clearSelection();
    cursor.movePosition(op, QTextCursor::KeepAnchor);
    cursor.removeSelectedText();
}

void PlainTextEditor::deleteWordBack()
{
    deleteWord(textCursor(), QTextCursor::PreviousWord);
}

void PlainTextEditor::deleteWordForward()
{
    deleteWord(textCursor(), QTextCursor::WordRight);
}

bool PlainTextEditor::event(QEvent *ev)
{
    if (ev->type() == QEvent::ShortcutOverride) {
        QKeyEvent *e = static_cast<QKeyEvent *>(ev);
        if (overrideShortcut(e)) {
            e->accept();
            return true;
        }
    }
    return QPlainTextEdit::event(ev);
}

453
bool PlainTextEditor::overrideShortcut(QKeyEvent *event)
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
{
    const int key = event->key() | event->modifiers();
    if (KStandardShortcut::copy().contains(key)) {
        return true;
    } else if (KStandardShortcut::paste().contains(key)) {
        return true;
    } else if (KStandardShortcut::cut().contains(key)) {
        return true;
    } else if (KStandardShortcut::undo().contains(key)) {
        return true;
    } else if (KStandardShortcut::redo().contains(key)) {
        return true;
    } else if (KStandardShortcut::deleteWordBack().contains(key)) {
        return true;
    } else if (KStandardShortcut::deleteWordForward().contains(key)) {
        return true;
    } else if (KStandardShortcut::backwardWord().contains(key)) {
        return true;
    } else if (KStandardShortcut::forwardWord().contains(key)) {
        return true;
    } else if (KStandardShortcut::next().contains(key)) {
        return true;
    } else if (KStandardShortcut::prior().contains(key)) {
        return true;
    } else if (KStandardShortcut::begin().contains(key)) {
        return true;
    } else if (KStandardShortcut::end().contains(key)) {
        return true;
    } else if (KStandardShortcut::beginningOfLine().contains(key)) {
        return true;
    } else if (KStandardShortcut::endOfLine().contains(key)) {
        return true;
    } else if (KStandardShortcut::pasteSelection().contains(key)) {
        return true;
    } else if (searchSupport() && KStandardShortcut::find().contains(key)) {
        return true;
    } else if (searchSupport() && KStandardShortcut::replace().contains(key)) {
        return true;
    } else if (searchSupport() && KStandardShortcut::findNext().contains(key)) {
        return true;
    } else if (event->matches(QKeySequence::SelectAll)) { // currently missing in QTextEdit
        return true;
496
497
    } else if (event == QKeySequence::DeleteEndOfLine) {
        return true;
498
499
500
501
    }
    return false;
}

502
bool PlainTextEditor::handleShortcut(QKeyEvent *event)
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
{
    const int key = event->key() | event->modifiers();

    if (KStandardShortcut::copy().contains(key)) {
        copy();
        return true;
    } else if (KStandardShortcut::paste().contains(key)) {
        paste();
        return true;
    } else if (KStandardShortcut::cut().contains(key)) {
        cut();
        return true;
    } else if (KStandardShortcut::undo().contains(key)) {
        if (!isReadOnly()) {
            undo();
        }
        return true;
    } else if (KStandardShortcut::redo().contains(key)) {
        if (!isReadOnly()) {
            redo();
        }
        return true;
    } else if (KStandardShortcut::deleteWordBack().contains(key)) {
        if (!isReadOnly()) {
            deleteWordBack();
        }
        return true;
    } else if (KStandardShortcut::deleteWordForward().contains(key)) {
        if (!isReadOnly()) {
            deleteWordForward();
        }
        return true;
    } else if (KStandardShortcut::backwardWord().contains(key)) {
        QTextCursor cursor = textCursor();
        cursor.movePosition(QTextCursor::PreviousWord);
        setTextCursor(cursor);
        return true;
    } else if (KStandardShortcut::forwardWord().contains(key)) {
        QTextCursor cursor = textCursor();
        cursor.movePosition(QTextCursor::NextWord);
        setTextCursor(cursor);
        return true;
    } else if (KStandardShortcut::next().contains(key)) {
        QTextCursor cursor = textCursor();
        bool moved = false;
        qreal lastY = cursorRect(cursor).bottom();
        qreal distance = 0;
        do {
            qreal y = cursorRect(cursor).bottom();
            distance += qAbs(y - lastY);
            lastY = y;
            moved = cursor.movePosition(QTextCursor::Down);
        } while (moved && distance < viewport()->height());

        if (moved) {
            cursor.movePosition(QTextCursor::Up);
            verticalScrollBar()->triggerAction(QAbstractSlider::SliderPageStepAdd);
        }
        setTextCursor(cursor);
        return true;
    } else if (KStandardShortcut::prior().contains(key)) {
        QTextCursor cursor = textCursor();
        bool moved = false;
        qreal lastY = cursorRect(cursor).bottom();
        qreal distance = 0;
        do {
            qreal y = cursorRect(cursor).bottom();
            distance += qAbs(y - lastY);
            lastY = y;
            moved = cursor.movePosition(QTextCursor::Up);
        } while (moved && distance < viewport()->height());

        if (moved) {
            cursor.movePosition(QTextCursor::Down);
            verticalScrollBar()->triggerAction(QAbstractSlider::SliderPageStepSub);
        }
        setTextCursor(cursor);
        return true;
    } else if (KStandardShortcut::begin().contains(key)) {
        QTextCursor cursor = textCursor();
        cursor.movePosition(QTextCursor::Start);
        setTextCursor(cursor);
        return true;
    } else if (KStandardShortcut::end().contains(key)) {
        QTextCursor cursor = textCursor();
        cursor.movePosition(QTextCursor::End);
        setTextCursor(cursor);
        return true;
    } else if (KStandardShortcut::beginningOfLine().contains(key)) {
        QTextCursor cursor = textCursor();
        cursor.movePosition(QTextCursor::StartOfLine);
        setTextCursor(cursor);
        return true;
    } else if (KStandardShortcut::endOfLine().contains(key)) {
        QTextCursor cursor = textCursor();
        cursor.movePosition(QTextCursor::EndOfLine);
        setTextCursor(cursor);
        return true;
    } else if (searchSupport() && KStandardShortcut::find().contains(key)) {
        Q_EMIT findText();
        return true;
    } else if (searchSupport() && KStandardShortcut::replace().contains(key)) {
        if (!isReadOnly()) {
            Q_EMIT replaceText();
        }
        return true;
    } else if (KStandardShortcut::pasteSelection().contains(key)) {
        QString text = QApplication::clipboard()->text(QClipboard::Selection);
        if (!text.isEmpty()) {
            insertPlainText(text);    // TODO: check if this is html? (MiB)
        }
        return true;
615
    } else if (event == QKeySequence::DeleteEndOfLine) {
616
        deleteEndOfLine();
617
        return true;
618
619
620
621
    }
    return false;
}

622
623
624
625
626
627
628
629
630
631
632
633
634
void PlainTextEditor::deleteEndOfLine()
{
    QTextCursor cursor = textCursor();
    QTextBlock block = cursor.block();
    if (cursor.position() == block.position() + block.length() - 2) {
        cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
    } else {
        cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
    }
    cursor.removeSelectedText();
    setTextCursor(cursor);
}

Laurent Montel's avatar
Laurent Montel committed
635
void PlainTextEditor::moveLineUpDown(bool moveUp)
636
637
{
    QTextCursor cursor = textCursor();
Laurent Montel's avatar
Laurent Montel committed
638
639
640
641
642
643
644
645
646
    QTextCursor move = cursor;
    move.beginEditBlock();

    bool hasSelection = cursor.hasSelection();

    if (hasSelection) {
        move.setPosition(cursor.selectionStart());
        move.movePosition(QTextCursor::StartOfBlock);
        move.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor);
Laurent Montel's avatar
Laurent Montel committed
647
        move.movePosition(move.atBlockStart() ? QTextCursor::Left : QTextCursor::EndOfBlock,
Laurent Montel's avatar
Laurent Montel committed
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
                          QTextCursor::KeepAnchor);
    } else {
        move.movePosition(QTextCursor::StartOfBlock);
        move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
    }
    QString text = move.selectedText();

    move.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
    move.removeSelectedText();

    if (moveUp) {
        move.movePosition(QTextCursor::PreviousBlock);
        move.insertBlock();
        move.movePosition(QTextCursor::Left);
    } else {
        move.movePosition(QTextCursor::EndOfBlock);
        if (move.atBlockStart()) { // empty block
            move.movePosition(QTextCursor::NextBlock);
            move.insertBlock();
            move.movePosition(QTextCursor::Left);
        } else {
            move.insertBlock();
        }
    }

    int start = move.position();
    move.clearSelection();
    move.insertText(text);
    int end = move.position();

    if (hasSelection) {
        move.setPosition(end);
        move.setPosition(start, QTextCursor::KeepAnchor);
    } else {
        move.setPosition(start);
    }
    move.endEditBlock();

    setTextCursor(move);
687
688
}

689
690
691
void PlainTextEditor::wheelEvent(QWheelEvent *event)
{
    if (QApplication::keyboardModifiers() & Qt::ControlModifier) {
692
        if (event->angleDelta().y() > 0) {
693
            zoomIn();
694
        } else if (event->angleDelta().y() < 0) {
695
696
697
            zoomOut();
        }
        event->accept();
698
        return;
699
    }
700
    QPlainTextEdit::wheelEvent(event);
701
702
}

703
704
void PlainTextEditor::keyPressEvent(QKeyEvent *event)
{
Laurent Montel's avatar
Laurent Montel committed
705
706
    const bool isControlClicked = event->modifiers() & Qt::ControlModifier;
    const bool isShiftClicked = event->modifiers() & Qt::ShiftModifier;
707
708
    if (handleShortcut(event)) {
        event->accept();
Laurent Montel's avatar
Laurent Montel committed
709
    } else if (event->key() == Qt::Key_Up && isControlClicked && isShiftClicked) {
Laurent Montel's avatar
Laurent Montel committed
710
711
        moveLineUpDown(true);
        event->accept();
Laurent Montel's avatar
Laurent Montel committed
712
    } else if (event->key() == Qt::Key_Down && isControlClicked && isShiftClicked) {
Laurent Montel's avatar
Laurent Montel committed
713
714
        moveLineUpDown(false);
        event->accept();
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
    } else {
        QPlainTextEdit::keyPressEvent(event);
    }
}

bool PlainTextEditor::activateLanguageMenu() const
{
    return d->activateLanguageMenu;
}

void PlainTextEditor::setActivateLanguageMenu(bool activate)
{
    d->activateLanguageMenu = activate;
}

Sonnet::Highlighter *PlainTextEditor::highlighter() const
{
    if (d->richTextDecorator) {
        return d->richTextDecorator->highlighter();
    } else {
Laurent Montel's avatar
Laurent Montel committed
735
        return nullptr;
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
    }
}

Sonnet::SpellCheckDecorator *PlainTextEditor::createSpellCheckDecorator()
{
    return new Sonnet::SpellCheckDecorator(this);
}

void PlainTextEditor::addIgnoreWordsToHighLighter()
{
    if (d->ignoreSpellCheckingWords.isEmpty()) {
        return;
    }
    if (d->richTextDecorator) {
        Sonnet::Highlighter *_highlighter = d->richTextDecorator->highlighter();
Laurent Montel's avatar
Laurent Montel committed
751
        for (const QString &word : qAsConst(d->ignoreSpellCheckingWords)) {
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
            _highlighter->ignoreWord(word);
        }
    }
}

void PlainTextEditor::setHighlighter(Sonnet::Highlighter *_highLighter)
{
    Sonnet::SpellCheckDecorator *decorator = createSpellCheckDecorator();
    delete decorator->highlighter();
    decorator->setHighlighter(_highLighter);

    //KTextEdit used to take ownership of the highlighter, Sonnet::SpellCheckDecorator does not.
    //so we reparent the highlighter so it will be deleted when the decorator is destroyed
    _highLighter->setParent(decorator);
    d->richTextDecorator = decorator;
    addIgnoreWordsToHighLighter();
}

void PlainTextEditor::focusInEvent(QFocusEvent *event)
{
    if (checkSpellingEnabled() && !isReadOnly() && !d->richTextDecorator && spellCheckingSupport()) {
        createHighlighter();
    }

    QPlainTextEdit::focusInEvent(event);
}

bool PlainTextEditor::checkSpellingEnabled() const
{
    return d->checkSpellingEnabled;
}

void PlainTextEditor::setCheckSpellingEnabled(bool check)
{
    if (check == d->checkSpellingEnabled) {
        return;
    }
    d->checkSpellingEnabled = check;
    Q_EMIT checkSpellingChanged(check);
791
    // From the above statement we know that if we're turning checking
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
    // on that we need to create a new highlighter and if we're turning it
    // off we should remove the old one.
    if (check) {
        if (hasFocus()) {
            if (!d->richTextDecorator) {
                createHighlighter();
            }
            if (!d->spellCheckingLanguage.isEmpty()) {
                setSpellCheckingLanguage(spellCheckingLanguage());
            }
        }
    } else {
        clearDecorator();
    }
    updateHighLighter();
}

void PlainTextEditor::updateHighLighter()
{
}

void PlainTextEditor::clearDecorator()
{
    delete d->richTextDecorator;
Laurent Montel's avatar
Laurent Montel committed
816
    d->richTextDecorator = nullptr;
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
}

void PlainTextEditor::createHighlighter()
{
    Sonnet::Highlighter *highlighter = new Sonnet::Highlighter(this);
    highlighter->setCurrentLanguage(spellCheckingLanguage());
    setHighlighter(highlighter);
}

void PlainTextEditor::setSpellCheckingConfigFileName(const QString &_fileName)
{
    d->spellCheckingConfigFileName = _fileName;
    KSharedConfig::Ptr config = KSharedConfig::openConfig(d->spellCheckingConfigFileName);
    if (config->hasGroup("Spelling")) {
        KConfigGroup group(config, "Spelling");
        d->checkSpellingEnabled = group.readEntry("checkerEnabledByDefault", false);
        d->spellCheckingLanguage = group.readEntry("Language", QString());
    }
    setCheckSpellingEnabled(checkSpellingEnabled());

    if (!d->spellCheckingLanguage.isEmpty() && highlighter()) {
        highlighter()->setCurrentLanguage(d->spellCheckingLanguage);
        highlighter()->rehighlight();
    }
}

QString PlainTextEditor::spellCheckingConfigFileName() const
{
    return d->spellCheckingConfigFileName;
}

void PlainTextEditor::slotLanguageSelected()
{
    QAction *languageAction = static_cast<QAction *>(QObject::sender());
    setSpellCheckingLanguage(languageAction->data().toString());
}

const QString &PlainTextEditor::spellCheckingLanguage() const
{
    return d->spellCheckingLanguage;
}

void PlainTextEditor::setSpellCheckingLanguage(const QString &_language)
{
    if (highlighter()) {
        highlighter()->setCurrentLanguage(_language);
        highlighter()->rehighlight();
    }

    if (_language != d->spellCheckingLanguage) {
        d->spellCheckingLanguage = _language;
        KSharedConfig::Ptr config = KSharedConfig::openConfig(d->spellCheckingConfigFileName);
        KConfigGroup group(config, "Spelling");
        group.writeEntry("Language", d->spellCheckingLanguage);
        setCheckSpellingEnabled(checkSpellingEnabled());

        Q_EMIT languageChanged(_language);
    }
}

void PlainTextEditor::slotToggleAutoSpellCheck()
{
    setCheckSpellingEnabled(!checkSpellingEnabled());
    KSharedConfig::Ptr config = KSharedConfig::openConfig(d->spellCheckingConfigFileName);
    KConfigGroup group(config, "Spelling");
    group.writeEntry("checkerEnabledByDefault", d->checkSpellingEnabled);
}
Laurent Montel's avatar
Laurent Montel committed
884
885
886

void PlainTextEditor::slotZoomReset()
{
Laurent Montel's avatar
Laurent Montel committed
887
888
    QFont f = font();
    if (d->mInitialFontSize != f.pointSize()) {
Laurent Montel's avatar
Laurent Montel committed
889
890
891
892
        f.setPointSize(d->mInitialFontSize);
        setFont(f);
    }
}