diff --git a/autotests/src/codecompletiontestmodel.h b/autotests/src/codecompletiontestmodel.h index 95428493..77ab32a5 100644 --- a/autotests/src/codecompletiontestmodel.h +++ b/autotests/src/codecompletiontestmodel.h @@ -1,63 +1,63 @@ /* This file is part of the KDE project Copyright (C) 2005 Hamish Rodda 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. 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. 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. */ #ifndef CODECOMPLETIONTEST_H #define CODECOMPLETIONTEST_H #include #include namespace KTextEditor { class View; class CodeCompletionInterface; } class CodeCompletionTestModel : public KTextEditor::CodeCompletionModel { Q_OBJECT public: CodeCompletionTestModel(KTextEditor::View *parent = nullptr, const QString &startText = QString()); KTextEditor::View *view() const; KTextEditor::CodeCompletionInterface *cc() const; - void completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, InvocationType invocationType) Q_DECL_OVERRIDE; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; + void completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, InvocationType invocationType) override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; private: QString m_startText; bool m_autoStartText; }; class AbbreviationCodeCompletionTestModel : public CodeCompletionTestModel { Q_OBJECT public: AbbreviationCodeCompletionTestModel(KTextEditor::View *parent = nullptr, const QString &startText = QString()); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; private: QStringList m_items; }; #endif diff --git a/autotests/src/codecompletiontestmodels.h b/autotests/src/codecompletiontestmodels.h index b1dc646e..3c296fed 100644 --- a/autotests/src/codecompletiontestmodels.h +++ b/autotests/src/codecompletiontestmodels.h @@ -1,166 +1,166 @@ /* This file is part of the KDE libraries Copyright (C) 2008 Niko Sams 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. 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. 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. */ #ifndef KATE_COMPLETIONTESTMODELS_H #define KATE_COMPLETIONTESTMODELS_H #include "codecompletiontestmodel.h" #include #include #include using namespace KTextEditor; class CustomRangeModel : public CodeCompletionTestModel, public CodeCompletionModelControllerInterface { Q_OBJECT Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) public: CustomRangeModel(KTextEditor::View *parent = nullptr, const QString &startText = QString()) : CodeCompletionTestModel(parent, startText) {} - Range completionRange(View *view, const Cursor &position) Q_DECL_OVERRIDE + Range completionRange(View *view, const Cursor &position) override { Range range = CodeCompletionModelControllerInterface::completionRange(view, position); if (range.start().column() > 0) { KTextEditor::Range preRange(Cursor(range.start().line(), range.start().column() - 1), Cursor(range.start().line(), range.start().column())); qDebug() << preRange << view->document()->text(preRange); if (view->document()->text(preRange) == "$") { range.expandToRange(preRange); qDebug() << "using custom completion range" << range; } } return range; } - bool shouldAbortCompletion(View *view, const Range &range, const QString ¤tCompletion) Q_DECL_OVERRIDE + bool shouldAbortCompletion(View *view, const Range &range, const QString ¤tCompletion) override { Q_UNUSED(view); Q_UNUSED(range); static const QRegExp allowedText("^\\$?(\\w*)"); return !allowedText.exactMatch(currentCompletion); } }; class CustomAbortModel : public CodeCompletionTestModel, public CodeCompletionModelControllerInterface { Q_OBJECT Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) public: CustomAbortModel(KTextEditor::View *parent = nullptr, const QString &startText = QString()) : CodeCompletionTestModel(parent, startText) {} - bool shouldAbortCompletion(View *view, const Range &range, const QString ¤tCompletion) Q_DECL_OVERRIDE + bool shouldAbortCompletion(View *view, const Range &range, const QString ¤tCompletion) override { Q_UNUSED(view); Q_UNUSED(range); static const QRegExp allowedText("^([\\w-]*)"); return !allowedText.exactMatch(currentCompletion); } }; class EmptyFilterStringModel : public CodeCompletionTestModel, public CodeCompletionModelControllerInterface { Q_OBJECT Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) public: EmptyFilterStringModel(KTextEditor::View *parent = nullptr, const QString &startText = QString()) : CodeCompletionTestModel(parent, startText) {} - QString filterString(View *, const Range &, const Cursor &) Q_DECL_OVERRIDE + QString filterString(View *, const Range &, const Cursor &) override { return QString(); } }; class UpdateCompletionRangeModel : public CodeCompletionTestModel, public CodeCompletionModelControllerInterface { Q_OBJECT Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) public: UpdateCompletionRangeModel(KTextEditor::View *parent = nullptr, const QString &startText = QString()) : CodeCompletionTestModel(parent, startText) {} - Range updateCompletionRange(View *view, const Range &range) Q_DECL_OVERRIDE + Range updateCompletionRange(View *view, const Range &range) override { Q_UNUSED(view); if (view->document()->text(range) == QString("ab")) { return Range(Cursor(range.start().line(), 0), range.end()); } return range; } - bool shouldAbortCompletion(View *view, const Range &range, const QString ¤tCompletion) Q_DECL_OVERRIDE + bool shouldAbortCompletion(View *view, const Range &range, const QString ¤tCompletion) override { Q_UNUSED(view); Q_UNUSED(range); Q_UNUSED(currentCompletion); return false; } }; class StartCompletionModel : public CodeCompletionTestModel, public CodeCompletionModelControllerInterface { Q_OBJECT Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) public: StartCompletionModel(KTextEditor::View *parent = nullptr, const QString &startText = QString()) : CodeCompletionTestModel(parent, startText) {} - bool shouldStartCompletion(View *view, const QString &insertedText, bool userInsertion, const Cursor &position) Q_DECL_OVERRIDE + bool shouldStartCompletion(View *view, const QString &insertedText, bool userInsertion, const Cursor &position) override { Q_UNUSED(view); Q_UNUSED(userInsertion); Q_UNUSED(position); if (insertedText.isEmpty()) { return false; } QChar lastChar = insertedText.at(insertedText.count() - 1); if (lastChar == '%') { return true; } return false; } }; class ImmideatelyAbortCompletionModel : public CodeCompletionTestModel, public CodeCompletionModelControllerInterface { Q_OBJECT Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) public: ImmideatelyAbortCompletionModel(KTextEditor::View *parent = nullptr, const QString &startText = QString()) : CodeCompletionTestModel(parent, startText) {} - bool shouldAbortCompletion(KTextEditor::View *view, const KTextEditor::Range &range, const QString ¤tCompletion) Q_DECL_OVERRIDE + bool shouldAbortCompletion(KTextEditor::View *view, const KTextEditor::Range &range, const QString ¤tCompletion) override { Q_UNUSED(view); Q_UNUSED(range); Q_UNUSED(currentCompletion); return true; } }; #endif diff --git a/autotests/src/movingrange_test.cpp b/autotests/src/movingrange_test.cpp index a4aae438..38f0b96e 100644 --- a/autotests/src/movingrange_test.cpp +++ b/autotests/src/movingrange_test.cpp @@ -1,443 +1,443 @@ /* This file is part of the KDE libraries Copyright (C) 2010 Dominik Haumann 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. 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. 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. */ #include "movingrange_test.h" #include "moc_movingrange_test.cpp" #include #include #include #include #include #include #include using namespace KTextEditor; QTEST_MAIN(MovingRangeTest) class RangeFeedback : public MovingRangeFeedback { public: RangeFeedback() : MovingRangeFeedback() { reset(); } - void rangeEmpty(MovingRange * /*range*/) Q_DECL_OVERRIDE + void rangeEmpty(MovingRange * /*range*/) override { m_rangeEmptyCalled = true; } - void rangeInvalid(MovingRange * /*range*/) Q_DECL_OVERRIDE + void rangeInvalid(MovingRange * /*range*/) override { m_rangeInvalidCalled = true; } - void mouseEnteredRange(MovingRange * /*range*/, View * /*view*/) Q_DECL_OVERRIDE + void mouseEnteredRange(MovingRange * /*range*/, View * /*view*/) override { m_mouseEnteredRangeCalled = true; } - void mouseExitedRange(MovingRange * /*range*/, View * /*view*/) Q_DECL_OVERRIDE + void mouseExitedRange(MovingRange * /*range*/, View * /*view*/) override { m_mouseExitedRangeCalled = true; } - void caretEnteredRange(MovingRange * /*range*/, View * /*view*/) Q_DECL_OVERRIDE + void caretEnteredRange(MovingRange * /*range*/, View * /*view*/) override { m_caretEnteredRangeCalled = true; } - void caretExitedRange(MovingRange * /*range*/, View * /*view*/) Q_DECL_OVERRIDE + void caretExitedRange(MovingRange * /*range*/, View * /*view*/) override { m_caretExitedRangeCalled = true; } // // Test functions to reset feedback watcher // public: void reset() { m_rangeEmptyCalled = false; m_rangeInvalidCalled = false; m_mouseEnteredRangeCalled = false; m_mouseExitedRangeCalled = false; m_caretEnteredRangeCalled = false; m_caretExitedRangeCalled = false; } void verifyReset() { QVERIFY(!m_rangeEmptyCalled); QVERIFY(!m_rangeInvalidCalled); QVERIFY(!m_mouseEnteredRangeCalled); QVERIFY(!m_mouseExitedRangeCalled); QVERIFY(!m_caretEnteredRangeCalled); QVERIFY(!m_caretExitedRangeCalled); } bool rangeEmptyCalled() const { return m_rangeEmptyCalled; } bool rangeInvalidCalled() const { return m_rangeInvalidCalled; } bool mouseEnteredRangeCalled() const { return m_mouseEnteredRangeCalled; } bool mouseExitedRangeCalled() const { return m_mouseExitedRangeCalled; } bool caretEnteredRangeCalled() const { return m_caretEnteredRangeCalled; } bool caretExitedRangeCalled() const { return m_caretExitedRangeCalled; } private: bool m_rangeEmptyCalled; bool m_rangeInvalidCalled; bool m_mouseEnteredRangeCalled; bool m_mouseExitedRangeCalled; bool m_caretEnteredRangeCalled; bool m_caretExitedRangeCalled; }; MovingRangeTest::MovingRangeTest() : QObject() { KTextEditor::EditorPrivate::enableUnitTestMode(); } MovingRangeTest::~MovingRangeTest() { } // tests: // - RangeFeedback::rangeEmpty void MovingRangeTest::testFeedbackEmptyRange() { KTextEditor::DocumentPrivate doc; // the range created below will span the 'x' characters QString text("..xxxx\n" "xxxx.."); doc.setText(text); // create range feedback RangeFeedback rf; // allow empty MovingRange *range = doc.newMovingRange(Range(Cursor(0, 2), Cursor(1, 4)), KTextEditor::MovingRange::DoNotExpand, KTextEditor::MovingRange::AllowEmpty); range->setFeedback(&rf); rf.verifyReset(); // remove exact range doc.removeText(range->toRange()); QVERIFY(rf.rangeEmptyCalled()); QVERIFY(!rf.rangeInvalidCalled()); QVERIFY(!rf.mouseEnteredRangeCalled()); QVERIFY(!rf.mouseExitedRangeCalled()); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); // clear document: should call rangeInvalid rf.reset(); rf.verifyReset(); doc.clear(); QVERIFY(rf.rangeInvalidCalled()); QVERIFY(!rf.rangeEmptyCalled()); QVERIFY(!rf.mouseEnteredRangeCalled()); QVERIFY(!rf.mouseExitedRangeCalled()); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); // setText: should behave just like clear document: call rangeInvalid again doc.setText(text); range->setRange(Range(Cursor(0, 2), Cursor(1, 4))); rf.reset(); rf.verifyReset(); doc.setText("--yyyy\nyyyy--"); QVERIFY(rf.rangeInvalidCalled()); QVERIFY(!rf.rangeEmptyCalled()); QVERIFY(!rf.mouseEnteredRangeCalled()); QVERIFY(!rf.mouseExitedRangeCalled()); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); // now remove entire document range. In this case, emptyRange should be called // instead of rangeInvalid doc.setText(text); range->setRange(Range(Cursor(0, 2), Cursor(1, 4))); rf.reset(); rf.verifyReset(); doc.removeText(doc.documentRange()); QVERIFY(rf.rangeEmptyCalled()); QVERIFY(!rf.rangeInvalidCalled()); QVERIFY(!rf.mouseEnteredRangeCalled()); QVERIFY(!rf.mouseExitedRangeCalled()); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); } // tests: // - RangeFeedback::rangeInvalid void MovingRangeTest::testFeedbackInvalidRange() { KTextEditor::DocumentPrivate doc; // the range created below will span the 'x' characters QString text("..xxxx\n" "xxxx.."); doc.setText(text); // create range feedback RangeFeedback rf; // allow empty MovingRange *range = doc.newMovingRange(Range(Cursor(0, 2), Cursor(1, 4)), KTextEditor::MovingRange::DoNotExpand, KTextEditor::MovingRange::InvalidateIfEmpty); range->setFeedback(&rf); rf.verifyReset(); // remove exact range doc.removeText(range->toRange()); QVERIFY(!rf.rangeEmptyCalled()); QVERIFY(rf.rangeInvalidCalled()); QVERIFY(!rf.mouseEnteredRangeCalled()); QVERIFY(!rf.mouseExitedRangeCalled()); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); // clear document: should call rangeInvalid again doc.setText(text); range->setRange(Range(Cursor(0, 2), Cursor(1, 4))); rf.reset(); rf.verifyReset(); doc.clear(); QVERIFY(rf.rangeInvalidCalled()); QVERIFY(!rf.rangeEmptyCalled()); QVERIFY(!rf.mouseEnteredRangeCalled()); QVERIFY(!rf.mouseExitedRangeCalled()); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); // setText: should behave just like clear document: call rangeInvalid again doc.setText(text); range->setRange(Range(Cursor(0, 2), Cursor(1, 4))); rf.reset(); rf.verifyReset(); doc.setText("--yyyy\nyyyy--"); QVERIFY(rf.rangeInvalidCalled()); QVERIFY(!rf.rangeEmptyCalled()); QVERIFY(!rf.mouseEnteredRangeCalled()); QVERIFY(!rf.mouseExitedRangeCalled()); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); // now remove entire document range. Call rangeInvalid again doc.setText(text); range->setRange(Range(Cursor(0, 2), Cursor(1, 4))); rf.reset(); rf.verifyReset(); doc.removeText(doc.documentRange()); QVERIFY(rf.rangeInvalidCalled()); QVERIFY(!rf.rangeEmptyCalled()); QVERIFY(!rf.mouseEnteredRangeCalled()); QVERIFY(!rf.mouseExitedRangeCalled()); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); } // tests: // - RangeFeedback::caretEnteredRange // - RangeFeedback::caretExitedRange void MovingRangeTest::testFeedbackCaret() { KTextEditor::DocumentPrivate doc; // the range created below will span the 'x' characters QString text("..xxxx\n" "xxxx.."); doc.setText(text); KTextEditor::ViewPrivate *view = static_cast(doc.createView(nullptr)); // create range feedback RangeFeedback rf; // first test: with ExpandLeft | ExpandRight { view->setCursorPosition(Cursor(1, 6)); MovingRange *range = doc.newMovingRange(Range(Cursor(0, 2), Cursor(1, 4)), KTextEditor::MovingRange::ExpandLeft | KTextEditor::MovingRange::ExpandRight, KTextEditor::MovingRange::InvalidateIfEmpty); rf.reset(); range->setFeedback(&rf); rf.verifyReset(); // left view->cursorLeft(); QCOMPARE(view->cursorPosition(), Cursor(1, 5)); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); view->cursorLeft(); QCOMPARE(view->cursorPosition(), Cursor(1, 4)); QVERIFY(rf.caretEnteredRangeCalled()); // ExpandRight: include cursor already now QVERIFY(!rf.caretExitedRangeCalled()); rf.reset(); view->cursorLeft(); QCOMPARE(view->cursorPosition(), Cursor(1, 3)); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); rf.reset(); view->up(); QCOMPARE(view->cursorPosition(), Cursor(0, 3)); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); rf.reset(); view->cursorLeft(); QCOMPARE(view->cursorPosition(), Cursor(0, 2)); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); rf.reset(); view->cursorLeft(); QCOMPARE(view->cursorPosition(), Cursor(0, 1)); // ExpandLeft: now we left it, not before QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(rf.caretExitedRangeCalled()); delete range; } // second test: with DoNotExpand { view->setCursorPosition(Cursor(1, 6)); MovingRange *range = doc.newMovingRange(Range(Cursor(0, 2), Cursor(1, 4)), KTextEditor::MovingRange::DoNotExpand, KTextEditor::MovingRange::InvalidateIfEmpty); rf.reset(); range->setFeedback(&rf); rf.verifyReset(); // left view->cursorLeft(); QCOMPARE(view->cursorPosition(), Cursor(1, 5)); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); view->cursorLeft(); QCOMPARE(view->cursorPosition(), Cursor(1, 4)); QVERIFY(!rf.caretEnteredRangeCalled()); // DoNotExpand: does not include cursor QVERIFY(!rf.caretExitedRangeCalled()); rf.reset(); view->cursorLeft(); QCOMPARE(view->cursorPosition(), Cursor(1, 3)); QVERIFY(rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); rf.reset(); view->up(); QCOMPARE(view->cursorPosition(), Cursor(0, 3)); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); rf.reset(); view->cursorLeft(); QCOMPARE(view->cursorPosition(), Cursor(0, 2)); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(rf.caretExitedRangeCalled()); // DoNotExpand: that's why we leave already now rf.reset(); view->cursorLeft(); QCOMPARE(view->cursorPosition(), Cursor(0, 1)); QVERIFY(!rf.caretEnteredRangeCalled()); QVERIFY(!rf.caretExitedRangeCalled()); delete range; } } // tests: // - RangeFeedback::mouseEnteredRange // - RangeFeedback::mouseExitedRange void MovingRangeTest::testFeedbackMouse() { KTextEditor::DocumentPrivate doc; // the range created below will span the 'x' characters QString text("..xxxx\n" "xxxx.."); doc.setText(text); KTextEditor::ViewPrivate *view = static_cast(doc.createView(nullptr)); view->setCursorPosition(Cursor(1, 6)); view->show(); view->resize(200, 100); // create range feedback RangeFeedback rf; QVERIFY(!rf.mouseEnteredRangeCalled()); QVERIFY(!rf.mouseExitedRangeCalled()); // allow empty MovingRange *range = doc.newMovingRange(Range(Cursor(0, 2), Cursor(1, 4)), KTextEditor::MovingRange::ExpandLeft | KTextEditor::MovingRange::ExpandRight, KTextEditor::MovingRange::InvalidateIfEmpty); range->setFeedback(&rf); rf.verifyReset(); // left (nothing) QTest::mouseMove(view, view->cursorToCoordinate(Cursor(0, 0)) + QPoint(0, 5)); QTest::qWait(200); // process mouse events. do not move mouse manually QVERIFY(!rf.mouseEnteredRangeCalled()); QVERIFY(!rf.mouseExitedRangeCalled()); // middle (enter) rf.reset(); QTest::mouseMove(view, view->cursorToCoordinate(Cursor(0, 3)) + QPoint(0, 5)); QTest::qWait(200); // process mouse events. do not move mouse manually QVERIFY(rf.mouseEnteredRangeCalled()); QVERIFY(!rf.mouseExitedRangeCalled()); // right (exit) rf.reset(); QTest::mouseMove(view, view->cursorToCoordinate(Cursor(1, 6)) + QPoint(10, 5)); QTest::qWait(200); // process mouse events. do not move mouse manually QVERIFY(!rf.mouseEnteredRangeCalled()); QVERIFY(rf.mouseExitedRangeCalled()); } diff --git a/autotests/src/vimode/completion.h b/autotests/src/vimode/completion.h index 19aa6a7f..25ef3470 100644 --- a/autotests/src/vimode/completion.h +++ b/autotests/src/vimode/completion.h @@ -1,70 +1,70 @@ /* * This file is part of the KDE libraries * * Copyright (C) 2014 Miquel Sabaté Solà * * 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. * * 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. * 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. */ #ifndef COMPLETION_TEST_H #define COMPLETION_TEST_H #include "base.h" #include "fakecodecompletiontestmodel.h" /** * This class handles implements a completion model for the completion * tests defined in the CompletionTest class. */ class VimCodeCompletionTestModel : public KTextEditor::CodeCompletionModel { public: VimCodeCompletionTestModel(KTextEditor::View *parent); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; KTextEditor::CodeCompletionInterface *cc() const; }; /** * This class implements a completion model used in the CompletionTest class * to test that code completion is not invoked. */ class FailTestOnInvocationModel : public KTextEditor::CodeCompletionModel { public: FailTestOnInvocationModel(KTextEditor::View *parent); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; void failTest() const; KTextEditor::CodeCompletionInterface *cc() const; }; class CompletionTest : public BaseTest { Q_OBJECT private Q_SLOTS: void FakeCodeCompletionTests(); void CompletionTests(); private: void waitForCompletionWidgetToActivate(); void clearTrackedDocumentChanges(); }; #endif /* COMPLETION_TEST_H */ diff --git a/autotests/src/vimode/emulatedcommandbarsetupandteardown.h b/autotests/src/vimode/emulatedcommandbarsetupandteardown.h index 30197ed4..a91caea0 100644 --- a/autotests/src/vimode/emulatedcommandbarsetupandteardown.h +++ b/autotests/src/vimode/emulatedcommandbarsetupandteardown.h @@ -1,68 +1,68 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2013-2016 Simon St James * * 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. * * 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. * * 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. */ #include namespace KTextEditor { class ViewPrivate; } class KateViInputMode; class QMainWindow; /** * This class is used by the EmulatedCommandBarSetUpAndTearDown class so * the main window is active all the time. */ class WindowKeepActive : public QObject { Q_OBJECT public: WindowKeepActive(QMainWindow *mainWindow); public Q_SLOTS: - bool eventFilter(QObject *object, QEvent *event) Q_DECL_OVERRIDE; + bool eventFilter(QObject *object, QEvent *event) override; private: QMainWindow *m_mainWindow; }; /** * Helper class that is used to setup and tear down tests affecting * the command bar in any way. */ class EmulatedCommandBarSetUpAndTearDown { public: EmulatedCommandBarSetUpAndTearDown(KateViInputMode *inputMode, KTextEditor::ViewPrivate *view, QMainWindow *window); ~EmulatedCommandBarSetUpAndTearDown(); private: KTextEditor::ViewPrivate *m_view; QMainWindow *m_window; WindowKeepActive m_windowKeepActive; KateViInputMode *m_viInputMode; }; diff --git a/autotests/src/vimode/fakecodecompletiontestmodel.h b/autotests/src/vimode/fakecodecompletiontestmodel.h index f643dee6..e9587126 100644 --- a/autotests/src/vimode/fakecodecompletiontestmodel.h +++ b/autotests/src/vimode/fakecodecompletiontestmodel.h @@ -1,102 +1,102 @@ /* * This file is part of the KDE libraries * * Copyright (C) 2014 Miquel Sabaté Solà * * 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. * * 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. * 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. */ #ifndef FAKE_CODE_COMPLETION_TEST_MODEL_H #define FAKE_CODE_COMPLETION_TEST_MODEL_H #include /** * Helper class that mimics some of the behaviour of KDevelop's code completion, in particular * whether it performs "bracket merging" on completed function calls e.g. if we complete a call * to "functionCall(int a)" at the end of the -> here: * * object->( * * we end up with * * object->functionCall( * * and the cursor placed after the closing bracket: the opening bracket is merged with the existing * bracket. * * However, if we do the same with * * object-> * * we end up with * * object->functionCall() * * again with the cursor placed after the opening bracket. This time, the brackets were not merged. * * This helper class is used to test how Macros and replaying of last changes works with complex * code completion. */ class FakeCodeCompletionTestModel : public KTextEditor::CodeCompletionModel { Q_OBJECT public: FakeCodeCompletionTestModel(KTextEditor::View *parent); /** * List of completions, in sorted order. * A string ending with "()" is treated as a call to a function with no arguments. * A string ending with "(...)" is treated as a call to a function with at least one argument. The "..." is not * inserted into the text. * A string ending with "();" or "(...);" is the same as above, and the semi-colon is added. Bracket merging * never happens with strings ending with ";". */ void setCompletions(const QStringList &completions); void setRemoveTailOnComplete(bool removeTailOnCompletion); void setFailTestOnInvocation(bool failTestOnInvocation); bool wasInvoked(); void clearWasInvoked(); /** * A more reliable form of setAutomaticInvocationEnabled(). */ void forceInvocationIfDocTextIs(const QString &desiredDocText); void doNotForceInvocation(); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; - void executeCompletionItem (KTextEditor::View *view, const KTextEditor::Range &word, const QModelIndex &index) const Q_DECL_OVERRIDE; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + void executeCompletionItem (KTextEditor::View *view, const KTextEditor::Range &word, const QModelIndex &index) const override; KTextEditor::CodeCompletionInterface *cc() const; private: void failTest() const; QStringList m_completions; KTextEditor::ViewPrivate *m_kateView; KTextEditor::Document *m_kateDoc; bool m_removeTailOnCompletion; bool m_failTestOnInvocation; mutable bool m_wasInvoked; QString m_forceInvocationIfDocTextIs; private Q_SLOTS: void textInserted(KTextEditor::Document *document, KTextEditor::Range range); void textRemoved(KTextEditor::Document *document, KTextEditor::Range range); void checkIfShouldForceInvocation(); }; #endif /* FAKE_CODE_COMPLETION_TEST_MODEL_H */ diff --git a/src/buffer/katetextcursor.h b/src/buffer/katetextcursor.h index 84288e1d..341fcf3f 100644 --- a/src/buffer/katetextcursor.h +++ b/src/buffer/katetextcursor.h @@ -1,260 +1,260 @@ /* This file is part of the Kate project. * * Copyright (C) 2010 Christoph Cullmann * * Based on code of the SmartCursor/Range by: * Copyright (C) 2003-2005 Hamish Rodda * * 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. * * 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. * * 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. */ #ifndef KATE_TEXTCURSOR_H #define KATE_TEXTCURSOR_H #include #include #include "katetextblock.h" namespace Kate { class TextBuffer; class TextBlock; class TextRange; /** * Class representing a 'clever' text cursor. * It will automagically move if the text inside the buffer it belongs to is modified. * By intention no subclass of KTextEditor::Cursor, must be converted manually. */ class KTEXTEDITOR_EXPORT TextCursor : public KTextEditor::MovingCursor { // range wants direct access to some internals friend class TextRange; // this is a friend, because this is needed to efficiently transfer cursors from on to an other block friend class TextBlock; private: /** * Construct a text cursor with given range as parent, private, used by TextRange constructor only. * @param buffer text buffer this cursor belongs to * @param range text range this cursor is part of * @param position wanted cursor position, if not valid for given buffer, will lead to invalid cursor * @param insertBehavior behavior of this cursor on insert of text at its position */ TextCursor(TextBuffer &buffer, TextRange *range, const KTextEditor::Cursor &position, InsertBehavior insertBehavior); public: /** * Construct a text cursor. * @param buffer text buffer this cursor belongs to * @param position wanted cursor position, if not valid for given buffer, will lead to invalid cursor * @param insertBehavior behavior of this cursor on insert of text at its position */ TextCursor(TextBuffer &buffer, const KTextEditor::Cursor &position, InsertBehavior insertBehavior); /** * Destruct the text cursor */ - ~TextCursor() Q_DECL_OVERRIDE; + ~TextCursor() override; /** * Set insert behavior. * @param insertBehavior new insert behavior */ - void setInsertBehavior(InsertBehavior insertBehavior) Q_DECL_OVERRIDE + void setInsertBehavior(InsertBehavior insertBehavior) override { m_moveOnInsert = insertBehavior == MoveOnInsert; } /** * Get current insert behavior. * @return current insert behavior */ - InsertBehavior insertBehavior() const Q_DECL_OVERRIDE + InsertBehavior insertBehavior() const override { return m_moveOnInsert ? MoveOnInsert : StayOnInsert; } /** * Gets the document to which this cursor is bound. * \return a pointer to the document */ - KTextEditor::Document *document() const Q_DECL_OVERRIDE; + KTextEditor::Document *document() const override; /** * Fast way to set the current cursor position to \e position. * * \param position new cursor position */ void setPosition(const TextCursor &position); /** * Set the current cursor position to \e position. * * \param position new cursor position */ - void setPosition(const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; + void setPosition(const KTextEditor::Cursor &position) override; /** * \overload * * Set the cursor position to \e line and \e column. * * \param line new cursor line * \param column new cursor column */ void setPosition(int line, int column) { KTextEditor::MovingCursor::setPosition(line, column); } /** * Retrieve the line on which this cursor is situated. * \return line number, where 0 is the first line. */ - int line() const Q_DECL_OVERRIDE; + int line() const override; /** * Non-virtual version of line(), which is faster. * Inlined for fast access (especially in KateTextBuffer::rangesForLine * \return line number, where 0 is the first line. */ int lineInternal() const { // invalid cursor have no block if (!m_block) { return -1; } // else, calculate real line return m_block->startLine() + m_line; } /** * Retrieve the column on which this cursor is situated. * \return column number, where 0 is the first column. */ - int column() const Q_DECL_OVERRIDE + int column() const override { return m_column; } /** * Non-virtual version of column(), which is faster. * \return column number, where 0 is the first column. * */ int columnInternal() const { return m_column; } /** * Get range this cursor belongs to, if any * @return range this pointer is part of, else 0 */ - KTextEditor::MovingRange *range() const Q_DECL_OVERRIDE; + KTextEditor::MovingRange *range() const override; /** * Get range this cursor belongs to, if any * @return range this pointer is part of, else 0 */ Kate::TextRange *kateRange() const { return m_range; } /** * Get block this cursor belongs to, if any * @return block this pointer is part of, else 0 */ TextBlock *block() const { return m_block; } /** * Get offset into block this cursor belongs to, if any * @return offset into block this pointer is part of, else -1 */ int lineInBlock() const { if (m_block) { return m_line; } return -1; } private: /** * no copy constructor, don't allow this to be copied. */ TextCursor(const TextCursor &); /** * no assignment operator, no copying around. */ TextCursor &operator= (const TextCursor &); /** * Set the current cursor position to \e position. * Internal helper to allow the same code be used for constructor and * setPosition. * * @param position new cursor position * @param init is this the initial setup of the position in the constructor? */ void setPosition(const KTextEditor::Cursor &position, bool init); private: /** * parent text buffer * is a reference, and no pointer, as this must always exist and can't change */ TextBuffer &m_buffer; /** * range this cursor belongs to * may be null, then no range owns this cursor * can not change after initial assignment */ TextRange *const m_range; /** * parent text block, valid cursors always belong to a block, else they are invalid. */ TextBlock *m_block; /** * line, offset in block, or -1 */ int m_line; /** * column */ int m_column; /** * should this cursor move on insert */ bool m_moveOnInsert; }; } #endif diff --git a/src/buffer/katetextrange.h b/src/buffer/katetextrange.h index a263fc5f..a2694dad 100644 --- a/src/buffer/katetextrange.h +++ b/src/buffer/katetextrange.h @@ -1,363 +1,363 @@ /* This file is part of the Kate project. * * Copyright (C) 2010 Christoph Cullmann * * Based on code of the SmartCursor/Range by: * Copyright (C) 2003-2005 Hamish Rodda * * 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. * * 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. * * 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. */ #ifndef KATE_TEXTRANGE_H #define KATE_TEXTRANGE_H #include #include #include #include #include "katetextcursor.h" namespace Kate { class TextBuffer; /** * Class representing a 'clever' text range. * It will automagically move if the text inside the buffer it belongs to is modified. * By intention no subclass of KTextEditor::Range, must be converted manually. * A TextRange is allowed to be empty. If you call setInvalidateIfEmpty(true), * a TextRange will become automatically invalid as soon as start() == end() * position holds. */ class KTEXTEDITOR_EXPORT TextRange : public KTextEditor::MovingRange { // this is a friend, block changes might invalidate ranges... friend class TextBlock; public: /** * Construct a text range. * A TextRange is not allowed to be empty, as soon as start == end position, it will become * automatically invalid! * @param buffer parent text buffer * @param range The initial text range assumed by the new range. * @param insertBehavior Define whether the range should expand when text is inserted adjacent to the range. * @param emptyBehavior Define whether the range should invalidate itself on becoming empty. */ TextRange(TextBuffer &buffer, const KTextEditor::Range &range, InsertBehaviors insertBehavior, EmptyBehavior emptyBehavior = AllowEmpty); /** * Destruct the text block */ - ~TextRange() Q_DECL_OVERRIDE; + ~TextRange() override; /** * Set insert behaviors. * @param insertBehaviors new insert behaviors */ - void setInsertBehaviors(InsertBehaviors insertBehaviors) Q_DECL_OVERRIDE; + void setInsertBehaviors(InsertBehaviors insertBehaviors) override; /** * Get current insert behaviors. * @return current insert behaviors */ - InsertBehaviors insertBehaviors() const Q_DECL_OVERRIDE; + InsertBehaviors insertBehaviors() const override; /** * Set if this range will invalidate itself if it becomes empty. * @param emptyBehavior behavior on becoming empty */ - void setEmptyBehavior(EmptyBehavior emptyBehavior) Q_DECL_OVERRIDE; + void setEmptyBehavior(EmptyBehavior emptyBehavior) override; /** * Will this range invalidate itself if it becomes empty? * @return behavior on becoming empty */ - EmptyBehavior emptyBehavior() const Q_DECL_OVERRIDE + EmptyBehavior emptyBehavior() const override { return m_invalidateIfEmpty ? InvalidateIfEmpty : AllowEmpty; } /** * Gets the document to which this range is bound. * \return a pointer to the document */ - KTextEditor::Document *document() const Q_DECL_OVERRIDE; + KTextEditor::Document *document() const override; /** * Set the range of this range. * A TextRange is not allowed to be empty, as soon as start == end position, it will become * automatically invalid! * @param range new range for this clever range */ - void setRange(const KTextEditor::Range &range) Q_DECL_OVERRIDE; + void setRange(const KTextEditor::Range &range) override; /** * \overload * Set the range of this range * A TextRange is not allowed to be empty, as soon as start == end position, it will become * automatically invalid! * @param start new start for this clever range * @param end new end for this clever range */ void setRange(const KTextEditor::Cursor &start, const KTextEditor::Cursor &end) { KTextEditor::MovingRange::setRange(start, end); } /** * Retrieve start cursor of this range, read-only. * @return start cursor */ - const KTextEditor::MovingCursor &start() const Q_DECL_OVERRIDE + const KTextEditor::MovingCursor &start() const override { return m_start; } /** * Non-virtual version of start(), which is faster. * @return start cursor */ const TextCursor &startInternal() const { return m_start; } /** * Retrieve end cursor of this range, read-only. * @return end cursor */ - const KTextEditor::MovingCursor &end() const Q_DECL_OVERRIDE + const KTextEditor::MovingCursor &end() const override { return m_end; } /** * Nonvirtual version of end(), which is faster. * @return end cursor */ const TextCursor &endInternal() const { return m_end; } /** * Convert this clever range into a dumb one. * @return normal range */ const KTextEditor::Range toRange() const { return KTextEditor::Range(start().toCursor(), end().toCursor()); } /** * Convert this clever range into a dumb one. Equal to toRange, allowing to use implicit conversion. * @return normal range */ operator KTextEditor::Range() const { return KTextEditor::Range(start().toCursor(), end().toCursor()); } /** * Gets the active view for this range. Might be already invalid, internally only used for pointer comparisons. * * \return a pointer to the active view */ - KTextEditor::View *view() const Q_DECL_OVERRIDE + KTextEditor::View *view() const override { return m_view; } /** * Sets the currently active view for this range. * This will trigger update of the relevant view parts, if the view changed. * Set view before the attribute, that will avoid not needed redraws. * * \param view View to assign to this range. If null, simply * removes the previous view. */ - void setView(KTextEditor::View *view) Q_DECL_OVERRIDE; + void setView(KTextEditor::View *view) override; /** * Gets the active Attribute for this range. * * \return a pointer to the active attribute */ - KTextEditor::Attribute::Ptr attribute() const Q_DECL_OVERRIDE + KTextEditor::Attribute::Ptr attribute() const override { return m_attribute; } /** * \return whether a nonzero attribute is set. This is faster than checking attribute(), * because the reference-counting is omitted. */ bool hasAttribute() const { return m_attribute.constData(); } /** * Sets the currently active attribute for this range. * This will trigger update of the relevant view parts. * * \param attribute Attribute to assign to this range. If null, simply * removes the previous Attribute. */ - void setAttribute(KTextEditor::Attribute::Ptr attribute) Q_DECL_OVERRIDE; + void setAttribute(KTextEditor::Attribute::Ptr attribute) override; /** * Gets the active MovingRangeFeedback for this range. * * \return a pointer to the active MovingRangeFeedback */ - KTextEditor::MovingRangeFeedback *feedback() const Q_DECL_OVERRIDE + KTextEditor::MovingRangeFeedback *feedback() const override { return m_feedback; } /** * Sets the currently active MovingRangeFeedback for this range. * This will trigger evaluation if feedback must be send again (for example if mouse is already inside range). * * \param feedback MovingRangeFeedback to assign to this range. If null, simply * removes the previous MovingRangeFeedback. */ - void setFeedback(KTextEditor::MovingRangeFeedback *feedback) Q_DECL_OVERRIDE; + void setFeedback(KTextEditor::MovingRangeFeedback *feedback) override; /** * Is this range's attribute only visible in views, not for example prints? * Default is false. * @return range visible only for views */ - bool attributeOnlyForViews() const Q_DECL_OVERRIDE + bool attributeOnlyForViews() const override { return m_attributeOnlyForViews; } /** * Set if this range's attribute is only visible in views, not for example prints. * @param onlyForViews attribute only valid for views */ - void setAttributeOnlyForViews(bool onlyForViews) Q_DECL_OVERRIDE; + void setAttributeOnlyForViews(bool onlyForViews) override; /** * Gets the current Z-depth of this range. * Ranges with smaller Z-depth than others will win during rendering. * Default is 0.0. * * \return current Z-depth of this range */ - qreal zDepth() const Q_DECL_OVERRIDE + qreal zDepth() const override { return m_zDepth; } /** * Set the current Z-depth of this range. * Ranges with smaller Z-depth than others will win during rendering. * This will trigger update of the relevant view parts, if the depth changed. * Set depth before the attribute, that will avoid not needed redraws. * Default is 0.0. * * \param zDepth new Z-depth of this range */ - void setZDepth(qreal zDepth) Q_DECL_OVERRIDE; + void setZDepth(qreal zDepth) override; private: /** * no copy constructor, don't allow this to be copied. */ TextRange(const TextRange &); /** * no assignment operator, no copying around. */ TextRange &operator= (const TextRange &); /** * Check if range is valid, used by constructor and setRange. * If at least one cursor is invalid, both will set to invalid. * Same if range itself is invalid (start >= end). * @param oldStartLine old start line of this range before changing of cursors, needed to add/remove range from m_ranges in blocks * @param oldEndLine old end line of this range * @param notifyAboutChange should feedback be emitted or not? */ void checkValidity(int oldStartLine = -1, int oldEndLine = -1, bool notifyAboutChange = true); /** * Add/Remove range from the lookup m_ranges hash of each block * @param oldStartLine old start line of this range before changing of cursors, needed to add/remove range from m_ranges in blocks * @param oldEndLine old end line of this range * @param startLine start line to start looking for the range to remove * @param endLine end line of this range */ void fixLookup(int oldStartLine, int oldEndLine, int startLine, int endLine); private: /** * parent text buffer * is a reference, and no pointer, as this must always exist and can't change */ TextBuffer &m_buffer; /** * Start cursor for this range, is a clever cursor */ TextCursor m_start; /** * End cursor for this range, is a clever cursor */ TextCursor m_end; /** * The view for which the attribute is valid, 0 means any view */ KTextEditor::View *m_view; /** * This range's current attribute. */ KTextEditor::Attribute::Ptr m_attribute; /** * pointer to the active MovingRangeFeedback */ KTextEditor::MovingRangeFeedback *m_feedback; /** * Z-depth of this range for rendering */ qreal m_zDepth; /** * Is this range's attribute only visible in views, not for example prints? */ bool m_attributeOnlyForViews; /** * Will this range invalidate itself if it becomes empty? */ bool m_invalidateIfEmpty; }; } #endif diff --git a/src/completion/expandingtree/expandingdelegate.h b/src/completion/expandingtree/expandingdelegate.h index 3395b380..3a72bf63 100644 --- a/src/completion/expandingtree/expandingdelegate.h +++ b/src/completion/expandingtree/expandingdelegate.h @@ -1,86 +1,86 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2006 Hamish Rodda * * 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. * * 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. * * 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. */ #ifndef ExpandingDelegate_H #define ExpandingDelegate_H #include #include #include class ExpandingWidgetModel; class QVariant; class QStyleOptionViewItem; /** * This is a delegate that cares, together with ExpandingWidgetModel, about embedded widgets in tree-view. * */ class ExpandingDelegate : public QItemDelegate { Q_OBJECT public: explicit ExpandingDelegate(ExpandingWidgetModel *model, QObject *parent = nullptr); // Overridden to create highlighting for current index - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; // Returns the basic size-hint as reported by QItemDelegate QSize basicSizeHint(const QModelIndex &index) const; ExpandingWidgetModel *model() const; protected: //Called right before paint to allow last-minute changes to the style virtual void adjustStyle(const QModelIndex &index, QStyleOptionViewItem &option) const; - void drawDisplay(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, const QString &text) const Q_DECL_OVERRIDE; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; - bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) Q_DECL_OVERRIDE; + void drawDisplay(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, const QString &text) const override; + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; + bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override; virtual void drawBackground(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; - void drawDecoration(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, const QPixmap &pixmap) const Q_DECL_OVERRIDE; + void drawDecoration(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, const QPixmap &pixmap) const override; //option can be changed virtual QList createHighlighting(const QModelIndex &index, QStyleOptionViewItem &option) const; void adjustRect(QRect &rect) const; /** * Creates a list of FormatRanges as should be returned by createHighlighting from a list of QVariants as described in the kde header ktexteditor/codecompletionmodel.h * */ QList highlightingFromVariantList(const QList &customHighlights) const; //Called when an item was expanded/unexpanded and the height changed virtual void heightChanged() const; //Initializes the style options from the index void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const; mutable int m_currentColumnStart; //Text-offset for custom highlighting, will be applied to m_cachedHighlights(Only highlights starting after this will be used). Shoult be zero of the highlighting is not taken from kate. mutable QList m_currentColumnStarts; mutable QList m_cachedHighlights; mutable Qt::Alignment m_cachedAlignment; mutable QColor m_backgroundColor; mutable QModelIndex m_currentIndex; private: ExpandingWidgetModel *m_model; }; #endif diff --git a/src/completion/expandingtree/expandingtree.h b/src/completion/expandingtree/expandingtree.h index 783897f1..426d729b 100644 --- a/src/completion/expandingtree/expandingtree.h +++ b/src/completion/expandingtree/expandingtree.h @@ -1,39 +1,39 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2007 David Nolden * * 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. * * 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. * * 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. */ #ifndef ExpandingTree_H #define ExpandingTree_H #include #include //A tree that allows drawing additional information class ExpandingTree : public QTreeView { public: explicit ExpandingTree(QWidget *parent); protected: - void drawRow(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; - int sizeHintForColumn(int column) const Q_DECL_OVERRIDE; + void drawRow(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; + int sizeHintForColumn(int column) const override; private: mutable QTextDocument m_drawText; }; #endif diff --git a/src/completion/expandingtree/expandingwidgetmodel.h b/src/completion/expandingtree/expandingwidgetmodel.h index d7119e1f..87462e18 100644 --- a/src/completion/expandingtree/expandingwidgetmodel.h +++ b/src/completion/expandingtree/expandingwidgetmodel.h @@ -1,157 +1,157 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2007 David Nolden * * 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. * * 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. * * 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. */ #ifndef EXPANDING_WIDGET_MODEL_H #define EXPANDING_WIDGET_MODEL_H #include #include #include class QTreeView; /** * Cares about expanding/un-expanding items in a tree-view together with ExpandingDelegate */ class ExpandingWidgetModel : public QAbstractItemModel { Q_OBJECT public: explicit ExpandingWidgetModel(QWidget *parent); virtual ~ExpandingWidgetModel(); enum ExpandingType { NotExpandable = 0, Expandable, Expanded }; ///The following three are convenience-functions for the current item that could be replaced by the later ones ///@return whether the current item can be expanded bool canExpandCurrentItem() const; ///@return whether the current item can be collapsed bool canCollapseCurrentItem() const; ///Expand/collapse the current item void setCurrentItemExpanded(bool); void clearMatchQualities(); ///Unexpand all rows and clear all cached information about them(this includes deleting the expanding-widgets) void clearExpanding(); ///@return whether the row given through index is expandable bool isExpandable(const QModelIndex &index) const; enum ExpansionType { NotExpanded = 0, ExpandDownwards, //The additional(expanded) information is shown UNDER the original information ExpandUpwards //The additional(expanded) information is shown ABOVE the original information }; ///Returns whether the given index is currently partially expanded. Does not do any other checks like calling models for data. ExpansionType isPartiallyExpanded(const QModelIndex &index) const; ///@return whether row is currently expanded bool isExpanded(const QModelIndex &row) const; ///Change the expand-state of the row given through index. The display will be updated. void setExpanded(QModelIndex index, bool expanded); ///Returns the total height added through all open expanding-widgets int expandingWidgetsHeight() const; ///@return the expanding-widget for the given row, if available. Expanding-widgets are in best case available for all expanded rows. ///This does not return the partially-expand widget. QWidget *expandingWidget(const QModelIndex &row) const; ///Amount by which the height of a row increases when it is partially expanded int partiallyExpandWidgetHeight() const; /** * Notifies underlying models that the item was selected, collapses any previous partially expanded line, * checks whether this line should be partially expanded, and eventually does it. * Does nothing when nothing needs to be done. * Does NOT show the expanding-widget. That is done immediately when painting by ExpandingDelegate, * to reduce flickering. @see showPartialExpandWidget() * @param row The row * */ /// virtual void rowSelected(const QModelIndex &row); ///Returns the rectangle for the partially expanded part of the given row QRect partialExpandRect(const QModelIndex &row) const; QString partialExpandText(const QModelIndex &row) const; ///Places and shows the expanding-widget for the given row, if it should be visible and is valid. ///Also shows the partial-expanding-widget when it should be visible. void placeExpandingWidget(const QModelIndex &row); virtual QTreeView *treeView() const = 0; ///Should return true if the given row should be painted like a contained item(as opposed to label-rows etc.) virtual bool indexIsItem(const QModelIndex &index) const = 0; ///Does not request data from index, this only returns local data like highlighting for expanded rows and similar - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; ///Returns the first row that is currently partially expanded. QModelIndex partiallyExpandedRow() const; ///Returns the match-color for the given index, or zero if match-quality could not be computed. uint matchColor(const QModelIndex &index) const; public Q_SLOTS: ///Place or hides all expanding-widgets to the correct positions. Should be called after the view was scrolled. void placeExpandingWidgets(); protected: /** * @return the context-match quality from 0 to 10 if it could be determined, else -1 * */ virtual int contextMatchQuality(const QModelIndex &index) const = 0; //Makes sure m_expandedIcon and m_collapsedIcon are loaded void cacheIcons() const; mutable QIcon m_expandedIcon; mutable QIcon m_collapsedIcon; //Does not update the view void partiallyUnExpand(const QModelIndex &index); //Finds out the basic height of the row represented by the given index. Basic means without respecting any expansion. int basicRowHeight(const QModelIndex &index) const; private: QMap m_partiallyExpanded; // Store expanding-widgets and cache whether items can be expanded mutable QMap m_expandState; QMap< QModelIndex, QPointer > m_expandingWidgets; //Map rows to their expanding-widgets QMap< QModelIndex, int > m_contextMatchQualities; //Map rows to their context-match qualities(undefined if unknown, else 0 to 10). Not used yet, eventually remove. }; /** * Helper-function to merge custom-highlighting variant-lists. * * @param strings A list of strings that should be merged * @param highlights One variant-list for highlighting, as described in the kde header ktextedtor/codecompletionmodel.h * @param gapBetweenStrings How many signs are inserted between 2 strings? * */ QList mergeCustomHighlighting(QStringList strings, QList highlights, int gapBetweenStrings = 0); #endif diff --git a/src/completion/kateargumenthintmodel.h b/src/completion/kateargumenthintmodel.h index d47bfd2c..82d06956 100644 --- a/src/completion/kateargumenthintmodel.h +++ b/src/completion/kateargumenthintmodel.h @@ -1,72 +1,72 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2007 David Nolden * * 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. * * 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. * * 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. */ #ifndef KATEARGUMENTHINTMODEL_H #define KATEARGUMENTHINTMODEL_H #include #include "katecompletionmodel.h" #include "expandingtree/expandingwidgetmodel.h" class KateCompletionWidget; class KateArgumentHintModel : public ExpandingWidgetModel { Q_OBJECT public: explicit KateArgumentHintModel(KateCompletionWidget *parent); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - int rowCount(const QModelIndex &parent = {}) const Q_DECL_OVERRIDE; + int rowCount(const QModelIndex &parent = {}) const override; - int columnCount(const QModelIndex & parent = {}) const Q_DECL_OVERRIDE; + int columnCount(const QModelIndex & parent = {}) const override; - QModelIndex index(int row, int column, const QModelIndex& parent = {}) const Q_DECL_OVERRIDE; + QModelIndex index(int row, int column, const QModelIndex& parent = {}) const override; - QModelIndex parent(const QModelIndex& parent) const Q_DECL_OVERRIDE; + QModelIndex parent(const QModelIndex& parent) const override; - QTreeView *treeView() const Q_DECL_OVERRIDE; + QTreeView *treeView() const override; - bool indexIsItem(const QModelIndex &index) const Q_DECL_OVERRIDE; + bool indexIsItem(const QModelIndex &index) const override; void emitDataChanged(const QModelIndex &start, const QModelIndex &end); //Returns the index in the source-model for an index within this model QModelIndex mapToSource(const QModelIndex &proxyIndex) const; void buildRows(); void clear(); protected: - int contextMatchQuality(const QModelIndex &row) const Q_DECL_OVERRIDE; + int contextMatchQuality(const QModelIndex &row) const override; public Q_SLOTS: void parentModelReset(); Q_SIGNALS: void contentStateChanged(bool hasContent); private: KateCompletionModel::Group *group() const; KateCompletionModel *model() const; QList m_rows; //Maps rows to either a positive row-number in the source group, or to a negative number which indicates a label KateCompletionWidget *m_parent; }; #endif diff --git a/src/completion/kateargumenthinttree.h b/src/completion/kateargumenthinttree.h index 41b18d78..176992a1 100644 --- a/src/completion/kateargumenthinttree.h +++ b/src/completion/kateargumenthinttree.h @@ -1,64 +1,64 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2007 David Nolden * * 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. * * 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. * * 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. */ #ifndef KATEARGUMENTHINTTREE_H #define KATEARGUMENTHINTTREE_H #include "expandingtree/expandingtree.h" class KateCompletionWidget; class KateArgumentHintModel; class QRect; class KateArgumentHintTree : public ExpandingTree { Q_OBJECT public: explicit KateArgumentHintTree(KateCompletionWidget *parent); // Navigation bool nextCompletion(); bool previousCompletion(); bool pageDown(); bool pageUp(); void top(); void bottom(); //Returns the total size of all columns int resizeColumns(); void clearCompletion(); public Q_SLOTS: void updateGeometry(); void updateGeometry(QRect rect); protected: - void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; - void rowsInserted(const QModelIndex &parent, int start, int end) Q_DECL_OVERRIDE; - void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles = QVector()) Q_DECL_OVERRIDE; - void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) Q_DECL_OVERRIDE; + void paintEvent(QPaintEvent *event) override; + void rowsInserted(const QModelIndex &parent, int start, int end) override; + void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector &roles = QVector()) override; + void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) override; private: uint rowHeight(const QModelIndex &index) const; KateArgumentHintModel *model() const; - int sizeHintForColumn(int column) const Q_DECL_OVERRIDE; + int sizeHintForColumn(int column) const override; KateCompletionWidget *m_parent; }; #endif diff --git a/src/completion/katecompletionconfig.h b/src/completion/katecompletionconfig.h index 03540f29..45b0f1b7 100644 --- a/src/completion/katecompletionconfig.h +++ b/src/completion/katecompletionconfig.h @@ -1,83 +1,83 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2006 Hamish Rodda * * 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. * * 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. * * 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. */ #ifndef KATECOMPLETIONCONFIG_H #define KATECOMPLETIONCONFIG_H #include #include "kateconfig.h" namespace Ui { class CompletionConfigWidget; } class QTreeWidgetItem; class KateCompletionModel; /** * @author Hamish Rodda */ class KateCompletionConfig : public QDialog, public KateConfig { Q_OBJECT public: explicit KateCompletionConfig(KateCompletionModel *model, QWidget *parent = nullptr); - ~KateCompletionConfig() Q_DECL_OVERRIDE; + ~KateCompletionConfig() override; /** * Read config from object */ void readConfig(const KConfigGroup &config); /** * Write config to object */ void writeConfig(KConfigGroup &config); public Q_SLOTS: void apply(); protected: - void updateConfig() Q_DECL_OVERRIDE; + void updateConfig() override; private Q_SLOTS: void moveColumnUp(); void moveColumnDown(); void moveGroupingUp(); void moveGroupingDown(); void moveGroupingOrderUp(); void moveGroupingOrderDown(); private: void applyInternal(); Ui::CompletionConfigWidget *ui; KateCompletionModel *m_model; QTreeWidgetItem *m_groupingScopeType; QTreeWidgetItem *m_groupingScope; QTreeWidgetItem *m_groupingAccessType; QTreeWidgetItem *m_groupingItemType; }; #endif diff --git a/src/completion/katecompletiondelegate.h b/src/completion/katecompletiondelegate.h index 361511bb..0124eb6b 100644 --- a/src/completion/katecompletiondelegate.h +++ b/src/completion/katecompletiondelegate.h @@ -1,47 +1,47 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2007 David Nolden * * 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. * * 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. * * 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. */ #ifndef KATECOMPLETIONDELEGATE_H #define KATECOMPLETIONDELEGATE_H #include "expandingtree/expandingdelegate.h" class KateRenderer; namespace KTextEditor { class DocumentPrivate; } class KateCompletionWidget; class KateCompletionDelegate : public ExpandingDelegate { public: explicit KateCompletionDelegate(ExpandingWidgetModel *model, KateCompletionWidget *parent); KateRenderer *renderer() const; KateCompletionWidget *widget() const; KTextEditor::DocumentPrivate *document() const; protected: - void adjustStyle(const QModelIndex &index, QStyleOptionViewItem &option) const Q_DECL_OVERRIDE; + void adjustStyle(const QModelIndex &index, QStyleOptionViewItem &option) const override; mutable int m_cachedRow; mutable QList m_cachedColumnStarts; - void heightChanged() const Q_DECL_OVERRIDE; - QList createHighlighting(const QModelIndex &index, QStyleOptionViewItem &option) const Q_DECL_OVERRIDE; + void heightChanged() const override; + QList createHighlighting(const QModelIndex &index, QStyleOptionViewItem &option) const override; }; #endif diff --git a/src/completion/katecompletionmodel.h b/src/completion/katecompletionmodel.h index d7594609..b68fb4da 100644 --- a/src/completion/katecompletionmodel.h +++ b/src/completion/katecompletionmodel.h @@ -1,417 +1,417 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2005-2006 Hamish Rodda * Copyright (C) 2007-2008 David Nolden * * 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. * * 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. * * 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. */ #ifndef KATECOMPLETIONMODEL_H #define KATECOMPLETIONMODEL_H #include #include #include #include #include #include "expandingtree/expandingwidgetmodel.h" class KateCompletionWidget; class KateArgumentHintModel; namespace KTextEditor { class ViewPrivate; } class QWidget; class QTextEdit; class QTimer; class HierarchicalModelHandler; /** * This class has the responsibility for filtering, sorting, and manipulating * code completion data provided by a CodeCompletionModel. * * @author Hamish Rodda */ class KTEXTEDITOR_EXPORT KateCompletionModel : public ExpandingWidgetModel { Q_OBJECT public: explicit KateCompletionModel(KateCompletionWidget *parent = nullptr); ~KateCompletionModel(); QList completionModels() const; void clearCompletionModels(); void addCompletionModel(KTextEditor::CodeCompletionModel *model); void setCompletionModel(KTextEditor::CodeCompletionModel *model); void setCompletionModels(const QList &models); void removeCompletionModel(KTextEditor::CodeCompletionModel *model); KTextEditor::ViewPrivate *view() const; KateCompletionWidget *widget() const; QString currentCompletion(KTextEditor::CodeCompletionModel *model) const; void setCurrentCompletion(KTextEditor::CodeCompletionModel *model, const QString &completion); Qt::CaseSensitivity matchCaseSensitivity() const; void setMatchCaseSensitivity(Qt::CaseSensitivity cs); static QString columnName(int column); int translateColumn(int sourceColumn) const; static QString propertyName(KTextEditor::CodeCompletionModel::CompletionProperty property); ///Returns a common prefix for all current visible completion entries ///If there is no common prefix, extracts the next useful prefix for the selected index QString commonPrefix(QModelIndex selectedIndex) const; - void rowSelected(const QModelIndex &row) Q_DECL_OVERRIDE; + void rowSelected(const QModelIndex &row) override; - bool indexIsItem(const QModelIndex &index) const Q_DECL_OVERRIDE; + bool indexIsItem(const QModelIndex &index) const override; - int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; - Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE; - bool hasChildren(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + Qt::ItemFlags flags(const QModelIndex &index) const override; + bool hasChildren(const QModelIndex &parent = QModelIndex()) const override; virtual bool hasIndex(int row, int column, const QModelIndex &parent = QModelIndex()) const; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; // Disabled in case of bugs, reenable once fully debugged. //virtual QMap itemData ( const QModelIndex & index ) const; - QModelIndex parent(const QModelIndex &index) const Q_DECL_OVERRIDE; - int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + QModelIndex parent(const QModelIndex &index) const override; + int rowCount(const QModelIndex &parent = QModelIndex()) const override; // Disabled in case of bugs, reenable once fully debugged. //virtual QModelIndex sibling ( int row, int column, const QModelIndex & index ) const; - void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) Q_DECL_OVERRIDE; + void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override; ///Maps from this display-model into the appropriate source code-completion model virtual QModelIndex mapToSource(const QModelIndex &proxyIndex) const; ///Maps from an index in a source-model to the index of the item in this display-model virtual QModelIndex mapFromSource(const QModelIndex &sourceIndex) const; // Sorting bool isSortingEnabled() const; bool isSortingAlphabetical() const; bool isSortingByInheritanceDepth() const; void setSortingByInheritanceDepth(bool byIneritance); void setSortingAlphabetical(bool alphabetical); Qt::CaseSensitivity sortingCaseSensitivity() const; void setSortingCaseSensitivity(Qt::CaseSensitivity cs); bool isSortingReverse() const; void setSortingReverse(bool reverse); // Filtering bool isFilteringEnabled() const; bool filterContextMatchesOnly() const; void setFilterContextMatchesOnly(bool filter); bool filterByAttribute() const; void setFilterByAttribute(bool filter); KTextEditor::CodeCompletionModel::CompletionProperties filterAttributes() const; void setFilterAttributes(KTextEditor::CodeCompletionModel::CompletionProperties attributes); // A maximum depth of <= 0 equals don't filter by inheritance depth (i.e. infinity) and is default int maximumInheritanceDepth() const; void setMaximumInheritanceDepth(int maxDepth); // Grouping bool isGroupingEnabled() const; enum gm { ScopeType = 0x1, Scope = 0x2, AccessType = 0x4, ItemType = 0x8 }; enum { //An own property that will be used to mark the best-matches group internally BestMatchesProperty = 2 * KTextEditor::CodeCompletionModel::LastProperty }; Q_DECLARE_FLAGS(GroupingMethods, gm) static const int ScopeTypeMask = 0x380000; static const int AccessTypeMask = 0x7; static const int ItemTypeMask = 0xfe0; GroupingMethods groupingMethod() const; void setGroupingMethod(GroupingMethods m); bool accessIncludeConst() const; void setAccessIncludeConst(bool include); bool accessIncludeStatic() const; void setAccessIncludeStatic(bool include); bool accessIncludeSignalSlot() const; void setAccessIncludeSignalSlot(bool include); // Column merging bool isColumnMergingEnabled() const; const QList< QList > &columnMerges() const; void setColumnMerges(const QList< QList > &columnMerges); void debugStats(); ///Returns whether one of the filtered items exactly matches its completion string bool shouldMatchHideCompletionList() const; uint filteredItemCount() const; protected: - int contextMatchQuality(const QModelIndex &index) const Q_DECL_OVERRIDE; + int contextMatchQuality(const QModelIndex &index) const override; Q_SIGNALS: void expandIndex(const QModelIndex &index); //Emitted whenever something has changed about the group of argument-hints void argumentHintsChanged(); public Q_SLOTS: void setSortingEnabled(bool enable); void setFilteringEnabled(bool enable); void setGroupingEnabled(bool enable); void setColumnMergingEnabled(bool enable); private Q_SLOTS: void slotRowsInserted(const QModelIndex &parent, int start, int end); void slotRowsRemoved(const QModelIndex &parent, int start, int end); void slotModelReset(); //Updates the best-matches group void updateBestMatches(); //Makes sure that the ungrouped group contains each item only once //Must only be called right after the group was created void makeGroupItemsUnique(bool onlyFiltered = false); private: typedef QPair ModelRow; virtual int contextMatchQuality(const ModelRow &sourceRow) const; - QTreeView *treeView() const Q_DECL_OVERRIDE; + QTreeView *treeView() const override; friend class KateArgumentHintModel; ModelRow modelRowPair(const QModelIndex &index) const; // Represents a source row; provides sorting method class Item { public: Item(bool doInitialMatch, KateCompletionModel *model, const HierarchicalModelHandler &handler, ModelRow sourceRow); bool isValid() const; // Returns true if the item is not filtered and matches the current completion string bool isVisible() const; // Returns whether the item is filtered or not bool isFiltered() const; // Returns whether the item matches the current completion string bool isMatching() const; bool filter(); enum MatchType { NoMatch = 0, PerfectMatch, StartsWithMatch, AbbreviationMatch, ContainsMatch }; MatchType match(); const ModelRow &sourceRow() const; // Sorting operator bool operator<(const Item &rhs) const; bool haveExactMatch() const { return m_haveExactMatch; } void clearExactMatch() { m_haveExactMatch = false; } QString name() const { return m_nameColumn; } private: KateCompletionModel *model; ModelRow m_sourceRow; mutable QString m_nameColumn; int inheritanceDepth; // True when currently matching completion string MatchType matchCompletion; // True when passes all active filters bool matchFilters; bool m_haveExactMatch; bool m_unimportant; QString completionSortingName() const; }; public: // Grouping and sorting of rows class Group { public: explicit Group(const QString& title, int attribute, KateCompletionModel *model); void addItem(Item i, bool notifyModel = false); /// Removes the item specified by \a row. Returns true if a change was made to rows. bool removeItem(const ModelRow &row); void resort(); void refilter(); void clear(); //Returns whether this group should be ordered before other bool orderBefore(Group *other) const; //Returns a number that can be used for ordering int orderNumber() const; ///Returns the row in the this group's filtered list of the given model-row in a source-model ///-1 if the item is not in the filtered list ///@todo Implement an efficient way of doing this map, that does _not_ iterate over all items! int rowOf(ModelRow item) { for (int a = 0; a < filtered.size(); ++a) if (filtered[a].sourceRow() == item) { return a; } return -1; } KateCompletionModel *model; int attribute; QString title, scope; QList filtered; QList prefilter; bool isEmpty; //-1 if none was set int customSortingKey; }; bool hasGroups() const; private: QString commonPrefixInternal(const QString &forcePrefix) const; /// @note performs model reset void createGroups(); ///Creates all sub-items of index i, or the item corresponding to index i. Returns the affected groups. ///i must be an index in the source model QSet createItems(const HierarchicalModelHandler &, const QModelIndex &i, bool notifyModel = false); ///Deletes all sub-items of index i, or the item corresponding to index i. Returns the affected groups. ///i must be an index in the source model QSet deleteItems(const QModelIndex &i); Group *createItem(const HierarchicalModelHandler &, const QModelIndex &i, bool notifyModel = false); /// @note Make sure you're in a {begin,end}ResetModel block when calling this! void clearGroups(); void hideOrShowGroup(Group *g, bool notifyModel = false); /// When forceGrouping is enabled, all given attributes will be used for grouping, regardless of the completion settings. Group *fetchGroup(int attribute, const QString &scope = QString(), bool forceGrouping = false); //If this returns nonzero on an index, the index is the header of the returned group Group *groupForIndex(const QModelIndex &index) const; inline Group *groupOfParent(const QModelIndex &child) const { return static_cast(child.internalPointer()); } QModelIndex indexForRow(Group *g, int row) const; QModelIndex indexForGroup(Group *g) const; enum changeTypes { Broaden, Narrow, Change }; //Returns whether the model needs to be reset void changeCompletions(Group *g, changeTypes changeType, bool notifyModel); bool hasCompletionModel() const; /// Removes attributes not used in grouping from the input \a attribute int groupingAttributes(int attribute) const; int countBits(int value) const; void resort(); void refilter(); static bool matchesAbbreviation(const QString &word, const QString &typed); bool m_hasGroups = false; // ### Runtime state // General QList m_completionModels; QMap m_currentMatch; Qt::CaseSensitivity m_matchCaseSensitivity = Qt::CaseInsensitive; // Column merging QList< QList > m_columnMerges; QTimer *m_updateBestMatchesTimer; Group *m_ungrouped; Group *m_argumentHints; //The argument-hints will be passed on to another model, to be shown in another widget Group *m_bestMatches; //A temporary group used for holding the best matches of all visible items // Storing the sorted order QList m_rowTable; QList m_emptyGroups; // Quick access to each specific group (if it exists) QMultiHash m_groupHash; // Maps custom group-names to their specific groups QHash m_customGroupHash; // ### Configurable state // Sorting bool m_sortingEnabled = false; bool m_sortingAlphabetical = false; bool m_isSortingByInheritance = false; Qt::CaseSensitivity m_sortingCaseSensitivity = Qt::CaseInsensitive; QHash< int, QList > m_sortingGroupingOrder; // Filtering bool m_filteringEnabled = false; bool m_filterContextMatchesOnly = false; bool m_filterByAttribute = false; KTextEditor::CodeCompletionModel::CompletionProperties m_filterAttributes; int m_maximumInheritanceDepth = 0; // Grouping bool m_groupingEnabled = false; GroupingMethods m_groupingMethod; bool m_accessConst = false, m_accessStatic = false, m_accesSignalSlot = false; // Column merging bool m_columnMergingEnabled = false/*, m_haveExactMatch*/; friend class CompletionTest; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KateCompletionModel::GroupingMethods) #endif diff --git a/src/completion/katecompletiontree.h b/src/completion/katecompletiontree.h index 12c35669..207da277 100644 --- a/src/completion/katecompletiontree.h +++ b/src/completion/katecompletiontree.h @@ -1,71 +1,71 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2006 Hamish Rodda * Copyright (C) 2007-2008 David Nolden * * 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. * * 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. * * 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. */ #ifndef KATECOMPLETIONTREE_H #define KATECOMPLETIONTREE_H #include "expandingtree/expandingtree.h" class KateCompletionWidget; class KateCompletionModel; class QTimer; class KateCompletionTree : public ExpandingTree { Q_OBJECT public: explicit KateCompletionTree(KateCompletionWidget *parent); KateCompletionWidget *widget() const; KateCompletionModel *kateModel() const; void resizeColumns(bool firstShow = false, bool forceResize = false); // Navigation bool nextCompletion(); bool previousCompletion(); bool pageDown(); bool pageUp(); void top(); void bottom(); void scheduleUpdate(); void setScrollingEnabled(bool); /// Returns the approximated viewport position of the text in the given column, skipping an eventual icon int columnTextViewportPosition(int column) const; private Q_SLOTS: void resizeColumnsSlot(); protected: - void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) Q_DECL_OVERRIDE; ///Not available as a signal in this way - void scrollContentsBy(int dx, int dy) Q_DECL_OVERRIDE; - QStyleOptionViewItem viewOptions() const Q_DECL_OVERRIDE; + void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) override; ///Not available as a signal in this way + void scrollContentsBy(int dx, int dy) override; + QStyleOptionViewItem viewOptions() const override; private: bool m_scrollingEnabled; QTimer *m_resizeTimer; }; #endif diff --git a/src/completion/katecompletionwidget.h b/src/completion/katecompletionwidget.h index 3265e6ff..c8b7ec60 100644 --- a/src/completion/katecompletionwidget.h +++ b/src/completion/katecompletionwidget.h @@ -1,248 +1,248 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2005-2006 Hamish Rodda * Copyright (C) 2007-2008 David Nolden * * 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. * * 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. * * 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. */ #ifndef KATECOMPLETIONWIDGET_H #define KATECOMPLETIONWIDGET_H #include #include #include #include #include #include class QToolButton; class QPushButton; class QLabel; class QTimer; namespace KTextEditor { class ViewPrivate; } class KateCompletionModel; class KateCompletionTree; class KateArgumentHintTree; class KateArgumentHintModel; namespace KTextEditor { class EmbeddedWidgetInterface; } /** * This is the code completion's main widget, and also contains the * core interface logic. * * @author Hamish Rodda */ class KTEXTEDITOR_EXPORT KateCompletionWidget : public QFrame { Q_OBJECT public: explicit KateCompletionWidget(KTextEditor::ViewPrivate *parent); - ~KateCompletionWidget() Q_DECL_OVERRIDE; + ~KateCompletionWidget() override; KTextEditor::ViewPrivate *view() const; KateCompletionTree *treeView() const; bool isCompletionActive() const; void startCompletion(KTextEditor::CodeCompletionModel::InvocationType invocationType, const QList &models = QList()); void startCompletion(const KTextEditor::Range &word, KTextEditor::CodeCompletionModel *model, KTextEditor::CodeCompletionModel::InvocationType invocationType = KTextEditor::CodeCompletionModel::ManualInvocation); void startCompletion(const KTextEditor::Range &word, const QList &models = QList(), KTextEditor::CodeCompletionModel::InvocationType invocationType = KTextEditor::CodeCompletionModel::ManualInvocation); void userInvokedCompletion(); public Q_SLOTS: //Executed when return is pressed while completion is active. void execute(); void cursorDown(); void cursorUp(); public: void tab(bool shift); ///Returns whether the current item was expanded/unexpanded bool toggleExpanded(bool forceExpand = false, bool forceUnExpand = false); const KateCompletionModel *model() const; KateCompletionModel *model(); void registerCompletionModel(KTextEditor::CodeCompletionModel *model); void unregisterCompletionModel(KTextEditor::CodeCompletionModel *model); bool isCompletionModelRegistered(KTextEditor::CodeCompletionModel *model) const; int automaticInvocationDelay() const; void setAutomaticInvocationDelay(int delay); struct CompletionRange { CompletionRange() { } explicit CompletionRange(KTextEditor::MovingRange *r) : range(r) { } bool operator==(const CompletionRange &rhs) const { return range->toRange() == rhs.range->toRange(); } KTextEditor::MovingRange *range = nullptr; //Whenever the cursor goes before this position, the completion is stopped, unless it is invalid. KTextEditor::Cursor leftBoundary; }; KTextEditor::MovingRange *completionRange(KTextEditor::CodeCompletionModel *model = nullptr) const; QMap completionRanges() const; // Navigation void pageDown(); void pageUp(); void top(); void bottom(); QWidget *currentEmbeddedWidget(); bool canExpandCurrentItem() const; bool canCollapseCurrentItem() const; void setCurrentItemExpanded(bool); //Returns true if a screen border has been hit bool updatePosition(bool force = false); - bool eventFilter(QObject *watched, QEvent *event) Q_DECL_OVERRIDE; + bool eventFilter(QObject *watched, QEvent *event) override; KateArgumentHintTree *argumentHintTree() const; KateArgumentHintModel *argumentHintModel() const; ///Called by KateViewInternal, because we need the specific information from the event. void updateHeight(); public Q_SLOTS: void waitForModelReset(); void abortCompletion(); void showConfig(); /* void viewFocusIn(); void viewFocusOut();*/ void updatePositionSlot(); void automaticInvocation(); /* void updateFocus();*/ void argumentHintsChanged(bool hasContent); bool navigateUp(); bool navigateDown(); bool navigateLeft(); bool navigateRight(); bool navigateAccept(); bool navigateBack(); bool hadNavigation() const; void resetHadNavigation(); protected: - void showEvent(QShowEvent *event) Q_DECL_OVERRIDE; - void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE; - void moveEvent(QMoveEvent *event) Q_DECL_OVERRIDE; - void focusOutEvent(QFocusEvent * event) Q_DECL_OVERRIDE; + void showEvent(QShowEvent *event) override; + void resizeEvent(QResizeEvent *event) override; + void moveEvent(QMoveEvent *event) override; + void focusOutEvent(QFocusEvent * event) override; private Q_SLOTS: void completionModelReset(); void modelDestroyed(QObject *model); void modelContentChanged(); void cursorPositionChanged(); void modelReset(); void rowsInserted(const QModelIndex &parent, int row, int rowEnd); void viewFocusOut(); void wrapLine(const KTextEditor::Cursor &position); void unwrapLine(int line); void insertText(const KTextEditor::Cursor &position, const QString &text); void removeText(const KTextEditor::Range &range); private: void updateAndShow(); void updateArgumentHintGeometry(); QModelIndex selectedIndex() const; void clear(); //Switch cursor between argument-hint list / completion-list void switchList(); KTextEditor::Range determineRange() const; void completionRangeChanged(KTextEditor::CodeCompletionModel *, const KTextEditor::Range &word); void deleteCompletionRanges(); QList m_sourceModels; KateCompletionModel *m_presentationModel; QMap m_completionRanges; QSet m_waitingForReset; KTextEditor::Cursor m_lastCursorPosition; KateCompletionTree *m_entryList; KateArgumentHintModel *m_argumentHintModel; KateArgumentHintTree *m_argumentHintTree; QTimer *m_automaticInvocationTimer; //QTimer* m_updateFocusTimer; QWidget *m_statusBar; QToolButton *m_sortButton; QLabel *m_sortText; QToolButton *m_filterButton; QLabel *m_filterText; QPushButton *m_configButton; KTextEditor::Cursor m_automaticInvocationAt; QString m_automaticInvocationLine; int m_automaticInvocationDelay; bool m_filterInstalled; class KateCompletionConfig *m_configWidget; bool m_lastInsertionByUser; bool m_inCompletionList; //Are we in the completion-list? If not, we're in the argument-hint list bool m_isSuspended; bool m_dontShowArgumentHints; //Used temporarily to prevent flashing bool m_needShow; bool m_hadCompletionNavigation; bool m_haveExactMatch; bool m_noAutoHide; /** * is a completion edit ongoing? */ bool m_completionEditRunning; int m_expandedAddedHeightBase; KTextEditor::CodeCompletionModel::InvocationType m_lastInvocationType; }; #endif diff --git a/src/completion/katekeywordcompletion.h b/src/completion/katekeywordcompletion.h index 7ba1efc2..3c7903f3 100644 --- a/src/completion/katekeywordcompletion.h +++ b/src/completion/katekeywordcompletion.h @@ -1,62 +1,62 @@ /* This file is part of the KDE libraries Copyright (C) 2014 Sven Brauch This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2, or any later version, as published by the Free Software Foundation. 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. 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. */ #ifndef KATEKEYWORDCOMPLETIONMODEL_H #define KATEKEYWORDCOMPLETIONMODEL_H #include "ktexteditor/codecompletionmodel.h" #include "codecompletionmodelcontrollerinterface.h" /** * @brief Highlighting-file based keyword completion for the editor. * * This model offers completion of language-specific keywords based on information * taken from the kate syntax files. It queries the highlighting engine to get the * correct context for a given cursor position, then suggests all keyword items * from the XML file for the active language. */ class KateKeywordCompletionModel : public KTextEditor::CodeCompletionModel , public KTextEditor::CodeCompletionModelControllerInterface { Q_OBJECT Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) public: explicit KateKeywordCompletionModel(QObject* parent); - QVariant data(const QModelIndex& index, int role) const Q_DECL_OVERRIDE; - int rowCount(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE; - QModelIndex parent(const QModelIndex& index) const Q_DECL_OVERRIDE; - QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE; + QVariant data(const QModelIndex& index, int role) const override; + int rowCount(const QModelIndex& parent = QModelIndex()) const override; + QModelIndex parent(const QModelIndex& index) const override; + QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; void completionInvoked(KTextEditor::View* view, const KTextEditor::Range& range, - InvocationType invocationType) Q_DECL_OVERRIDE; - KTextEditor::Range completionRange(KTextEditor::View* view, const KTextEditor::Cursor& position) Q_DECL_OVERRIDE; + InvocationType invocationType) override; + KTextEditor::Range completionRange(KTextEditor::View* view, const KTextEditor::Cursor& position) override; bool shouldAbortCompletion(KTextEditor::View* view, const KTextEditor::Range& range, - const QString& currentCompletion) Q_DECL_OVERRIDE; + const QString& currentCompletion) override; bool shouldStartCompletion(KTextEditor::View* view, const QString& insertedText, bool userInsertion, - const KTextEditor::Cursor& position) Q_DECL_OVERRIDE; - MatchReaction matchingItem(const QModelIndex& matched) Q_DECL_OVERRIDE; - bool shouldHideItemsWithEqualNames() const Q_DECL_OVERRIDE; + const KTextEditor::Cursor& position) override; + MatchReaction matchingItem(const QModelIndex& matched) override; + bool shouldHideItemsWithEqualNames() const override; private: QList m_items; }; #endif // KATEKEYWORDCOMPLETIONMODEL_H // kate: indent-width 4; replace-tabs on diff --git a/src/completion/katewordcompletion.h b/src/completion/katewordcompletion.h index 047cdcf4..a9bc6018 100644 --- a/src/completion/katewordcompletion.h +++ b/src/completion/katewordcompletion.h @@ -1,114 +1,114 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2003 Anders Lund * Copyright (C) 2010 Christoph Cullmann * * 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. * * 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. * * 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. */ #ifndef _KateWordCompletion_h_ #define _KateWordCompletion_h_ #include #include #include #include #include #include #include #include "katepartdebug.h" #include class KTEXTEDITOR_EXPORT KateWordCompletionModel : public KTextEditor::CodeCompletionModel, public KTextEditor::CodeCompletionModelControllerInterface { Q_OBJECT Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) public: explicit KateWordCompletionModel(QObject *parent); - ~KateWordCompletionModel() Q_DECL_OVERRIDE; + ~KateWordCompletionModel() override; /** * This function is responsible to generating / updating the list of current * completions. The default implementation does nothing. * * When implementing this function, remember to call setRowCount() (or implement * rowCount()), and to generate the appropriate change notifications (for instance * by calling QAbstractItemModel::reset()). * @param view The view to generate completions for * @param range The range of text to generate completions for * */ - void completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, InvocationType invocationType) Q_DECL_OVERRIDE; + void completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, InvocationType invocationType) override; - bool shouldStartCompletion(KTextEditor::View *view, const QString &insertedText, bool userInsertion, const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; - bool shouldAbortCompletion(KTextEditor::View *view, const KTextEditor::Range &range, const QString ¤tCompletion) Q_DECL_OVERRIDE; + bool shouldStartCompletion(KTextEditor::View *view, const QString &insertedText, bool userInsertion, const KTextEditor::Cursor &position) override; + bool shouldAbortCompletion(KTextEditor::View *view, const KTextEditor::Range &range, const QString ¤tCompletion) override; void saveMatches(KTextEditor::View *view, const KTextEditor::Range &range); - int rowCount(const QModelIndex &parent) const Q_DECL_OVERRIDE; + int rowCount(const QModelIndex &parent) const override; - QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; - QModelIndex parent(const QModelIndex &index) const Q_DECL_OVERRIDE; - MatchReaction matchingItem(const QModelIndex &matched) Q_DECL_OVERRIDE; + QVariant data(const QModelIndex &index, int role) const override; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; + QModelIndex parent(const QModelIndex &index) const override; + MatchReaction matchingItem(const QModelIndex &matched) override; - KTextEditor::Range completionRange(KTextEditor::View *view, const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; + KTextEditor::Range completionRange(KTextEditor::View *view, const KTextEditor::Cursor &position) override; - bool shouldHideItemsWithEqualNames() const Q_DECL_OVERRIDE; + bool shouldHideItemsWithEqualNames() const override; QStringList allMatches(KTextEditor::View *view, const KTextEditor::Range &range) const; - void executeCompletionItem (KTextEditor::View *view, const KTextEditor::Range &word, const QModelIndex &index) const Q_DECL_OVERRIDE; + void executeCompletionItem (KTextEditor::View *view, const KTextEditor::Range &word, const QModelIndex &index) const override; private: QStringList m_matches; bool m_automatic; }; class KateWordCompletionView : public QObject { Q_OBJECT public: KateWordCompletionView(KTextEditor::View *view, KActionCollection *ac); ~KateWordCompletionView(); private Q_SLOTS: void completeBackwards(); void completeForwards(); void slotCursorMoved(); void shellComplete(); void popupCompletionList(); private: void complete(bool fw = true); QString word() const; KTextEditor::Range range() const; QString findLongestUnique(const QStringList &matches, int lead) const; KTextEditor::View *m_view; KateWordCompletionModel *m_dWCompletionModel; struct KateWordCompletionViewPrivate *d; }; #endif // _DocWordCompletionPlugin_h_ diff --git a/src/dialogs/katedialogs.h b/src/dialogs/katedialogs.h index a0d3f806..5bda8579 100644 --- a/src/dialogs/katedialogs.h +++ b/src/dialogs/katedialogs.h @@ -1,374 +1,374 @@ /* This file is part of the KDE libraries Copyright (C) 2002, 2003 Anders Lund Copyright (C) 2003 Christoph Cullmann Copyright (C) 2001 Joseph Wenninger Copyright (C) 2006-2016 Dominik Haumann Copyright (C) 2007 Mirko Stocker Copyright (C) 2009 Michel Ludwig Copyright (C) 1999 Jochen Wilhelmy * * 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. * * 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. * * 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. */ #ifndef __KATE_DIALOGS_H__ #define __KATE_DIALOGS_H__ #include "katehighlight.h" #include "kateviewhelpers.h" #include "kateconfigpage.h" #include #include #include #include #include #include #include #include #include class ModeConfigPage; namespace KTextEditor { class DocumentPrivate; } namespace KTextEditor { class ViewPrivate; } namespace KTextEditor { class Message; } namespace KIO { class Job; class TransferJob; } class KComboBox; class KShortcutsEditor; class QSpinBox; class KPluginSelector; class KPluginInfo; class KProcess; class QCheckBox; class QLabel; class QCheckBox; class QKeyEvent; class QTemporaryFile; class QTableWidget; namespace Ui { class TextareaAppearanceConfigWidget; class BordersAppearanceConfigWidget; class NavigationConfigWidget; class EditConfigWidget; class IndentationConfigWidget; class OpenSaveConfigWidget; class OpenSaveConfigAdvWidget; class CompletionConfigTab; class SpellCheckConfigWidget; } class KateGotoBar : public KateViewBarWidget { Q_OBJECT public: explicit KateGotoBar(KTextEditor::View *view, QWidget *parent = nullptr); void updateData(); protected Q_SLOTS: void gotoLine(); protected: - void keyPressEvent(QKeyEvent *event) Q_DECL_OVERRIDE; + void keyPressEvent(QKeyEvent *event) override; private: KTextEditor::View *const m_view; QSpinBox *gotoRange; }; class KateDictionaryBar : public KateViewBarWidget { Q_OBJECT public: explicit KateDictionaryBar(KTextEditor::ViewPrivate *view, QWidget *parent = nullptr); virtual ~KateDictionaryBar(); public Q_SLOTS: void updateData(); protected Q_SLOTS: void dictionaryChanged(const QString &dictionary); private: KTextEditor::ViewPrivate *m_view; Sonnet::DictionaryComboBox *m_dictionaryComboBox; }; class KateIndentConfigTab : public KateConfigPage { Q_OBJECT public: explicit KateIndentConfigTab(QWidget *parent); ~KateIndentConfigTab(); - QString name() const Q_DECL_OVERRIDE; + QString name() const override; protected: Ui::IndentationConfigWidget *ui; public Q_SLOTS: - void apply() Q_DECL_OVERRIDE; - void reload() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE {} - void defaults() Q_DECL_OVERRIDE {} + void apply() override; + void reload() override; + void reset() override {} + void defaults() override {} private Q_SLOTS: void slotChanged(); void showWhatsThis(const QString &text); }; class KateCompletionConfigTab : public KateConfigPage { Q_OBJECT public: explicit KateCompletionConfigTab(QWidget *parent); ~KateCompletionConfigTab(); - QString name() const Q_DECL_OVERRIDE; + QString name() const override; protected: Ui::CompletionConfigTab *ui; public Q_SLOTS: - void apply() Q_DECL_OVERRIDE; - void reload() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE {} - void defaults() Q_DECL_OVERRIDE {} + void apply() override; + void reload() override; + void reset() override {} + void defaults() override {} private Q_SLOTS: void showWhatsThis(const QString &text); }; class KateEditGeneralConfigTab : public KateConfigPage { Q_OBJECT public: explicit KateEditGeneralConfigTab(QWidget *parent); ~KateEditGeneralConfigTab(); - QString name() const Q_DECL_OVERRIDE; + QString name() const override; private: Ui::EditConfigWidget *ui; public Q_SLOTS: - void apply() Q_DECL_OVERRIDE; - void reload() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE {} - void defaults() Q_DECL_OVERRIDE {} + void apply() override; + void reload() override; + void reset() override {} + void defaults() override {} }; class KateNavigationConfigTab : public KateConfigPage { Q_OBJECT public: explicit KateNavigationConfigTab(QWidget *parent); ~KateNavigationConfigTab(); - QString name() const Q_DECL_OVERRIDE; + QString name() const override; private: Ui::NavigationConfigWidget *ui; public Q_SLOTS: - void apply() Q_DECL_OVERRIDE; - void reload() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE {} - void defaults() Q_DECL_OVERRIDE {} + void apply() override; + void reload() override; + void reset() override {} + void defaults() override {} }; class KateSpellCheckConfigTab : public KateConfigPage { Q_OBJECT public: explicit KateSpellCheckConfigTab(QWidget *parent); ~KateSpellCheckConfigTab(); - QString name() const Q_DECL_OVERRIDE; + QString name() const override; protected: Ui::SpellCheckConfigWidget *ui; Sonnet::ConfigWidget *m_sonnetConfigWidget; public Q_SLOTS: - void apply() Q_DECL_OVERRIDE; - void reload() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE {} - void defaults() Q_DECL_OVERRIDE {} + void apply() override; + void reload() override; + void reset() override {} + void defaults() override {} private Q_SLOTS: void showWhatsThis(const QString &text); }; class KateEditConfigTab : public KateConfigPage { Q_OBJECT public: explicit KateEditConfigTab(QWidget *parent); ~KateEditConfigTab(); - QString name() const Q_DECL_OVERRIDE; - QString fullName() const Q_DECL_OVERRIDE; - QIcon icon() const Q_DECL_OVERRIDE; + QString name() const override; + QString fullName() const override; + QIcon icon() const override; public Q_SLOTS: - void apply() Q_DECL_OVERRIDE; - void reload() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE; - void defaults() Q_DECL_OVERRIDE; + void apply() override; + void reload() override; + void reset() override; + void defaults() override; private: KateEditGeneralConfigTab *editConfigTab; KateNavigationConfigTab *navigationConfigTab; KateIndentConfigTab *indentConfigTab; KateCompletionConfigTab *completionConfigTab; KateSpellCheckConfigTab *spellCheckConfigTab; QList m_inputModeConfigTabs; }; class KateViewDefaultsConfig : public KateConfigPage { Q_OBJECT public: explicit KateViewDefaultsConfig(QWidget *parent); ~KateViewDefaultsConfig(); - QString name() const Q_DECL_OVERRIDE; - QString fullName() const Q_DECL_OVERRIDE; - QIcon icon() const Q_DECL_OVERRIDE; + QString name() const override; + QString fullName() const override; + QIcon icon() const override; public Q_SLOTS: - void apply() Q_DECL_OVERRIDE; - void reload() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE; - void defaults() Q_DECL_OVERRIDE; + void apply() override; + void reload() override; + void reset() override; + void defaults() override; private: Ui::TextareaAppearanceConfigWidget *const textareaUi; Ui::BordersAppearanceConfigWidget *const bordersUi; }; class KateSaveConfigTab : public KateConfigPage { Q_OBJECT public: explicit KateSaveConfigTab(QWidget *parent); ~KateSaveConfigTab(); - QString name() const Q_DECL_OVERRIDE; - QString fullName() const Q_DECL_OVERRIDE; - QIcon icon() const Q_DECL_OVERRIDE; + QString name() const override; + QString fullName() const override; + QIcon icon() const override; public Q_SLOTS: - void apply() Q_DECL_OVERRIDE; - void reload() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE; - void defaults() Q_DECL_OVERRIDE; + void apply() override; + void reload() override; + void reset() override; + void defaults() override; void swapFileModeChanged(int); protected: //why? //KComboBox *m_encoding, *m_encodingDetection, *m_eol; QCheckBox *cbLocalFiles, *cbRemoteFiles; QCheckBox *replaceTabs, *removeSpaces, *allowEolDetection; class QSpinBox *blockCount; class QLabel *blockCountLabel; private: Ui::OpenSaveConfigWidget *ui; Ui::OpenSaveConfigAdvWidget *uiadv; ModeConfigPage *modeConfigPage; }; class KateHlDownloadDialog: public QDialog { Q_OBJECT public: KateHlDownloadDialog(QWidget *parent, const char *name, bool modal); ~KateHlDownloadDialog(); private: static unsigned parseVersion(const QString &); class QTreeWidget *list; class QString listData; KIO::TransferJob *transferJob; QPushButton *m_installButton; private Q_SLOTS: void listDataReceived(KIO::Job *, const QByteArray &data); void slotInstall(); }; /** * This dialog will prompt the user for what do with a file that is * modified on disk. * If the file wasn't deleted, it has a 'diff' button, which will create * a diff file (uing diff(1)) and launch that using KRun. */ class KateModOnHdPrompt : public QObject { Q_OBJECT public: enum Status { Reload = 1, // 0 is QDialog::Rejected Save, Overwrite, Ignore, Close }; KateModOnHdPrompt(KTextEditor::DocumentPrivate *doc, KTextEditor::ModificationInterface::ModifiedOnDiskReason modtype, const QString &reason); ~KateModOnHdPrompt(); Q_SIGNALS: void saveAsTriggered(); void ignoreTriggered(); void reloadTriggered(); private Q_SLOTS: /** * Show a diff between the document text and the disk file. */ void slotDiff(); private Q_SLOTS: void slotDataAvailable(); ///< read data from the process void slotPDone(); ///< Runs the diff file when done private: KTextEditor::DocumentPrivate *m_doc; QPointer m_message; KTextEditor::ModificationInterface::ModifiedOnDiskReason m_modtype; KProcess *m_proc; QTemporaryFile *m_diffFile; QAction *m_diffAction; }; #endif diff --git a/src/document/katebuffer.h b/src/document/katebuffer.h index 1bbe7c22..09a9d772 100644 --- a/src/document/katebuffer.h +++ b/src/document/katebuffer.h @@ -1,294 +1,294 @@ /* This file is part of the KDE libraries Copyright (c) 2000 Waldo Bastian Copyright (C) 2002-2004 Christoph Cullmann 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. 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. 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. */ #ifndef __KATE_BUFFER_H__ #define __KATE_BUFFER_H__ #include "katetextbuffer.h" #include #include class KateLineInfo; namespace KTextEditor { class DocumentPrivate; } class KateHighlighting; /** * The KateBuffer class maintains a collections of lines. * * @author Waldo Bastian * @author Christoph Cullmann */ class KTEXTEDITOR_EXPORT KateBuffer : public Kate::TextBuffer { Q_OBJECT public: /** * Create an empty buffer. * @param doc parent document */ explicit KateBuffer(KTextEditor::DocumentPrivate *doc); /** * Goodbye buffer */ - ~KateBuffer() Q_DECL_OVERRIDE; + ~KateBuffer() override; public: /** * start some editing action */ void editStart(); /** * finish some editing action */ void editEnd(); /** * were there changes in the current running * editing session? * @return changes done? */ inline bool editChanged() const { return editingChangedBuffer(); } /** * dirty lines start * @return start line */ inline int editTagStart() const { return editingMinimalLineChanged(); } /** * dirty lines end * @return end line */ inline int editTagEnd() const { return editingMaximalLineChanged(); } /** * line inserted/removed? * @return line inserted/removed? */ inline bool editTagFrom() const { return editingChangedNumberOfLines() != 0; } public: /** * Clear the buffer. */ - void clear() Q_DECL_OVERRIDE; + void clear() override; /** * Open a file, use the given filename * @param m_file filename to open * @param enforceTextCodec enforce to use only the set text codec * @return success */ bool openFile(const QString &m_file, bool enforceTextCodec); /** * Did encoding errors occur on load? * @return encoding errors occurred on load? */ bool brokenEncoding() const { return m_brokenEncoding; } /** * Too long lines wrapped on load? * @return too long lines wrapped on load? */ bool tooLongLinesWrapped() const { return m_tooLongLinesWrapped; } int longestLineLoaded() const { return m_longestLineLoaded; } /** * Can the current codec handle all chars * @return chars can be encoded */ bool canEncode(); /** * Save the buffer to a file, use the given filename + codec + end of line chars (internal use of qtextstream) * @param m_file filename to save to * @return success */ bool saveFile(const QString &m_file); public: /** * Return line @p lineno. * Highlighting of returned line might be out-dated, which may be sufficient * for pure text manipulation functions, like search/replace. * If you require highlighting to be up to date, call @ref ensureHighlighted * prior to this method. */ inline Kate::TextLine plainLine(int lineno) { if (lineno < 0 || lineno >= lines()) { return Kate::TextLine(); } return line(lineno); } /** * Update highlighting of given line @p line, if needed. * If @p line is already highlighted, this function does nothing. * If @p line is not highlighted, all lines up to line + lookAhead * are highlighted. * @param lookAhead also highlight these following lines */ void ensureHighlighted(int line, int lookAhead = 64); /** * Return the total number of lines in the buffer. */ inline int count() const { return lines(); } /** * Unwrap given line. * @param line line to unwrap */ - void unwrapLine(int line) Q_DECL_OVERRIDE; + void unwrapLine(int line) override; /** * Wrap line at given cursor position. * @param position line/column as cursor where to wrap */ - void wrapLine(const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; + void wrapLine(const KTextEditor::Cursor &position) override; public: inline int tabWidth() const { return m_tabWidth; } public: void setTabWidth(int w); /** * Use @p highlight for highlighting * * @p highlight may be 0 in which case highlighting * will be disabled. */ void setHighlight(int hlMode); KateHighlighting *highlight() { return m_highlight; } /** * Invalidate highlighting of whole buffer. */ void invalidateHighlighting(); /** * For a given line, compute the folding range that starts there * to be used to fold e.g. from the icon border * @param startLine start line * @return folding range starting at the given line or invalid range */ KTextEditor::Range computeFoldingRangeForStartLine(int startLine); private: /** * Highlight information needs to be updated. * * @param from first line in range * @param to last line in range * @param invalidate should the rehighlighted lines be tagged? */ void doHighlight(int from, int to, bool invalidate); Q_SIGNALS: /** * Emitted when the highlighting of a certain range has * changed. */ void tagLines(int start, int end); void respellCheckBlock(int start, int end); private: /** * document we belong to */ KTextEditor::DocumentPrivate *const m_doc; /** * file loaded with encoding problems? */ bool m_brokenEncoding; /** * too long lines wrapped on load? */ bool m_tooLongLinesWrapped; /** * length of the longest line loaded */ int m_longestLineLoaded; /** * current highlighting mode or 0 */ KateHighlighting *m_highlight; // for the scrapty indent sensitive langs int m_tabWidth; /** * last line with valid highlighting */ int m_lineHighlighted; /** * number of dynamic contexts causing a full invalidation */ int m_maxDynamicContexts; }; #endif diff --git a/src/document/katedocument.h b/src/document/katedocument.h index be771a16..fa05c2b3 100644 --- a/src/document/katedocument.h +++ b/src/document/katedocument.h @@ -1,1414 +1,1414 @@ /* This file is part of the KDE libraries Copyright (C) 2001-2004 Christoph Cullmann Copyright (C) 2001 Joseph Wenninger Copyright (C) 1999 Jochen Wilhelmy Copyright (C) 2006 Hamish Rodda This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. 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. 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. */ #ifndef _KATE_DOCUMENT_H_ #define _KATE_DOCUMENT_H_ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "katetextline.h" class KateTemplateHandler; namespace KTextEditor { class Plugin; class Attribute; class TemplateScript; } namespace KIO { class TransferJob; } namespace Kate { class SwapFile; } class KateBuffer; namespace KTextEditor { class ViewPrivate; } class KateDocumentConfig; class KateHighlighting; class KateUndoManager; class KateOnTheFlyChecker; class KateDocumentTest; class KateAutoIndent; class KateModOnHdPrompt; /** * @brief Backend of KTextEditor::Document related public KTextEditor interfaces. * * @warning This file is @e private API and not part of the public * KTextEditor interfaces. */ class KTEXTEDITOR_EXPORT KTextEditor::DocumentPrivate : public KTextEditor::Document, public KTextEditor::MarkInterface, public KTextEditor::ModificationInterface, public KTextEditor::ConfigInterface, public KTextEditor::AnnotationInterface, public KTextEditor::MovingInterface, private KTextEditor::MovingRangeFeedback { Q_OBJECT Q_INTERFACES(KTextEditor::MarkInterface) Q_INTERFACES(KTextEditor::ModificationInterface) Q_INTERFACES(KTextEditor::AnnotationInterface) Q_INTERFACES(KTextEditor::ConfigInterface) Q_INTERFACES(KTextEditor::MovingInterface) friend class KTextEditor::Document; friend class ::KateDocumentTest; friend class ::KateBuffer; public: explicit DocumentPrivate(bool bSingleViewMode = false, bool bReadOnly = false, QWidget *parentWidget = nullptr, QObject * = nullptr); - ~DocumentPrivate() Q_DECL_OVERRIDE; + ~DocumentPrivate() override; using ReadWritePart::closeUrl; - bool closeUrl() Q_DECL_OVERRIDE; + bool closeUrl() override; - bool openUrl(const QUrl &url) Q_DECL_OVERRIDE; + bool openUrl(const QUrl &url) override; KTextEditor::Range rangeOnLine(KTextEditor::Range range, int line) const; private: void showAndSetOpeningErrorAccess(); /* * Overload this to have on-demand view creation */ public: /** * @return The widget defined by this part, set by setWidget(). */ - QWidget *widget() Q_DECL_OVERRIDE; + QWidget *widget() override; public: bool readOnly() const { return m_bReadOnly; } bool singleViewMode() const { return m_bSingleViewMode; } private: // only to make part work, don't change it ! const bool m_bSingleViewMode; const bool m_bReadOnly; // // KTextEditor::Document stuff // public: - KTextEditor::View *createView(QWidget *parent, KTextEditor::MainWindow *mainWindow = nullptr) Q_DECL_OVERRIDE; + KTextEditor::View *createView(QWidget *parent, KTextEditor::MainWindow *mainWindow = nullptr) override; - QList views() const Q_DECL_OVERRIDE + QList views() const override { return m_viewsCache; } virtual KTextEditor::View *activeView() const { return m_activeView; } private: QHash m_views; KTextEditor::View *m_activeView = nullptr; // // KTextEditor::EditInterface stuff // public Q_SLOTS: - bool setText(const QString &) Q_DECL_OVERRIDE; - bool setText(const QStringList &text) Q_DECL_OVERRIDE; - bool clear() Q_DECL_OVERRIDE; + bool setText(const QString &) override; + bool setText(const QStringList &text) override; + bool clear() override; - bool insertText(const KTextEditor::Cursor &position, const QString &s, bool block = false) Q_DECL_OVERRIDE; - bool insertText(const KTextEditor::Cursor &position, const QStringList &text, bool block = false) Q_DECL_OVERRIDE; + bool insertText(const KTextEditor::Cursor &position, const QString &s, bool block = false) override; + bool insertText(const KTextEditor::Cursor &position, const QStringList &text, bool block = false) override; - bool insertLine(int line, const QString &s) Q_DECL_OVERRIDE; - bool insertLines(int line, const QStringList &s) Q_DECL_OVERRIDE; + bool insertLine(int line, const QString &s) override; + bool insertLines(int line, const QStringList &s) override; - bool removeText(const KTextEditor::Range &range, bool block = false) Q_DECL_OVERRIDE; - bool removeLine(int line) Q_DECL_OVERRIDE; + bool removeText(const KTextEditor::Range &range, bool block = false) override; + bool removeLine(int line) override; - bool replaceText(const KTextEditor::Range &range, const QString &s, bool block = false) Q_DECL_OVERRIDE; + bool replaceText(const KTextEditor::Range &range, const QString &s, bool block = false) override; // unhide method... - bool replaceText(const KTextEditor::Range &r, const QStringList &l, bool b) Q_DECL_OVERRIDE + bool replaceText(const KTextEditor::Range &r, const QStringList &l, bool b) override { return KTextEditor::Document::replaceText(r, l, b); } public: - bool isEditingTransactionRunning() const Q_DECL_OVERRIDE; - QString text(const KTextEditor::Range &range, bool blockwise = false) const Q_DECL_OVERRIDE; - QStringList textLines(const KTextEditor::Range &range, bool block = false) const Q_DECL_OVERRIDE; - QString text() const Q_DECL_OVERRIDE; - QString line(int line) const Q_DECL_OVERRIDE; - QChar characterAt(const KTextEditor::Cursor &position) const Q_DECL_OVERRIDE; - QString wordAt(const KTextEditor::Cursor &cursor) const Q_DECL_OVERRIDE; - KTextEditor::Range wordRangeAt(const KTextEditor::Cursor &cursor) const Q_DECL_OVERRIDE; - bool isValidTextPosition(const KTextEditor::Cursor& cursor) const Q_DECL_OVERRIDE; - int lines() const Q_DECL_OVERRIDE; - bool isLineModified(int line) const Q_DECL_OVERRIDE; - bool isLineSaved(int line) const Q_DECL_OVERRIDE; - bool isLineTouched(int line) const Q_DECL_OVERRIDE; - KTextEditor::Cursor documentEnd() const Q_DECL_OVERRIDE; - int totalCharacters() const Q_DECL_OVERRIDE; - int lineLength(int line) const Q_DECL_OVERRIDE; + bool isEditingTransactionRunning() const override; + QString text(const KTextEditor::Range &range, bool blockwise = false) const override; + QStringList textLines(const KTextEditor::Range &range, bool block = false) const override; + QString text() const override; + QString line(int line) const override; + QChar characterAt(const KTextEditor::Cursor &position) const override; + QString wordAt(const KTextEditor::Cursor &cursor) const override; + KTextEditor::Range wordRangeAt(const KTextEditor::Cursor &cursor) const override; + bool isValidTextPosition(const KTextEditor::Cursor& cursor) const override; + int lines() const override; + bool isLineModified(int line) const override; + bool isLineSaved(int line) const override; + bool isLineTouched(int line) const override; + KTextEditor::Cursor documentEnd() const override; + int totalCharacters() const override; + int lineLength(int line) const override; Q_SIGNALS: void charactersSemiInteractivelyInserted(const KTextEditor::Cursor &position, const QString &text); /** * The \p document emits this signal whenever text was inserted. The * insertion occurred at range.start(), and new text now occupies up to * range.end(). * \param document document which emitted this signal * \param range range that the newly inserted text occupies * \see insertText(), insertLine() */ void textInserted(KTextEditor::Document *document, const KTextEditor::Range &range); /** * The \p document emits this signal whenever \p range was removed, i.e. * text was removed. * \param document document which emitted this signal * \param range range that the removed text previously occupied * \param oldText the text that has been removed * \see removeText(), removeLine(), clear() */ void textRemoved(KTextEditor::Document *document, const KTextEditor::Range &range, const QString &oldText); public: //BEGIN editStart/editEnd (start, end, undo, cursor update, view update) /** * Enclose editor actions with @p editStart() and @p editEnd() to group * them. */ bool editStart(); /** * Alias for @p editStart() */ void editBegin() { editStart(); } /** * End a editor operation. * @see editStart() */ bool editEnd(); void pushEditState(); void popEditState(); virtual bool startEditing() { return editStart(); } virtual bool finishEditing() { return editEnd(); } //END editStart/editEnd void inputMethodStart(); void inputMethodEnd(); //BEGIN LINE BASED INSERT/REMOVE STUFF (editStart() and editEnd() included) /** * Add a string in the given line/column * @param line line number * @param col column * @param s string to be inserted * @return true on success */ bool editInsertText(int line, int col, const QString &s); /** * Remove a string in the given line/column * @param line line number * @param col column * @param len length of text to be removed * @return true on success */ bool editRemoveText(int line, int col, int len); /** * Mark @p line as @p autowrapped. This is necessary if static word warp is * enabled, because we have to know whether to insert a new line or add the * wrapped words to the followin line. * @param line line number * @param autowrapped autowrapped? * @return true on success */ bool editMarkLineAutoWrapped(int line, bool autowrapped); /** * Wrap @p line. If @p newLine is true, ignore the textline's flag * KateTextLine::flagAutoWrapped and force a new line. Whether a new line * was needed/added you can grab with @p newLineAdded. * @param line line number * @param col column * @param newLine if true, force a new line * @param newLineAdded return value is true, if new line was added (may be 0) * @return true on success */ bool editWrapLine(int line, int col, bool newLine = true, bool *newLineAdded = nullptr); /** * Unwrap @p line. If @p removeLine is true, we force to join the lines. If * @p removeLine is true, @p length is ignored (eg not needed). * @param line line number * @param removeLine if true, force to remove the next line * @return true on success */ bool editUnWrapLine(int line, bool removeLine = true, int length = 0); /** * Insert a string at the given line. * @param line line number * @param s string to insert * @return true on success */ bool editInsertLine(int line, const QString &s); /** * Remove a line * @param line line number * @return true on success */ bool editRemoveLine(int line); bool editRemoveLines(int from, int to); /** * Remove a line * @param startLine line to begin wrapping * @param endLine line to stop wrapping * @return true on success */ bool wrapText(int startLine, int endLine); //END LINE BASED INSERT/REMOVE STUFF Q_SIGNALS: /** * Emmitted when text from @p line was wrapped at position pos onto line @p nextLine. */ void editLineWrapped(int line, int col, int len); /** * Emitted each time text from @p nextLine was upwrapped onto @p line. */ void editLineUnWrapped(int line, int col); public: bool isEditRunning() const; void setUndoMergeAllEdits(bool merge); enum EditingPositionKind { Previous, Next }; /** *Returns the next or previous position cursor in this document from the stack depending on the argument passed. *@return cursor invalid if m_editingStack empty */ KTextEditor::Cursor lastEditingPosition(EditingPositionKind nextOrPrevious, KTextEditor::Cursor); private: int editSessionNumber = 0; QStack editStateStack; bool editIsRunning = false; bool m_undoMergeAllEdits = false; QStack> m_editingStack; int m_editingStackPosition = -1; static const int s_editingStackSizeLimit = 32; // // KTextEditor::UndoInterface stuff // public Q_SLOTS: void undo(); void redo(); /** * Removes all the elements in m_editingStack of the respective document. */ void clearEditingPosStack(); /** * Saves the editing positions into the stack. * If the consecutive editings happens in the same line, then remove * the previous and add the new one with updated column no. */ void saveEditingPositions(KTextEditor::Document *, const KTextEditor::Range &range); public: uint undoCount() const; uint redoCount() const; KateUndoManager *undoManager() { return m_undoManager; } protected: KateUndoManager *const m_undoManager; Q_SIGNALS: void undoChanged(); public: QVector searchText( const KTextEditor::Range &range, const QString &pattern, const KTextEditor::SearchOptions options) const; private: /** * Return a widget suitable to be used as a dialog parent. */ QWidget *dialogParent(); /* * Access to the mode/highlighting subsystem */ public: /** * @copydoc KTextEditor::Document::defaultStyleAt() */ - KTextEditor::DefaultStyle defaultStyleAt(const KTextEditor::Cursor &position) const Q_DECL_OVERRIDE; + KTextEditor::DefaultStyle defaultStyleAt(const KTextEditor::Cursor &position) const override; /** * Return the name of the currently used mode * \return name of the used mode */ - QString mode() const Q_DECL_OVERRIDE; + QString mode() const override; /** * Return the name of the currently used mode * \return name of the used mode */ - QString highlightingMode() const Q_DECL_OVERRIDE; + QString highlightingMode() const override; /** * Return a list of the names of all possible modes * \return list of mode names */ - QStringList modes() const Q_DECL_OVERRIDE; + QStringList modes() const override; /** * Return a list of the names of all possible modes * \return list of mode names */ - QStringList highlightingModes() const Q_DECL_OVERRIDE; + QStringList highlightingModes() const override; /** * Set the current mode of the document by giving its name * \param name name of the mode to use for this document * \return \e true on success, otherwise \e false */ - bool setMode(const QString &name) Q_DECL_OVERRIDE; + bool setMode(const QString &name) override; /** * Set the current mode of the document by giving its name * \param name name of the mode to use for this document * \return \e true on success, otherwise \e false */ - bool setHighlightingMode(const QString &name) Q_DECL_OVERRIDE; + bool setHighlightingMode(const QString &name) override; /** * Returns the name of the section for a highlight given its @p index in the highlight * list (as returned by highlightModes()). * You can use this function to build a tree of the highlight names, organized in sections. * \param index in the highlight list for which to find the section name. */ - QString highlightingModeSection(int index) const Q_DECL_OVERRIDE; + QString highlightingModeSection(int index) const override; /** * Returns the name of the section for a mode given its @p index in the highlight * list (as returned by modes()). * You can use this function to build a tree of the mode names, organized in sections. * \param index index in the highlight list for which to find the section name. */ - QString modeSection(int index) const Q_DECL_OVERRIDE; + QString modeSection(int index) const override; /* * Helpers.... */ public: void bufferHlChanged(); /** * allow to mark, that we changed hl on user wish and should not reset it * atm used for the user visible menu to select highlightings */ void setDontChangeHlOnSave(); /** * Set that the BOM marker is forced via the tool menu */ void bomSetByUser(); public: /** * Read session settings from the given \p config. * * Known flags: * "SkipUrl" => don't save/restore the file * "SkipMode" => don't save/restore the mode * "SkipHighlighting" => don't save/restore the highlighting * "SkipEncoding" => don't save/restore the encoding * * \param config read the session settings from this KConfigGroup * \param flags additional flags * \see writeSessionConfig() */ - void readSessionConfig(const KConfigGroup &config, const QSet &flags = QSet()) Q_DECL_OVERRIDE; + void readSessionConfig(const KConfigGroup &config, const QSet &flags = QSet()) override; /** * Write session settings to the \p config. * See readSessionConfig() for more details. * * \param config write the session settings to this KConfigGroup * \param flags additional flags * \see readSessionConfig() */ - void writeSessionConfig(KConfigGroup &config, const QSet &flags = QSet()) Q_DECL_OVERRIDE; + void writeSessionConfig(KConfigGroup &config, const QSet &flags = QSet()) override; Q_SIGNALS: void configChanged(); // // KTextEditor::MarkInterface // public Q_SLOTS: - void setMark(int line, uint markType) Q_DECL_OVERRIDE; - void clearMark(int line) Q_DECL_OVERRIDE; + void setMark(int line, uint markType) override; + void clearMark(int line) override; - void addMark(int line, uint markType) Q_DECL_OVERRIDE; - void removeMark(int line, uint markType) Q_DECL_OVERRIDE; + void addMark(int line, uint markType) override; + void removeMark(int line, uint markType) override; - void clearMarks() Q_DECL_OVERRIDE; + void clearMarks() override; void requestMarkTooltip(int line, QPoint position); ///Returns true if the click on the mark should not be further processed bool handleMarkClick(int line); ///Returns true if the context-menu event should not further be processed bool handleMarkContextMenu(int line, QPoint position); - void setMarkPixmap(MarkInterface::MarkTypes, const QPixmap &) Q_DECL_OVERRIDE; + void setMarkPixmap(MarkInterface::MarkTypes, const QPixmap &) override; - void setMarkDescription(MarkInterface::MarkTypes, const QString &) Q_DECL_OVERRIDE; + void setMarkDescription(MarkInterface::MarkTypes, const QString &) override; - void setEditableMarks(uint markMask) Q_DECL_OVERRIDE; + void setEditableMarks(uint markMask) override; public: - uint mark(int line) Q_DECL_OVERRIDE; - const QHash &marks() Q_DECL_OVERRIDE; - QPixmap markPixmap(MarkInterface::MarkTypes) const Q_DECL_OVERRIDE; - QString markDescription(MarkInterface::MarkTypes) const Q_DECL_OVERRIDE; + uint mark(int line) override; + const QHash &marks() override; + QPixmap markPixmap(MarkInterface::MarkTypes) const override; + QString markDescription(MarkInterface::MarkTypes) const override; virtual QColor markColor(MarkInterface::MarkTypes) const; - uint editableMarks() const Q_DECL_OVERRIDE; + uint editableMarks() const override; Q_SIGNALS: void markToolTipRequested(KTextEditor::Document *document, KTextEditor::Mark mark, QPoint position, bool &handled); void markContextMenuRequested(KTextEditor::Document *document, KTextEditor::Mark mark, QPoint pos, bool &handled); void markClicked(KTextEditor::Document *document, KTextEditor::Mark mark, bool &handled); - void marksChanged(KTextEditor::Document *) Q_DECL_OVERRIDE; - void markChanged(KTextEditor::Document *, KTextEditor::Mark, KTextEditor::MarkInterface::MarkChangeAction) Q_DECL_OVERRIDE; + void marksChanged(KTextEditor::Document *) override; + void markChanged(KTextEditor::Document *, KTextEditor::Mark, KTextEditor::MarkInterface::MarkChangeAction) override; private: QHash m_marks; QHash m_markPixmaps; QHash m_markDescriptions; uint m_editableMarks = markType01; // KTextEditor::PrintInterface // public Q_SLOTS: - bool print() Q_DECL_OVERRIDE; - void printPreview() Q_DECL_OVERRIDE; + bool print() override; + void printPreview() override; // // KTextEditor::DocumentInfoInterface ( ### unfinished ) // public: /** * Tries to detect mime-type based on file name and content of buffer. * * @return the name of the mimetype for the document. */ - QString mimeType() Q_DECL_OVERRIDE; + QString mimeType() override; // // once was KTextEditor::VariableInterface // public: /** * Returns the value for the variable @p name. * If the Document does not have a variable called @p name, * an empty QString() is returned. * * @param name variable to query * @return value of the variable @p name * @see setVariable() */ virtual QString variable(const QString &name) const; /** * Set the variable @p name to @p value. Setting and changing a variable * has immediate effect on the Document. For instance, setting the variable * @e indent-mode to @e cstyle will immediately cause the Document to load * the C Style indenter. * * @param name the variable name * @param value the value to be set * @see variable() */ virtual void setVariable(const QString &name, const QString &value); private: QMap m_storedVariables; // // MovingInterface API // public: /** * Create a new moving cursor for this document. * @param position position of the moving cursor to create * @param insertBehavior insertion behavior * @return new moving cursor for the document */ - KTextEditor::MovingCursor *newMovingCursor(const KTextEditor::Cursor &position, KTextEditor::MovingCursor::InsertBehavior insertBehavior = KTextEditor::MovingCursor::MoveOnInsert) Q_DECL_OVERRIDE; + KTextEditor::MovingCursor *newMovingCursor(const KTextEditor::Cursor &position, KTextEditor::MovingCursor::InsertBehavior insertBehavior = KTextEditor::MovingCursor::MoveOnInsert) override; /** * Create a new moving range for this document. * @param range range of the moving range to create * @param insertBehaviors insertion behaviors * @param emptyBehavior behavior on becoming empty * @return new moving range for the document */ KTextEditor::MovingRange *newMovingRange(const KTextEditor::Range &range, KTextEditor::MovingRange::InsertBehaviors insertBehaviors = KTextEditor::MovingRange::DoNotExpand - , KTextEditor::MovingRange::EmptyBehavior emptyBehavior = KTextEditor::MovingRange::AllowEmpty) Q_DECL_OVERRIDE; + , KTextEditor::MovingRange::EmptyBehavior emptyBehavior = KTextEditor::MovingRange::AllowEmpty) override; /** * Current revision * @return current revision */ - qint64 revision() const Q_DECL_OVERRIDE; + qint64 revision() const override; /** * Last revision the buffer got successful saved * @return last revision buffer got saved, -1 if none */ - qint64 lastSavedRevision() const Q_DECL_OVERRIDE; + qint64 lastSavedRevision() const override; /** * Lock a revision, this will keep it around until released again. * But all revisions will always be cleared on buffer clear() (and therefor load()) * @param revision revision to lock */ - void lockRevision(qint64 revision) Q_DECL_OVERRIDE; + void lockRevision(qint64 revision) override; /** * Release a revision. * @param revision revision to release */ - void unlockRevision(qint64 revision) Q_DECL_OVERRIDE; + void unlockRevision(qint64 revision) override; /** * Transform a cursor from one revision to an other. * @param cursor cursor to transform * @param insertBehavior behavior of this cursor on insert of text at its position * @param fromRevision from this revision we want to transform * @param toRevision to this revision we want to transform, default of -1 is current revision */ - void transformCursor(KTextEditor::Cursor &cursor, KTextEditor::MovingCursor::InsertBehavior insertBehavior, qint64 fromRevision, qint64 toRevision = -1) Q_DECL_OVERRIDE; + void transformCursor(KTextEditor::Cursor &cursor, KTextEditor::MovingCursor::InsertBehavior insertBehavior, qint64 fromRevision, qint64 toRevision = -1) override; /** * Transform a cursor from one revision to an other. * @param line line number of the cursor to transform * @param column column number of the cursor to transform * @param insertBehavior behavior of this cursor on insert of text at its position * @param fromRevision from this revision we want to transform * @param toRevision to this revision we want to transform, default of -1 is current revision */ - void transformCursor(int &line, int &column, KTextEditor::MovingCursor::InsertBehavior insertBehavior, qint64 fromRevision, qint64 toRevision = -1) Q_DECL_OVERRIDE; + void transformCursor(int &line, int &column, KTextEditor::MovingCursor::InsertBehavior insertBehavior, qint64 fromRevision, qint64 toRevision = -1) override; /** * Transform a range from one revision to an other. * @param range range to transform * @param insertBehaviors behavior of this range on insert of text at its position * @param emptyBehavior behavior on becoming empty * @param fromRevision from this revision we want to transform * @param toRevision to this revision we want to transform, default of -1 is current revision */ - void transformRange(KTextEditor::Range &range, KTextEditor::MovingRange::InsertBehaviors insertBehaviors, KTextEditor::MovingRange::EmptyBehavior emptyBehavior, qint64 fromRevision, qint64 toRevision = -1) Q_DECL_OVERRIDE; + void transformRange(KTextEditor::Range &range, KTextEditor::MovingRange::InsertBehaviors insertBehaviors, KTextEditor::MovingRange::EmptyBehavior emptyBehavior, qint64 fromRevision, qint64 toRevision = -1) override; // // MovingInterface Signals // Q_SIGNALS: /** * This signal is emitted before the cursors/ranges/revisions of a document are destroyed as the document is deleted. * @param document the document which the interface belongs too which is in the process of being deleted */ void aboutToDeleteMovingInterfaceContent(KTextEditor::Document *document); /** * This signal is emitted before the ranges of a document are invalidated and the revisions are deleted as the document is cleared (for example on load/reload). * While this signal is emitted, still the old document content is around before the clear. * @param document the document which the interface belongs too which will invalidate its data */ void aboutToInvalidateMovingInterfaceContent(KTextEditor::Document *document); // // Annotation Interface // public: - void setAnnotationModel(KTextEditor::AnnotationModel *model) Q_DECL_OVERRIDE; - KTextEditor::AnnotationModel *annotationModel() const Q_DECL_OVERRIDE; + void setAnnotationModel(KTextEditor::AnnotationModel *model) override; + KTextEditor::AnnotationModel *annotationModel() const override; Q_SIGNALS: void annotationModelChanged(KTextEditor::AnnotationModel *, KTextEditor::AnnotationModel *); private: KTextEditor::AnnotationModel *m_annotationModel = nullptr; // // KParts::ReadWrite stuff // public: /** * open the file obtained by the kparts framework * the framework abstracts the loading of remote files * @return success */ - bool openFile() Q_DECL_OVERRIDE; + bool openFile() override; /** * save the file obtained by the kparts framework * the framework abstracts the uploading of remote files * @return success */ - bool saveFile() Q_DECL_OVERRIDE; + bool saveFile() override; - void setReadWrite(bool rw = true) Q_DECL_OVERRIDE; + void setReadWrite(bool rw = true) override; - void setModified(bool m) Q_DECL_OVERRIDE; + void setModified(bool m) override; private: void activateDirWatch(const QString &useFileName = QString()); void deactivateDirWatch(); QString m_dirWatchFile; /** * Make backup copy during saveFile, if configured that way. * @return success? else saveFile should return false and not write the file */ bool createBackupFile(); public: /** * Type chars in a view. * Will filter out non-printable chars from the realChars array before inserting. */ bool typeChars(KTextEditor::ViewPrivate *type, const QString &realChars); /** * gets the last line number (lines() - 1) */ inline int lastLine() const { return lines() - 1; } // Repaint all of all of the views void repaintViews(bool paintOnlyDirty = true); KateHighlighting *highlight() const; public Q_SLOTS: void tagLines(int start, int end); private Q_SLOTS: void internalHlChanged(); public: void addView(KTextEditor::View *); /** removes the view from the list of views. The view is *not* deleted. * That's your job. Or, easier, just delete the view in the first place. * It will remove itself. TODO: this could be converted to a private slot * connected to the view's destroyed() signal. It is not currently called * anywhere except from the KTextEditor::ViewPrivate destructor. */ void removeView(KTextEditor::View *); void setActiveView(KTextEditor::View *); bool ownedView(KTextEditor::ViewPrivate *); int toVirtualColumn(int line, int column) const; int toVirtualColumn(const KTextEditor::Cursor &) const; int fromVirtualColumn(int line, int column) const; int fromVirtualColumn(const KTextEditor::Cursor &) const; void newLine(KTextEditor::ViewPrivate *view); // Changes input void backspace(KTextEditor::ViewPrivate *view, const KTextEditor::Cursor &); void del(KTextEditor::ViewPrivate *view, const KTextEditor::Cursor &); void transpose(const KTextEditor::Cursor &); void paste(KTextEditor::ViewPrivate *view, const QString &text); public: void indent(KTextEditor::Range range, int change); void comment(KTextEditor::ViewPrivate *view, uint line, uint column, int change); void align(KTextEditor::ViewPrivate *view, const KTextEditor::Range &range); void insertTab(KTextEditor::ViewPrivate *view, const KTextEditor::Cursor &); enum TextTransform { Uppercase, Lowercase, Capitalize }; /** Handling uppercase, lowercase and capitalize for the view. If there is a selection, that is transformed, otherwise for uppercase or lowercase the character right of the cursor is transformed, for capitalize the word under the cursor is transformed. */ void transform(KTextEditor::ViewPrivate *view, const KTextEditor::Cursor &, TextTransform); /** Unwrap a range of lines. */ void joinLines(uint first, uint last); private: bool removeStringFromBeginning(int line, const QString &str); bool removeStringFromEnd(int line, const QString &str); /** Expand tabs to spaces in typed text, if enabled. @param cursorPos The current cursor position for the inserted characters. @param str The typed characters to expand. */ QString eventuallyReplaceTabs(const KTextEditor::Cursor &cursorPos, const QString &str) const; /** Find the position (line and col) of the next char that is not a space. If found line and col point to the found character. Otherwise they have both the value -1. @param line Line of the character which is examined first. @param col Column of the character which is examined first. @return True if the specified or a following character is not a space Otherwise false. */ bool nextNonSpaceCharPos(int &line, int &col); /** Find the position (line and col) of the previous char that is not a space. If found line and col point to the found character. Otherwise they have both the value -1. @return True if the specified or a preceding character is not a space. Otherwise false. */ bool previousNonSpaceCharPos(int &line, int &col); /** * Sets a comment marker as defined by the language providing the attribute * @p attrib on the line @p line */ void addStartLineCommentToSingleLine(int line, int attrib = 0); /** * Removes a comment marker as defined by the language providing the attribute * @p attrib on the line @p line */ bool removeStartLineCommentFromSingleLine(int line, int attrib = 0); /** * @see addStartLineCommentToSingleLine. */ void addStartStopCommentToSingleLine(int line, int attrib = 0); /** *@see removeStartLineCommentFromSingleLine. */ bool removeStartStopCommentFromSingleLine(int line, int attrib = 0); /** *@see removeStartLineCommentFromSingleLine. */ bool removeStartStopCommentFromRegion(const KTextEditor::Cursor &start, const KTextEditor::Cursor &end, int attrib = 0); /** * Add a comment marker as defined by the language providing the attribute * @p attrib to each line in the selection. */ void addStartStopCommentToSelection(KTextEditor::ViewPrivate *view, int attrib = 0); /** * @see addStartStopCommentToSelection. */ void addStartLineCommentToSelection(KTextEditor::ViewPrivate *view, int attrib = 0); /** * Removes comment markers relevant to the language providing * the attribuge @p attrib from each line in the selection. * * @return whether the operation succeeded. */ bool removeStartStopCommentFromSelection(KTextEditor::ViewPrivate *view, int attrib = 0); /** * @see removeStartStopCommentFromSelection. */ bool removeStartLineCommentFromSelection(KTextEditor::ViewPrivate *view, int attrib = 0); public: KTextEditor::Range findMatchingBracket(const KTextEditor::Cursor & start, int maxLines); public: - QString documentName() const Q_DECL_OVERRIDE + QString documentName() const override { return m_docName; } private: void updateDocName(); public: /** * @return whether the document is modified on disk since last saved */ bool isModifiedOnDisc() { return m_modOnHd; } - void setModifiedOnDisk(ModifiedOnDiskReason reason) Q_DECL_OVERRIDE; + void setModifiedOnDisk(ModifiedOnDiskReason reason) override; - void setModifiedOnDiskWarning(bool on) Q_DECL_OVERRIDE; + void setModifiedOnDiskWarning(bool on) override; public Q_SLOTS: /** * Ask the user what to do, if the file has been modified on disk. * Reimplemented from KTextEditor::Document. */ virtual void slotModifiedOnDisk(KTextEditor::View *v = nullptr); /** * Reloads the current document from disk if possible */ - bool documentReload() Q_DECL_OVERRIDE; + bool documentReload() override; - bool documentSave() Q_DECL_OVERRIDE; - bool documentSaveAs() Q_DECL_OVERRIDE; + bool documentSave() override; + bool documentSaveAs() override; bool documentSaveAsWithEncoding(const QString &encoding); bool documentSaveCopyAs(); - bool save() Q_DECL_OVERRIDE; + bool save() override; public: - bool saveAs(const QUrl &url) Q_DECL_OVERRIDE; + bool saveAs(const QUrl &url) override; Q_SIGNALS: /** * Indicate this file is modified on disk * @param doc the KTextEditor::Document object that represents the file on disk * @param isModified indicates the file was modified rather than created or deleted * @param reason the reason we are emitting the signal. */ - void modifiedOnDisk(KTextEditor::Document *doc, bool isModified, KTextEditor::ModificationInterface::ModifiedOnDiskReason reason) Q_DECL_OVERRIDE; + void modifiedOnDisk(KTextEditor::Document *doc, bool isModified, KTextEditor::ModificationInterface::ModifiedOnDiskReason reason) override; private: // helper to handle the embedded notification for externally modified files QPointer m_modOnHdHandler; private Q_SLOTS: void onModOnHdSaveAs(); void onModOnHdReload(); void onModOnHdIgnore(); public: - bool setEncoding(const QString &e) Q_DECL_OVERRIDE; - QString encoding() const Q_DECL_OVERRIDE; + bool setEncoding(const QString &e) override; + QString encoding() const override; public Q_SLOTS: void setWordWrap(bool on); void setWordWrapAt(uint col); public: bool wordWrap() const; uint wordWrapAt() const; public Q_SLOTS: void setPageUpDownMovesCursor(bool on); public: bool pageUpDownMovesCursor() const; // code folding public: /** * Same as plainKateTextLine(), except that it is made sure * the line is highlighted. */ Kate::TextLine kateTextLine(int i); //! @copydoc KateBuffer::plainLine() Kate::TextLine plainKateTextLine(int i); Q_SIGNALS: void aboutToRemoveText(const KTextEditor::Range &); private Q_SLOTS: void slotModOnHdDirty(const QString &path); void slotModOnHdCreated(const QString &path); void slotModOnHdDeleted(const QString &path); void slotDelayedHandleModOnHd(); private: /** * Create a git compatible sha1 checksum of the file, if it is a local file. * The result can be accessed through KateBuffer::digest(). * * @return wheather the operation was attempted and succeeded. */ bool createDigest(); /** * create a string for the modonhd warnings, giving the reason. */ QString reasonedMOHString() const; /** * Removes all trailing whitespace in the document. */ void removeTrailingSpaces(); public: /** * Returns a git compatible sha1 checksum of this document on disk. * @return checksum for this document on disk */ - QByteArray checksum() const Q_DECL_OVERRIDE; + QByteArray checksum() const override; void updateFileType(const QString &newType, bool user = false); QString fileType() const { return m_fileType; } /** * Get access to buffer of this document. * Is needed to create cursors and ranges for example. * @return document buffer */ KateBuffer &buffer() { return *m_buffer; } /** * set indentation mode by user * this will remember that a user did set it and will avoid reset on save */ void rememberUserDidSetIndentationMode() { m_indenterSetByUser = true; } /** * User did set encoding for next reload => enforce it! */ void userSetEncodingForNextReload() { m_userSetEncodingForNextReload = true; } // // REALLY internal data ;) // private: // text buffer KateBuffer *const m_buffer; // indenter KateAutoIndent *const m_indenter; bool m_hlSetByUser = false; bool m_bomSetByUser = false; bool m_indenterSetByUser = false; bool m_userSetEncodingForNextReload = false; bool m_modOnHd = false; ModifiedOnDiskReason m_modOnHdReason = OnDiskUnmodified; ModifiedOnDiskReason m_prevModOnHdReason = OnDiskUnmodified; QString m_docName; int m_docNameNumber = 0; // file type !!! QString m_fileType; bool m_fileTypeSetByUser = false; /** * document is still reloading a file */ bool m_reloading = false; public Q_SLOTS: void slotQueryClose_save(bool *handled, bool *abortClosing); public: - bool queryClose() Q_DECL_OVERRIDE; + bool queryClose() override; void makeAttribs(bool needInvalidate = true); static bool checkOverwrite(QUrl u, QWidget *parent); /** * Configuration */ public: KateDocumentConfig *config() { return m_config; } KateDocumentConfig *config() const { return m_config; } void updateConfig(); private: KateDocumentConfig *const m_config; /** * Variable Reader * TODO add register functionality/ktexteditor interface */ private: /** * read dir config file */ void readDirConfig(); /** Reads all the variables in the document. Called when opening/saving a document */ void readVariables(bool onlyViewAndRenderer = false); /** Reads and applies the variables in a single line TODO registered variables gets saved in a [map] */ void readVariableLine(QString t, bool onlyViewAndRenderer = false); /** Sets a view variable in all the views. */ void setViewVariable(QString var, QString val); /** @return weather a string value could be converted to a bool value as supported. The value is put in *result. */ static bool checkBoolValue(QString value, bool *result); /** @return weather a string value could be converted to a integer value. The value is put in *result. */ static bool checkIntValue(QString value, int *result); /** Feeds value into @p col using QColor::setNamedColor() and returns wheather the color is valid */ static bool checkColorValue(QString value, QColor &col); bool m_fileChangedDialogsActivated = false; // // KTextEditor::ConfigInterface // public: - QStringList configKeys() const Q_DECL_OVERRIDE; - QVariant configValue(const QString &key) Q_DECL_OVERRIDE; - void setConfigValue(const QString &key, const QVariant &value) Q_DECL_OVERRIDE; + QStringList configKeys() const override; + QVariant configValue(const QString &key) override; + void setConfigValue(const QString &key, const QVariant &value) override; // // KTextEditor::RecoveryInterface // public: - bool isDataRecoveryAvailable() const Q_DECL_OVERRIDE; - void recoverData() Q_DECL_OVERRIDE; - void discardDataRecovery() Q_DECL_OVERRIDE; + bool isDataRecoveryAvailable() const override; + void recoverData() override; + void discardDataRecovery() override; // // Highlighting information // public: - QStringList embeddedHighlightingModes() const Q_DECL_OVERRIDE; - QString highlightingModeAt(const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; + QStringList embeddedHighlightingModes() const override; + QString highlightingModeAt(const KTextEditor::Cursor &position) override; // TODO KDE5: move to View virtual KTextEditor::Attribute::Ptr attributeAt(const KTextEditor::Cursor &position); // //BEGIN: KTextEditor::MessageInterface // public: - bool postMessage(KTextEditor::Message *message) Q_DECL_OVERRIDE; + bool postMessage(KTextEditor::Message *message) override; public Q_SLOTS: void messageDestroyed(KTextEditor::Message *message); private: QHash > > m_messageHash; //END KTextEditor::MessageInterface public: QString defaultDictionary() const; QList > dictionaryRanges() const; bool isOnTheFlySpellCheckingEnabled() const; QString dictionaryForMisspelledRange(const KTextEditor::Range &range) const; void clearMisspellingForWord(const QString &word); public Q_SLOTS: void clearDictionaryRanges(); void setDictionary(const QString &dict, const KTextEditor::Range &range); void revertToDefaultDictionary(const KTextEditor::Range &range); void setDefaultDictionary(const QString &dict); void onTheFlySpellCheckingEnabled(bool enable); void refreshOnTheFlyCheck(const KTextEditor::Range &range = KTextEditor::Range::invalid()); Q_SIGNALS: void dictionaryRangesPresent(bool yesNo); void defaultDictionaryChanged(KTextEditor::DocumentPrivate *document); public: bool containsCharacterEncoding(const KTextEditor::Range &range); typedef QList > OffsetList; int computePositionWrtOffsets(const OffsetList &offsetList, int pos); /** * The first OffsetList is from decoded to encoded, and the second OffsetList from * encoded to decoded. **/ QString decodeCharacters(const KTextEditor::Range &range, KTextEditor::DocumentPrivate::OffsetList &decToEncOffsetList, KTextEditor::DocumentPrivate::OffsetList &encToDecOffsetList); void replaceCharactersByEncoding(const KTextEditor::Range &range); enum EncodedCharaterInsertionPolicy {EncodeAlways, EncodeWhenPresent, EncodeNever}; protected: KateOnTheFlyChecker *m_onTheFlyChecker = nullptr; QString m_defaultDictionary; QList > m_dictionaryRanges; // from KTextEditor::MovingRangeFeedback - void rangeInvalid(KTextEditor::MovingRange *movingRange) Q_DECL_OVERRIDE; - void rangeEmpty(KTextEditor::MovingRange *movingRange) Q_DECL_OVERRIDE; + void rangeInvalid(KTextEditor::MovingRange *movingRange) override; + void rangeEmpty(KTextEditor::MovingRange *movingRange) override; void deleteDictionaryRange(KTextEditor::MovingRange *movingRange); private: Kate::SwapFile *m_swapfile; public: Kate::SwapFile *swapFile(); //helpers for scripting and codefolding int defStyleNum(int line, int column); bool isComment(int line, int column); public: /** * Find the next modified/saved line, starting at @p startLine. If @p down * is \e true, the search is performed downwards, otherwise upwards. * @return the touched line in the requested search direction, or -1 if not found */ int findTouchedLine(int startLine, bool down); private Q_SLOTS: /** * watch for all started io jobs to remember if file is perhaps loading atm * @param job started job */ void slotStarted(KIO::Job *job); void slotCompleted(); void slotCanceled(); /** * trigger display of loading message, after 1000 ms */ void slotTriggerLoadingMessage(); /** * Abort loading */ void slotAbortLoading(); void slotUrlChanged(const QUrl &url); private: /** * different possible states */ enum DocumentStates { /** * Idle */ DocumentIdle, /** * Loading */ DocumentLoading, /** * Saving */ DocumentSaving, /** * Pre Saving As, this is between ::saveAs is called and ::save */ DocumentPreSavingAs, /** * Saving As */ DocumentSavingAs }; /** * current state */ DocumentStates m_documentState = DocumentIdle; /** * read-write state before loading started */ bool m_readWriteStateBeforeLoading = false; /** * if the document is untitled */ bool m_isUntitled = true; /** * loading job, we want to cancel with cancel in the loading message */ QPointer m_loadingJob; /** * message to show during loading */ QPointer m_loadingMessage; /** * Was there any open error on last file loading? */ bool m_openingError = false; /** * Last open file error message */ QString m_openingErrorMessage; public: /** * reads the line length limit from config, if it is not overriden */ int lineLengthLimit() const; public Q_SLOTS: void openWithLineLengthLimitOverride(); private: /** * timer for delayed handling of mod on hd */ QTimer m_modOnHdTimer; private: /** * currently active template handler; there can be only one */ QPointer m_activeTemplateHandler; private: /** * current autobrace range */ QSharedPointer m_currentAutobraceRange; /** * current autobrace closing charater (e.g. ']') */ QChar m_currentAutobraceClosingChar; private Q_SLOTS: void checkCursorForAutobrace(KTextEditor::View* view, const KTextEditor::Cursor& newPos); public: void setActiveTemplateHandler(KateTemplateHandler* handler); Q_SIGNALS: void loaded(KTextEditor::DocumentPrivate *document); private Q_SLOTS: /** * trigger a close of this document in the application */ void closeDocumentInApplication(); private: // To calculate a QHash.keys() is quite expensive, // better keep a copy of that list updated when a view is added or removed. QList m_viewsCache; }; #endif diff --git a/src/export/htmlexporter.h b/src/export/htmlexporter.h index a40485a0..7cd82241 100644 --- a/src/export/htmlexporter.h +++ b/src/export/htmlexporter.h @@ -1,38 +1,38 @@ /** * This file is part of the KDE libraries * Copyright (C) 2009 Milian Wolff * * 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. * * 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. * * 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. */ #ifndef HTMLEXPORTER_H #define HTMLEXPORTER_H #include "abstractexporter.h" /// TODO: add abstract interface for future exporters class HTMLExporter : public AbstractExporter { public: HTMLExporter(KTextEditor::View *view, QTextStream &output, const bool withHeaderFooter = false); virtual ~HTMLExporter(); - void openLine() Q_DECL_OVERRIDE; - void closeLine(const bool lastLine) Q_DECL_OVERRIDE; - void exportText(const QString &text, const KTextEditor::Attribute::Ptr &attrib) Q_DECL_OVERRIDE; + void openLine() override; + void closeLine(const bool lastLine) override; + void exportText(const QString &text, const KTextEditor::Attribute::Ptr &attrib) override; }; #endif diff --git a/src/include/ktexteditor/codecompletionmodel.h b/src/include/ktexteditor/codecompletionmodel.h index 163268d4..31cb2f2a 100644 --- a/src/include/ktexteditor/codecompletionmodel.h +++ b/src/include/ktexteditor/codecompletionmodel.h @@ -1,475 +1,475 @@ /* This file is part of the KDE libraries Copyright (C) 2007-2008 David Nolden Copyright (C) 2005-2006 Hamish Rodda * * 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. * * 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. * * 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. */ #ifndef KTEXTEDITOR_CODECOMPLETIONMODEL_H #define KTEXTEDITOR_CODECOMPLETIONMODEL_H #include #include #include namespace KTextEditor { class Document; class View; /** * \short An item model for providing code completion, and meta information for * enhanced presentation. * * \section compmodel_intro Introduction * * The CodeCompletionModel is the actual workhorse to provide code completions * in a KTextEditor::View. It is meant to be used in conjunction with the * CodeCompletionInterface. The CodeCompletionModel is not meant to be used as * is. Rather you need to implement a subclass of CodeCompletionModel to actually * generate completions appropriate for your type of Document. * * \section compmodel_implementing Implementing a CodeCompletionModel * * The CodeCompletionModel is a QAbstractItemModel, and can be subclassed in the * same way. It provides default implementations of several members, however, so * in most cases (if your completions are essentially a non-hierarchical, flat list * of matches) you will only need to overload few virtual functions. * * \section compmodel_flatlist Implementing a CodeCompletionModel for a flat list * * For the simple case of a flat list of completions, you will need to: * - Implement completionInvoked() to actually generate/update the list of completion * matches * - implement itemData() (or QAbstractItemModel::data()) to return the information that * should be displayed for each match. * - use setRowCount() to reflect the number of matches. * * \section compmodel_roles_columns Columns and roles * * \todo document the meaning and usage of the columns and roles used by the * CodeCompletionInterface * * \section compmodel_usage Using the new CodeCompletionModel * * To start using your CodeCompletionModel, refer to CodeCompletionInterface. * * \section compmodel_controller ControllerInterface to get more control * * To have more control over code completion implement * CodeCompletionModelControllerInterface in your CodeCompletionModel. * * \see CodeCompletionInterface, CodeCompletionModelControllerInterface * @author Hamish Rodda */ class KTEXTEDITOR_EXPORT CodeCompletionModel : public QAbstractItemModel { Q_OBJECT public: explicit CodeCompletionModel(QObject *parent); - ~CodeCompletionModel() Q_DECL_OVERRIDE; + ~CodeCompletionModel() override; enum Columns { Prefix = 0, /// Icon representing the type of completion. We have a separate icon field /// so that names remain aligned where only some completions have icons, /// and so that they can be rearranged by the user. Icon, Scope, Name, Arguments, Postfix }; static const int ColumnCount = Postfix + 1; enum CompletionProperty { NoProperty = 0x0, FirstProperty = 0x1, // Access specifiers - no more than 1 per item Public = 0x1, Protected = 0x2, Private = 0x4, // Extra access specifiers - any number per item Static = 0x8, Const = 0x10, // Type - no more than 1 per item (except for Template) Namespace = 0x20, Class = 0x40, Struct = 0x80, Union = 0x100, Function = 0x200, Variable = 0x400, Enum = 0x800, Template = 0x1000, TypeAlias = 0x2000, // Special attributes - any number per item Virtual = 0x4000, Override = 0x8000, Inline = 0x10000, Friend = 0x20000, Signal = 0x40000, Slot = 0x80000, // Scope - no more than 1 per item LocalScope = 0x100000, NamespaceScope = 0x200000, GlobalScope = 0x400000, // Keep this in sync so the code knows when to stop LastProperty = GlobalScope }; Q_DECLARE_FLAGS(CompletionProperties, CompletionProperty) enum HighlightMethod { NoHighlighting = 0x0, InternalHighlighting = 0x1, CustomHighlighting = 0x2 }; Q_DECLARE_FLAGS(HighlightMethods, HighlightMethod) /// Meta information is passed through extra {Qt::ItemDataRole}s. /// This information should be returned when requested on the Name column. enum ExtraItemDataRoles { /// The model should return a set of CompletionProperties. CompletionRole = Qt::UserRole, /// The model should return an index to the scope /// -1 represents no scope /// \todo how to sort scope? ScopeIndex, /** * If requested, your model should try to determine whether the * completion in question is a suitable match for the context (ie. * is accessible, exported, + returns the data type required). * * The returned data should ideally be matched against the argument-hint context * set earlier by SetMatchContext. * * Return an integer value that should be positive if the completion is suitable, * and zero if the completion is not suitable. The value should be between 0 an 10, where * 10 means perfect match. * * Return QVariant::Invalid if you are unable to determine this. */ MatchQuality, /** * Is requested before MatchQuality(..) is requested. The item on which this is requested * is an argument-hint item(@see ArgumentHintDepth). When this role is requested, the item should * be noted, and whenever MatchQuality is requested, it should be computed by matching the item given * with MatchQuality into the context chosen by SetMatchContext. * * Feel free to ignore this, but ideally you should return QVariant::Invalid to make clear that your model does not support this. * */ SetMatchContext, /** * Define which highlighting method will be used: * - QVariant::Invalid - allows the editor to choose (usually internal highlighting) * - QVariant::Integer - highlight as specified by HighlightMethods. */ HighlightingMethod, /** * Allows an item to provide custom highlighting. Return a * QList\ in the following format: * - int startColumn (where 0 = start of the completion entry) * - int endColumn (note: not length) * - QTextFormat attribute (note: attribute may be a KTextEditor::Attribute, as it is a child class) * If the attribute is invalid, and the item is an argument-hint, the text will be drawn with * a background-color depending on match-quality, or yellow. * You can use that to mark the actual arguments that are matched in an argument-hint. * * Repeat this triplet as many times as required, however each column must be >= the previous, * and startColumn != endColumn. */ CustomHighlight, /** * Returns the inheritance depth of the completion. For example, a completion * which comes from the base class would have depth 0, one from a parent class * would have depth 1, one from that class' parent 2, etc. you can use this to * symbolize the general distance of a completion-item from a user. It will be used * for sorting. */ InheritanceDepth, /** * This allows items in the completion-list to be expandable. If a model returns an QVariant bool value * that evaluates to true, the completion-widget will draw a handle to expand the item, and will also make * that action accessible through keyboard. */ IsExpandable, /** * After a model returned true for a row on IsExpandable, the row may be expanded by the user. * When this happens, ExpandingWidget is requested. * * The model may return two types of values: * QWidget*: * If the model returns a QVariant of type QWidget*, the code-completion takes over the given widget * and embeds it into the completion-list under the completion-item. The widget will be automatically deleted at some point. * The completion-widget will use the height of the widget as a hint for its preferred size, but it will * resize the widget at will. * QString: * If the mode returns a QVariant of type QString, it will create a small html-widget showing the given html-code, * and embed it into the completion-list under the completion-item. * * Warning: * QWidget* widget; * return QVariant(widget); * Will not work correctly! * Use the following instead.: * QVariant v; * v.setValue(widget); * return v; * * */ ExpandingWidget, /** * Whenever an item is selected, this will be requested from the underlying model. * It may be used as a simple notification that the item was selected. * * Above that, the model may return a QString, which then should then contain html-code. A html-widget * will then be displayed as a one- or two-liner under the currently selected item(it will be partially expanded) * */ ItemSelected, /**Is this completion-item an argument-hint? * The model should return an integral positive number if the item is an argument-hint, and QVariant() or 0 if it is not one. * * The returned depth-integer is important for sorting and matching. * Example: * "otherFunction(function1(function2(" * all functions named function2 should have ArgumentHintDepth 1, all functions found for function1 should have ArgumentHintDepth 2, * and all functions named otherFunction should have ArgumentHintDepth 3 * * Later, a completed item may then be matched with the first argument of function2, the return-type of function2 with the first * argument-type of function1, and the return-type of function1 with the argument-type of otherFunction. * * If the model returns a positive value on this role for a row, the content will be treated specially: * - It will be shown in a separate argument-hint list * - It will be sorted by Argument-hint depth * - Match-qualities will be illustrated by differently highlighting the matched argument if possible * The argument-hint list strings will be built from all source-model, with a little special behavior: * Prefix - Should be all text of the function-signature up to left of the matched argument of the function * Name - Should be the type and name of the function's matched argument. This part will be highlighted differently depending on the match-quality * Suffix - Should be all the text of the function-signature behind the matched argument * * Example: You are matching a function with signature "void test(int param1, int param2)", and you are matching the first argument. * The model should then return: * Prefix: "void test(" * Name: "int param1" * Suffix: ", int param2)" * * If you don't use the highlighting, matching, etc. you can also return the columns in the usual way. * */ ArgumentHintDepth, /** * This will be requested for each item to ask whether it should be included in computing a best-matches list. * If you return a valid positive integer n here, the n best matches will be listed at top of the completion-list separately. * * This is expensive because all items of the whole completion-list will be tested for their matching-quality, with each of the level 1 * argument-hints. * * For that reason the end-user should be able to disable this feature. */ BestMatchesCount, /** * The following three enumeration-values are only used on expanded completion-list items that contain an expanding-widget(@see ExpandingWidget) * * You can use them to allow the user to interact with the widget by keyboard. * * AccessibilityNext will be requested on an item if it is expanded, contains an expanding-widget, and the user triggers a special navigation * short-cut to go to navigate to the next position within the expanding-widget(if applicable). * * Return QVariant(true) if the input was used. * */ AccessibilityNext, /** * AccessibilityPrevious will be requested on an item if it is expanded, contains an expanding-widget, and the user triggers a special navigation * short-cut to go to navigate to the previous position within the expanding-widget(if applicable). * * Return QVariant(true) if the input was used. * */ AccessibilityPrevious, /** * AccessibilityAccept will be requested on an item if it is expanded, contains an expanding-widget, and the user triggers a special * shortcut to trigger the action associated with the position within the expanding-widget the user has navigated to using AccessibilityNext and AccessibilityPrevious. * * This should return QVariant(true) if an action was triggered, else QVariant(false) or QVariant(). * */ AccessibilityAccept, /** * Using this Role, it is possible to greatly optimize the time needed to process very long completion-lists. * * In the completion-list, the items are usually ordered by some properties like argument-hint depth, * inheritance-depth and attributes. Kate usually has to query the completion-models for these values * for each item in the completion-list in order to extract the argument-hints and correctly sort the * completion-list. However, with a very long completion-list, only a very small fraction of the items is actually * visible. * * By using a tree structure you can give the items in a grouped order to kate, so it does not need to look at each * item and query data in order to initially show the completion-list. * * This is how it works: * - You create a tree-structure for your items * - Every inner node of the tree defines one attribute value that all sub-nodes have in common. * - When the inner node is queried for GroupRole, it should return the "ExtraItemDataRoles" that all sub-nodes have in common * - When the inner node is then queried for that exact role, it should return that value. * - No other queries will be done to inner nodes. * - Every leaf node stands for an actual item in the completion list. * * The recommended grouping order is: Argument-hint depth, inheritance depth, attributes. * * This role can also be used to define completely custom groups, bypassing the editors builtin grouping: * - Return Qt::DisplayRole when GroupRole is requested * - Return the lable text of the group when Qt::DisplayRole * - Optional: Return an integer sorting-value when InheritanceDepth is requested. This number will * be used to determine the order of the groups. The order of the builtin groups is: * 1 = Best Matches, 100 = Local Scope, 200 = Public, 300 = Protected, 400 = Private, 500 = Namespace, 600 = Global * You can pick any arbitrary number to position your group relative to these builtin groups. * */ GroupRole, /** * Return a nonzero value here to enforce sorting the item at the end of the list. */ UnimportantItemRole, LastExtraItemDataRole }; void setRowCount(int rowCount); enum InvocationType { AutomaticInvocation, UserInvocation, ManualInvocation }; /** * This function is responsible to generating / updating the list of current * completions. The default implementation does nothing. * * When implementing this function, remember to call setRowCount() (or implement * rowCount()), and to generate the appropriate change notifications (for instance * by calling QAbstractItemModel::reset()). * @param view The view to generate completions for * @param range The range of text to generate completions for * @param invocationType How the code completion was triggered * */ virtual void completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, InvocationType invocationType); /** * This function is responsible for inserting a selected completion into the * view. The default implementation replaces the text that the completions * were based on with the Qt::DisplayRole of the Name column of the given match. * * @param view the view to insert the completion into * @param word the Range that the completions are based on (what the user entered * so far) * @param index identifies the completion match to insert * */ virtual void executeCompletionItem(KTextEditor::View *view, const Range &word, const QModelIndex &index) const; // Reimplementations /** * Reimplemented from QAbstractItemModel::columnCount(). The default implementation * returns ColumnCount for all indices. * */ - int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; /** * Reimplemented from QAbstractItemModel::index(). The default implementation * returns a standard QModelIndex as long as the row and column are valid. * */ - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; /** * Reimplemented from QAbstractItemModel::itemData(). The default implementation * returns a map with the QAbstractItemModel::data() for all roles that are used * by the CodeCompletionInterface. You will need to reimplement either this * function or QAbstractItemModel::data() in your CodeCompletionModel. * */ - QMap itemData(const QModelIndex &index) const Q_DECL_OVERRIDE; + QMap itemData(const QModelIndex &index) const override; /** * Reimplemented from QAbstractItemModel::parent(). The default implementation * returns an invalid QModelIndex for all items. This is appropriate for * non-hierarchical / flat lists of completions. * */ - QModelIndex parent(const QModelIndex &index) const Q_DECL_OVERRIDE; + QModelIndex parent(const QModelIndex &index) const override; /** * Reimplemented from QAbstractItemModel::rowCount(). The default implementation * returns the value set by setRowCount() for invalid (toplevel) indices, and 0 * for all other indices. This is appropriate for non-hierarchical / flat lists * of completions * */ - int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + int rowCount(const QModelIndex &parent = QModelIndex()) const override; /** * This function returns true if the model needs grouping, otherwise false. * The default is false if not changed via setHasGroups(). */ bool hasGroups() const; Q_SIGNALS: /** * Emit this if the code-completion for this model was invoked, some time is needed in order to get the data, * and the model is reset once the data is available. * * This only has an effect if emitted from within completionInvoked(..). * * This prevents the code-completion list from showing until this model is reset, * so there is no annoying flashing in the user-interface resulting from other models * supplying their data earlier. * * @note The implementation may choose to show the completion-list anyway after some timeout * * @warning If you emit this, you _must_ also reset the model at some point, * else the code-completion will be completely broken to the user. * Consider that there may always be additional completion-models apart from yours. * * @since 4.3 */ void waitForReset(); /** * Internal */ void hasGroupsChanged(KTextEditor::CodeCompletionModel *model, bool hasGroups); protected: void setHasGroups(bool hasGroups); private: class CodeCompletionModelPrivate *const d; }; Q_DECLARE_OPERATORS_FOR_FLAGS(CodeCompletionModel::CompletionProperties) Q_DECLARE_OPERATORS_FOR_FLAGS(CodeCompletionModel::HighlightMethods) } #endif // KTEXTEDITOR_CODECOMPLETIONMODEL_H diff --git a/src/include/ktexteditor/plugin.h b/src/include/ktexteditor/plugin.h index 2e84a35d..fb17011f 100644 --- a/src/include/ktexteditor/plugin.h +++ b/src/include/ktexteditor/plugin.h @@ -1,150 +1,150 @@ /* This file is part of the KDE libraries Copyright (C) 2001-2014 Christoph Cullmann Copyright (C) 2005-2014 Dominik Haumann (dhaumann@kde.org) 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. 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. 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. */ #ifndef KTEXTEDITOR_PLUGIN_H #define KTEXTEDITOR_PLUGIN_H #include #include namespace KTextEditor { class ConfigPage; class MainWindow; /** * \brief KTextEditor Plugin interface. * * Topics: * - \ref plugin_intro * - \ref plugin_config_pages * - \ref plugin_sessions * * \section plugin_intro Introduction * * The Plugin class provides methods to create loadable plugins for the * KTextEditor framework. The Plugin class itself a function createView() * that is called for each MainWindow. In createView(), the plugin is * responsible to create tool views through MainWindow::createToolView(), * hook itself into the menus and toolbars through KXMLGuiClient, and attach * itself to View%s or Document%s. * * \section plugin_config_pages Plugin Config Pages * * If your plugin needs config pages, override the functions configPages() * and configPage() in your plugin as follows: * \code * class MyPlugin : public KTextEditor::Plugin * { * Q_OBJECT * public: * // ... - * int configPages() const Q_DECL_OVERRIDE; - * ConfigPage *configPage(int number, QWidget *parent) Q_DECL_OVERRIDE; + * int configPages() const override; + * ConfigPage *configPage(int number, QWidget *parent) override; * }; * \endcode * The host application will call configPage() for each config page. * * \section plugin_sessions Session Management * * As an extension a Plugin can implement the SessionConfigInterface. This * interface provides functions to read and write session related settings. * If you have session dependent data additionally derive your Plugin from * this interface and implement the session related functions, for example: * \code * class MyPlugin : public KTextEditor::Plugin, * public KTextEditor::SessionConfigInterface * { * Q_OBJECT * Q_INTERFACES(KTextEditor::SessionConfigInterface) * public: * // ... - * void readSessionConfig (const KConfigGroup& config) Q_DECL_OVERRIDE; - * void writeSessionConfig (KConfigGroup& config) Q_DECL_OVERRIDE; + * void readSessionConfig (const KConfigGroup& config) override; + * void writeSessionConfig (KConfigGroup& config) override; * }; * \endcode * * \see KTextEditor::SessionConfigInterface, KTextEditor::ConfigPage, * KTextEditor::MainWindow * \author Christoph Cullmann \ */ class KTEXTEDITOR_EXPORT Plugin : public QObject { Q_OBJECT public: /** * Constructor. * * Create a new application plugin. * \param parent parent object */ Plugin(QObject *parent); /** * Virtual destructor. */ virtual ~Plugin(); /** * Create a new View for this plugin for the given KTextEditor::MainWindow. * This may be called arbitrary often by the application to create as much * views as MainWindow%s exist. The application will take care to delete * a view whenever a MainWindow is closed, so you do not need to handle * deletion of the view yourself in the plugin. * * \note Session configuration: The host application will try to cast the * returned QObject with \p qobject_cast into the SessionConfigInterface. * This way, not only your Plugin, but also each Plugin view can have * session related settings. * * \param mainWindow the MainWindow for which a view should be created * \return the new created view or NULL * @see SessionConfigInterface */ virtual QObject *createView(KTextEditor::MainWindow *mainWindow) = 0; /** * Get the number of available config pages. * If a number < 1 is returned, it does not support config pages. * \return number of config pages, default implementation says 0 * \see configPage() */ virtual int configPages() const; /** * Get the config page with the \p number, config pages from 0 to * configPages()-1 are available if configPages() > 0. * \param number index of config page * \param parent parent widget for config page * \return created config page or NULL, if the number is out of bounds, default implementation returns NULL * \see configPages() */ virtual ConfigPage *configPage(int number, QWidget *parent); private: class PluginPrivate *const d; }; } #endif diff --git a/src/inputmode/katenormalinputmode.h b/src/inputmode/katenormalinputmode.h index 8037c6cb..27e00bca 100644 --- a/src/inputmode/katenormalinputmode.h +++ b/src/inputmode/katenormalinputmode.h @@ -1,118 +1,118 @@ /* This file is part of the KDE libraries and the Kate part. * * 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. * * 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. * * 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. */ #ifndef __KATE_NORMAL_INPUT_MODE_H__ #define __KATE_NORMAL_INPUT_MODE_H__ #include "kateabstractinputmode.h" class KateNormalInputModeFactory; class KateSearchBar; class KateCommandLineBar; class KateNormalInputMode : public KateAbstractInputMode { KateNormalInputMode(KateViewInternal *viewInternal); friend KateNormalInputModeFactory; public: - ~KateNormalInputMode() Q_DECL_OVERRIDE; + ~KateNormalInputMode() override; - KTextEditor::View::ViewMode viewMode() const Q_DECL_OVERRIDE; - QString viewModeHuman() const Q_DECL_OVERRIDE; - KTextEditor::View::InputMode viewInputMode() const Q_DECL_OVERRIDE; - QString viewInputModeHuman() const Q_DECL_OVERRIDE; + KTextEditor::View::ViewMode viewMode() const override; + QString viewModeHuman() const override; + KTextEditor::View::InputMode viewInputMode() const override; + QString viewInputModeHuman() const override; - void activate() Q_DECL_OVERRIDE; - void deactivate() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE; + void activate() override; + void deactivate() override; + void reset() override; - bool overwrite() const Q_DECL_OVERRIDE; - void overwrittenChar(const QChar &) Q_DECL_OVERRIDE; + bool overwrite() const override; + void overwrittenChar(const QChar &) override; - void clearSelection() Q_DECL_OVERRIDE; - bool stealKey(QKeyEvent *) Q_DECL_OVERRIDE; + void clearSelection() override; + bool stealKey(QKeyEvent *) override; - void gotFocus() Q_DECL_OVERRIDE; - void lostFocus() Q_DECL_OVERRIDE; + void gotFocus() override; + void lostFocus() override; - void readSessionConfig(const KConfigGroup &config) Q_DECL_OVERRIDE; - void writeSessionConfig(KConfigGroup &config) Q_DECL_OVERRIDE; - void updateRendererConfig() Q_DECL_OVERRIDE; - void updateConfig() Q_DECL_OVERRIDE; - void readWriteChanged(bool rw) Q_DECL_OVERRIDE; + void readSessionConfig(const KConfigGroup &config) override; + void writeSessionConfig(KConfigGroup &config) override; + void updateRendererConfig() override; + void updateConfig() override; + void readWriteChanged(bool rw) override; - void find() Q_DECL_OVERRIDE; - void findSelectedForwards() Q_DECL_OVERRIDE; - void findSelectedBackwards() Q_DECL_OVERRIDE; - void findReplace() Q_DECL_OVERRIDE; - void findNext() Q_DECL_OVERRIDE; - void findPrevious() Q_DECL_OVERRIDE; + void find() override; + void findSelectedForwards() override; + void findSelectedBackwards() override; + void findReplace() override; + void findNext() override; + void findPrevious() override; - void activateCommandLine() Q_DECL_OVERRIDE; + void activateCommandLine() override; - bool keyPress(QKeyEvent *) Q_DECL_OVERRIDE; - bool blinkCaret() const Q_DECL_OVERRIDE; - KateRenderer::caretStyles caretStyle() const Q_DECL_OVERRIDE; + bool keyPress(QKeyEvent *) override; + bool blinkCaret() const override; + KateRenderer::caretStyles caretStyle() const override; - void toggleInsert() Q_DECL_OVERRIDE; - void launchInteractiveCommand(const QString &command) Q_DECL_OVERRIDE; + void toggleInsert() override; + void launchInteractiveCommand(const QString &command) override; - QString bookmarkLabel(int line) const Q_DECL_OVERRIDE; + QString bookmarkLabel(int line) const override; private: /** * Search bar mode: * - Setup Incremental mode, among other things: potential new search pattern * - Setup Power mode, aka find & replace: Also potential new search pattern * - Use current mode and current search pattern or if no Search bar exists, launch Incremental mode */ enum SearchBarMode { IncrementalSearchBar, PowerSearchBar, IncrementalSearchBarOrKeepMode }; /** * Get search bar, create it on demand. (with right mode) * @param mode wanted search bar mode * @return search bar widget */ KateSearchBar *searchBar(const SearchBarMode mode); /** * search bar around? * @return search bar around? */ bool hasSearchBar() const { return m_searchBar; } /** * Get command line bar, create it on demand. * @return command line bar, created if not already there */ KateCommandLineBar *cmdLineBar(); private: KateSearchBar *m_searchBar; KateCommandLineBar *m_cmdLine; }; #endif diff --git a/src/inputmode/katenormalinputmodefactory.h b/src/inputmode/katenormalinputmodefactory.h index f19105c4..c0746388 100644 --- a/src/inputmode/katenormalinputmodefactory.h +++ b/src/inputmode/katenormalinputmodefactory.h @@ -1,38 +1,38 @@ /* This file is part of the KDE libraries and the Kate part. * * 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. * * 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. * * 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. */ #ifndef __KATE_NORMAL_INPUT_MODE_FACTORY_H__ #define __KATE_NORMAL_INPUT_MODE_FACTORY_H__ #include "kateabstractinputmodefactory.h" class KateNormalInputModeFactory : public KateAbstractInputModeFactory { public: KateNormalInputModeFactory(); - ~KateNormalInputModeFactory() Q_DECL_OVERRIDE; - KateAbstractInputMode *createInputMode(KateViewInternal *viewInternal) Q_DECL_OVERRIDE; + ~KateNormalInputModeFactory() override; + KateAbstractInputMode *createInputMode(KateViewInternal *viewInternal) override; - QString name() Q_DECL_OVERRIDE; - KTextEditor::View::InputMode inputMode() Q_DECL_OVERRIDE; + QString name() override; + KTextEditor::View::InputMode inputMode() override; - KateConfigPage *createConfigPage(QWidget *) Q_DECL_OVERRIDE; + KateConfigPage *createConfigPage(QWidget *) override; }; #endif diff --git a/src/inputmode/kateviinputmode.h b/src/inputmode/kateviinputmode.h index 6aa69f38..ec678237 100644 --- a/src/inputmode/kateviinputmode.h +++ b/src/inputmode/kateviinputmode.h @@ -1,102 +1,102 @@ /* This file is part of the KDE libraries and the Kate part. * * 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. * * 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. * * 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. */ #ifndef __KATE_VI_INPUT_MODE_H__ #define __KATE_VI_INPUT_MODE_H__ #include "kateabstractinputmode.h" namespace KateVi { class GlobalState; class InputModeManager; class EmulatedCommandBar; } class KateViInputModeFactory; class KTEXTEDITOR_EXPORT KateViInputMode : public KateAbstractInputMode { explicit KateViInputMode(KateViewInternal *viewInternal, KateVi::GlobalState *global); friend KateViInputModeFactory; public: - ~KateViInputMode() Q_DECL_OVERRIDE; + ~KateViInputMode() override; - KTextEditor::View::ViewMode viewMode() const Q_DECL_OVERRIDE; - QString viewModeHuman() const Q_DECL_OVERRIDE; - KTextEditor::View::InputMode viewInputMode() const Q_DECL_OVERRIDE; - QString viewInputModeHuman() const Q_DECL_OVERRIDE; + KTextEditor::View::ViewMode viewMode() const override; + QString viewModeHuman() const override; + KTextEditor::View::InputMode viewInputMode() const override; + QString viewInputModeHuman() const override; - void activate() Q_DECL_OVERRIDE; - void deactivate() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE; + void activate() override; + void deactivate() override; + void reset() override; - bool overwrite() const Q_DECL_OVERRIDE; - void overwrittenChar(const QChar &) Q_DECL_OVERRIDE; + bool overwrite() const override; + void overwrittenChar(const QChar &) override; - void clearSelection() Q_DECL_OVERRIDE; - bool stealKey(QKeyEvent *) Q_DECL_OVERRIDE; + void clearSelection() override; + bool stealKey(QKeyEvent *) override; - void gotFocus() Q_DECL_OVERRIDE; - void lostFocus() Q_DECL_OVERRIDE; + void gotFocus() override; + void lostFocus() override; - void readSessionConfig(const KConfigGroup &config) Q_DECL_OVERRIDE; - void writeSessionConfig(KConfigGroup &config) Q_DECL_OVERRIDE; - void updateRendererConfig() Q_DECL_OVERRIDE; - void updateConfig() Q_DECL_OVERRIDE; - void readWriteChanged(bool rw) Q_DECL_OVERRIDE; + void readSessionConfig(const KConfigGroup &config) override; + void writeSessionConfig(KConfigGroup &config) override; + void updateRendererConfig() override; + void updateConfig() override; + void readWriteChanged(bool rw) override; - void find() Q_DECL_OVERRIDE; - void findSelectedForwards() Q_DECL_OVERRIDE; - void findSelectedBackwards() Q_DECL_OVERRIDE; - void findReplace() Q_DECL_OVERRIDE; - void findNext() Q_DECL_OVERRIDE; - void findPrevious() Q_DECL_OVERRIDE; + void find() override; + void findSelectedForwards() override; + void findSelectedBackwards() override; + void findReplace() override; + void findNext() override; + void findPrevious() override; - void activateCommandLine() Q_DECL_OVERRIDE; + void activateCommandLine() override; - bool keyPress(QKeyEvent *) Q_DECL_OVERRIDE; - bool blinkCaret() const Q_DECL_OVERRIDE; - KateRenderer::caretStyles caretStyle() const Q_DECL_OVERRIDE; + bool keyPress(QKeyEvent *) override; + bool blinkCaret() const override; + KateRenderer::caretStyles caretStyle() const override; - void toggleInsert() Q_DECL_OVERRIDE; - void launchInteractiveCommand(const QString &command) Q_DECL_OVERRIDE; + void toggleInsert() override; + void launchInteractiveCommand(const QString &command) override; - QString bookmarkLabel(int line) const Q_DECL_OVERRIDE; + QString bookmarkLabel(int line) const override; public: void showViModeEmulatedCommandBar(); KateVi::EmulatedCommandBar *viModeEmulatedCommandBar(); inline KateVi::GlobalState *globalState() const { return m_viGlobal; } inline KateVi::InputModeManager *viInputModeManager() const { return m_viModeManager; } inline bool isActive() const { return m_activated; } void setCaretStyle(const KateRenderer::caretStyles caret); private: KateVi::InputModeManager *m_viModeManager; KateVi::EmulatedCommandBar *m_viModeEmulatedCommandBar; KateVi::GlobalState *m_viGlobal; KateRenderer::caretStyles m_caret; bool m_nextKeypressIsOverriddenShortCut; // configs bool m_relLineNumbers; bool m_activated; }; #endif diff --git a/src/inputmode/kateviinputmodefactory.h b/src/inputmode/kateviinputmodefactory.h index 03539b8d..7b2fc08f 100644 --- a/src/inputmode/kateviinputmodefactory.h +++ b/src/inputmode/kateviinputmodefactory.h @@ -1,44 +1,44 @@ /* This file is part of the KDE libraries and the Kate part. * * 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. * * 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. * * 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. */ #ifndef __KATE_VI_INPUT_MODE_FACTORY_H__ #define __KATE_VI_INPUT_MODE_FACTORY_H__ #include "kateabstractinputmodefactory.h" namespace KateVi { class GlobalState; } class KateViInputMode; class KateViInputModeFactory : public KateAbstractInputModeFactory { friend KateViInputMode; public: KateViInputModeFactory(); - ~KateViInputModeFactory() Q_DECL_OVERRIDE; - KateAbstractInputMode *createInputMode(KateViewInternal *viewInternal) Q_DECL_OVERRIDE; + ~KateViInputModeFactory() override; + KateAbstractInputMode *createInputMode(KateViewInternal *viewInternal) override; - QString name() Q_DECL_OVERRIDE; - KTextEditor::View::InputMode inputMode() Q_DECL_OVERRIDE; + QString name() override; + KTextEditor::View::InputMode inputMode() override; - KateConfigPage *createConfigPage(QWidget *) Q_DECL_OVERRIDE; + KateConfigPage *createConfigPage(QWidget *) override; private: KateVi::GlobalState *m_viGlobal; }; #endif diff --git a/src/mode/katemodeconfigpage.h b/src/mode/katemodeconfigpage.h index b4d4bd72..47d65fc7 100644 --- a/src/mode/katemodeconfigpage.h +++ b/src/mode/katemodeconfigpage.h @@ -1,66 +1,66 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2001-2010 Christoph Cullmann * * 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. * * 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. * * 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. */ #ifndef KATE_MODECONFIGPAGE_H__ #define KATE_MODECONFIGPAGE_H__ #include #include #include "katedialogs.h" #include "katemodemanager.h" namespace Ui { class FileTypeConfigWidget; } class ModeConfigPage : public KateConfigPage { Q_OBJECT public: explicit ModeConfigPage(QWidget *parent); - ~ModeConfigPage() Q_DECL_OVERRIDE; - QString name() const Q_DECL_OVERRIDE; + ~ModeConfigPage() override; + QString name() const override; public Q_SLOTS: - void apply() Q_DECL_OVERRIDE; - void reload() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE; - void defaults() Q_DECL_OVERRIDE; + void apply() override; + void reload() override; + void reset() override; + void defaults() override; private Q_SLOTS: void update(); void deleteType(); void newType(); void typeChanged(int type); void showMTDlg(); void save(); void hlDownload(); private: Ui::FileTypeConfigWidget *ui; QList m_types; int m_lastType; }; #endif diff --git a/src/part/katepart.cpp b/src/part/katepart.cpp index 6bf29eaf..a4e5fadd 100644 --- a/src/part/katepart.cpp +++ b/src/part/katepart.cpp @@ -1,71 +1,71 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2001-2010 Christoph Cullmann * * 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. * * 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. * * 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. */ #include "katedocument.h" #include /** * wrapper factory to be sure nobody external deletes our kateglobal object * each instance will just increment the reference counter of our internal * super private global instance ;) */ class KateFactory : public KPluginFactory { Q_OBJECT Q_PLUGIN_METADATA(IID KPluginFactory_iid FILE "katepart.json") Q_INTERFACES(KPluginFactory) public: /** * This function is called when the factory asked to create an Object. * * You may reimplement it to provide a very flexible factory. This is especially useful to * provide generic factories for plugins implemeted using a scripting language. * * \param iface The staticMetaObject::className() string identifying the plugin interface that * was requested. E.g. for KCModule plugins this string will be "KCModule". * \param parentWidget Only used if the requested plugin is a KPart. * \param parent The parent object for the plugin object. * \param args A plugin specific list of arbitrary arguments. * \param keyword A string that uniquely identifies the plugin. If a KService is used this * keyword is read from the X-KDE-PluginKeyword entry in the .desktop file. */ - QObject *create(const char *iface, QWidget *parentWidget, QObject *parent, const QVariantList &, const QString &) Q_DECL_OVERRIDE + QObject *create(const char *iface, QWidget *parentWidget, QObject *parent, const QVariantList &, const QString &) override { // iface == classname to construct const QByteArray classname (iface); // default to the kparts::* behavior of having one single widget() if the user don't requested a pure document const bool bWantSingleView = (classname != "KTextEditor::Document"); // should we be readonly? const bool bWantReadOnly = (classname == "KParts::ReadOnlyPart"); // construct right part variant KParts::ReadWritePart *part = new KTextEditor::DocumentPrivate (bWantSingleView, bWantReadOnly, parentWidget, parent); part->setReadWrite(!bWantReadOnly); return part; } }; #include "katepart.moc" diff --git a/src/render/katerenderrange.h b/src/render/katerenderrange.h index 432fe8da..5812fb06 100644 --- a/src/render/katerenderrange.h +++ b/src/render/katerenderrange.h @@ -1,75 +1,75 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2003-2005 Hamish Rodda * Copyright (C) 2008 David Nolden * * 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. * * 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. * * 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. */ #ifndef KATERENDERRANGE_H #define KATERENDERRANGE_H #include #include #include #include class KateRenderRange { public: virtual ~KateRenderRange() {} virtual KTextEditor::Cursor nextBoundary() const = 0; virtual bool advanceTo(const KTextEditor::Cursor &pos) = 0; virtual KTextEditor::Attribute::Ptr currentAttribute() const = 0; virtual bool isReady() const; }; typedef QPair pairRA; class NormalRenderRange : public KateRenderRange { public: NormalRenderRange(); - ~NormalRenderRange() Q_DECL_OVERRIDE; + ~NormalRenderRange() override; void addRange(KTextEditor::Range *range, KTextEditor::Attribute::Ptr attribute); - KTextEditor::Cursor nextBoundary() const Q_DECL_OVERRIDE; - bool advanceTo(const KTextEditor::Cursor &pos) Q_DECL_OVERRIDE; - KTextEditor::Attribute::Ptr currentAttribute() const Q_DECL_OVERRIDE; + KTextEditor::Cursor nextBoundary() const override; + bool advanceTo(const KTextEditor::Cursor &pos) override; + KTextEditor::Attribute::Ptr currentAttribute() const override; private: QList m_ranges; KTextEditor::Cursor m_nextBoundary; KTextEditor::Attribute::Ptr m_currentAttribute; int m_currentRange = 0; }; class RenderRangeList : public QList { public: ~RenderRangeList(); KTextEditor::Cursor nextBoundary() const; void advanceTo(const KTextEditor::Cursor &pos); bool hasAttribute() const; KTextEditor::Attribute::Ptr generateAttribute() const; private: KTextEditor::Cursor m_currentPos; }; #endif diff --git a/src/schema/katecategorydrawer.h b/src/schema/katecategorydrawer.h index 5cda1f3e..0b614112 100644 --- a/src/schema/katecategorydrawer.h +++ b/src/schema/katecategorydrawer.h @@ -1,48 +1,48 @@ /* * Copyright (C) 2009 by Rafael Fernández López * Copyright (C) 2013 by Dominik Haumann * * 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. * * 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. * * 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. */ #ifndef KATE_CATEGORYDRAWER_H #define KATE_CATEGORYDRAWER_H #include class QPainter; class QModelIndex; class QStyleOption; class KateCategoryDrawer : public KCategoryDrawer { public: KateCategoryDrawer(); virtual void drawCategory(const QModelIndex &index, int sortRole, const QStyleOption &option, - QPainter *painter) const Q_DECL_OVERRIDE; + QPainter *painter) const override; - int categoryHeight(const QModelIndex &index, const QStyleOption &option) const Q_DECL_OVERRIDE; + int categoryHeight(const QModelIndex &index, const QStyleOption &option) const override; - int leftMargin() const Q_DECL_OVERRIDE; + int leftMargin() const override; - int rightMargin() const Q_DECL_OVERRIDE; + int rightMargin() const override; }; #endif diff --git a/src/schema/katecolortreewidget.cpp b/src/schema/katecolortreewidget.cpp index b0fa8baf..3f8b0765 100644 --- a/src/schema/katecolortreewidget.cpp +++ b/src/schema/katecolortreewidget.cpp @@ -1,386 +1,386 @@ /* This file is part of the KDE libraries Copyright (C) 2012 Dominik Haumann * * 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. * * 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. * * 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. */ #include "katecolortreewidget.h" #include "katecategorydrawer.h" #include #include #include #include #include #include "katepartdebug.h" #include #include #include #include #include //BEGIN KateColorTreeItem class KateColorTreeItem : public QTreeWidgetItem { public: KateColorTreeItem(const KateColorItem &colorItem, QTreeWidgetItem *parent = nullptr) : QTreeWidgetItem(parent) , m_colorItem(colorItem) { setText(0, m_colorItem.name); if (!colorItem.whatsThis.isEmpty()) { setData(1, Qt::WhatsThisRole, colorItem.whatsThis); } if (!colorItem.useDefault) { setData(2, Qt::ToolTipRole, i18n("Use default color from the KDE color scheme")); } } QColor color() const { return m_colorItem.color; } void setColor(const QColor &c) { m_colorItem.color = c; } QColor defaultColor() const { return m_colorItem.defaultColor; } bool useDefaultColor() const { return m_colorItem.useDefault; } void setUseDefaultColor(bool useDefault) { m_colorItem.useDefault = useDefault; QString tooltip = useDefault ? QString() : i18n("Use default color from the KDE color scheme"); setData(2, Qt::ToolTipRole, tooltip); } QString key() { return m_colorItem.key; } KateColorItem colorItem() const { return m_colorItem; } private: KateColorItem m_colorItem; }; //END KateColorTreeItem //BEGIN KateColorTreeDelegate class KateColorTreeDelegate : public QStyledItemDelegate { public: KateColorTreeDelegate(KateColorTreeWidget *widget) : QStyledItemDelegate(widget) , m_tree(widget) { } - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override { QSize sh = QStyledItemDelegate::sizeHint(option, index); if (!index.parent().isValid()) { sh.rheight() += 2 * m_categoryDrawer.leftMargin(); } else { sh.rheight() += m_categoryDrawer.leftMargin(); } if (index.column() == 0) { sh.rwidth() += m_categoryDrawer.leftMargin(); } else if (index.column() == 1) { sh.rwidth() = 150; } else { sh.rwidth() += m_categoryDrawer.leftMargin(); } return sh; } QRect fullCategoryRect(const QStyleOptionViewItem &option, const QModelIndex &index) const { QModelIndex i = index; if (i.parent().isValid()) { i = i.parent(); } QTreeWidgetItem *item = m_tree->itemFromIndex(i); QRect r = m_tree->visualItemRect(item); // adapt width r.setLeft(m_categoryDrawer.leftMargin()); r.setWidth(m_tree->viewport()->width() - m_categoryDrawer.leftMargin() - m_categoryDrawer.rightMargin()); // adapt height if (item->isExpanded() && item->childCount() > 0) { const int childCount = item->childCount(); const int h = sizeHint(option, index.child(0, 0)).height(); r.setHeight(r.height() + childCount * h); } r.setTop(r.top() + m_categoryDrawer.leftMargin()); return r; } - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override { Q_ASSERT(index.isValid()); Q_ASSERT(index.column() >= 0 && index.column() <= 2); //BEGIN: draw toplevel items if (!index.parent().isValid()) { QStyleOptionViewItem opt(option); const QRegion cl = painter->clipRegion(); painter->setClipRect(opt.rect); opt.rect = fullCategoryRect(option, index); m_categoryDrawer.drawCategory(index, 0, opt, painter); painter->setClipRegion(cl); return; } //END: draw toplevel items //BEGIN: draw background of category for all other items { QStyleOptionViewItem opt(option); opt.rect = fullCategoryRect(option, index); const QRegion cl = painter->clipRegion(); QRect cr = option.rect; if (index.column() == 0) { if (m_tree->layoutDirection() == Qt::LeftToRight) { cr.setLeft(5); } else { cr.setRight(opt.rect.right()); } } painter->setClipRect(cr); m_categoryDrawer.drawCategory(index, 0, opt, painter); painter->setClipRegion(cl); painter->setRenderHint(QPainter::Antialiasing, false); } //END: draw background of category for all other items // paint the text QStyledItemDelegate::paint(painter, option, index); if (index.column() == 0) { return; } painter->setClipRect(option.rect); KateColorTreeItem *item = dynamic_cast(m_tree->itemFromIndex(index)); //BEGIN: draw color button if (index.column() == 1) { QColor color = item->useDefaultColor() ? item->defaultColor() : item->color(); QStyleOptionButton opt; opt.rect = option.rect; opt.palette = m_tree->palette(); m_tree->style()->drawControl(QStyle::CE_PushButton, &opt, painter, m_tree); opt.rect = m_tree->style()->subElementRect(QStyle::SE_PushButtonContents, &opt, m_tree); opt.rect.adjust(1, 1, -1, -1); painter->fillRect(opt.rect, color); qDrawShadePanel(painter, opt.rect, opt.palette, true, 1, nullptr); } //END: draw color button //BEGIN: draw reset icon if (index.column() == 2 && !item->useDefaultColor()) { // get right pixmap const bool enabled = (option.state & QStyle::State_MouseOver || option.state & QStyle::State_HasFocus); const QPixmap p = QIcon::fromTheme(QStringLiteral("edit-undo")).pixmap(16, 16, enabled ? QIcon::Normal : QIcon::Disabled); // compute rect with scaled sizes const QRect rect(option.rect.left() + 10, option.rect.top() + (option.rect.height() - p.height() / p.devicePixelRatio() + 1) / 2, p.width() / p.devicePixelRatio(), p.height() / p.devicePixelRatio()); painter->drawPixmap(rect, p); } //END: draw reset icon } private: KateColorTreeWidget *m_tree; KateCategoryDrawer m_categoryDrawer; }; //END KateColorTreeDelegate KateColorTreeWidget::KateColorTreeWidget(QWidget *parent) : QTreeWidget(parent) { setItemDelegate(new KateColorTreeDelegate(this)); QStringList headers; headers << QString() // i18nc("@title:column the color name", "Color Role") << QString() // i18nc("@title:column a color button", "Color") << QString();// i18nc("@title:column use default color", "Reset") setHeaderLabels(headers); setHeaderHidden(true); setRootIsDecorated(false); setIndentation(25); } bool KateColorTreeWidget::edit(const QModelIndex &index, EditTrigger trigger, QEvent *event) { // accept edit only for color buttons in column 1 and reset in column 2 if (!index.parent().isValid() || index.column() < 1) { return QTreeWidget::edit(index, trigger, event); } bool accept = false; if (event && event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast(event); accept = (ke->key() == Qt::Key_Space); // allow Space to edit } switch (trigger) { case QAbstractItemView::DoubleClicked: case QAbstractItemView::SelectedClicked: case QAbstractItemView::EditKeyPressed: // = F2 accept = true; break; default: break; } if (accept) { KateColorTreeItem *item = dynamic_cast(itemFromIndex(index)); const QColor color = item->useDefaultColor() ? item->defaultColor() : item->color(); if (index.column() == 1) { const QColor selectedColor = QColorDialog::getColor(color, this); if (selectedColor.isValid()) { item->setUseDefaultColor(false); item->setColor(selectedColor); viewport()->update(); emit changed(); } } else if (index.column() == 2 && !item->useDefaultColor()) { item->setUseDefaultColor(true); viewport()->update(); emit changed(); } return false; } return QTreeWidget::edit(index, trigger, event); } void KateColorTreeWidget::drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const { Q_UNUSED(painter) Q_UNUSED(rect) Q_UNUSED(index) } void KateColorTreeWidget::selectDefaults() { bool somethingChanged = false; // use default colors for all selected items for (int a = 0; a < topLevelItemCount(); ++a) { QTreeWidgetItem *top = topLevelItem(a); for (int b = 0; b < top->childCount(); ++b) { KateColorTreeItem *it = dynamic_cast(top->child(b)); Q_ASSERT(it); if (!it->useDefaultColor()) { it->setUseDefaultColor(true); somethingChanged = true; } } } if (somethingChanged) { viewport()->update(); emit changed(); } } void KateColorTreeWidget::addColorItem(const KateColorItem &colorItem) { QTreeWidgetItem *categoryItem = nullptr; for (int i = 0; i < topLevelItemCount(); ++i) { if (topLevelItem(i)->text(0) == colorItem.category) { categoryItem = topLevelItem(i); break; } } if (!categoryItem) { categoryItem = new QTreeWidgetItem(); categoryItem->setText(0, colorItem.category); addTopLevelItem(categoryItem); expandItem(categoryItem); } new KateColorTreeItem(colorItem, categoryItem); resizeColumnToContents(0); } void KateColorTreeWidget::addColorItems(const QVector &colorItems) { foreach (const KateColorItem &item, colorItems) { addColorItem(item); } } QVector KateColorTreeWidget::colorItems() const { QVector items; for (int a = 0; a < topLevelItemCount(); ++a) { QTreeWidgetItem *top = topLevelItem(a); for (int b = 0; b < top->childCount(); ++b) { KateColorTreeItem *item = dynamic_cast(top->child(b)); Q_ASSERT(item); items.append(item->colorItem()); } } return items; } QColor KateColorTreeWidget::findColor(const QString &key) const { for (int a = 0; a < topLevelItemCount(); ++a) { QTreeWidgetItem *top = topLevelItem(a); for (int b = 0; b < top->childCount(); ++b) { KateColorTreeItem *item = dynamic_cast(top->child(b)); if (item->key() == key) { if (item->useDefaultColor()) { return item->defaultColor(); } else { return item->color(); } } } } return QColor(); } diff --git a/src/schema/katecolortreewidget.h b/src/schema/katecolortreewidget.h index d5c39ffe..e5a45c6a 100644 --- a/src/schema/katecolortreewidget.h +++ b/src/schema/katecolortreewidget.h @@ -1,70 +1,70 @@ /* This file is part of the KDE libraries Copyright (C) 2012 Dominik Haumann * * 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. * * 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. * * 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. */ #ifndef KATE_COLOR_TREE_WIDGET_H #define KATE_COLOR_TREE_WIDGET_H #include class KateColorItem { public: KateColorItem() { } QString name; // translated name QString category; // translated category for tree view hierarchy QString whatsThis; // what's this info QString key; // untranslated id, used as key to save/load from KConfig QColor color; // user visible color QColor defaultColor; // used when "Default" is clicked bool useDefault = true; // flag whether to use the default color }; class KateColorTreeWidget : public QTreeWidget { Q_OBJECT friend class KateColorTreeItem; friend class KateColorTreeDelegate; public: explicit KateColorTreeWidget(QWidget *parent = nullptr); public: void addColorItem(const KateColorItem &colorItem); void addColorItems(const QVector &colorItems); QVector colorItems() const; QColor findColor(const QString &key) const; public Q_SLOTS: void selectDefaults(); Q_SIGNALS: void changed(); protected: - bool edit(const QModelIndex &index, EditTrigger trigger, QEvent *event) Q_DECL_OVERRIDE; - void drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const Q_DECL_OVERRIDE; + bool edit(const QModelIndex &index, EditTrigger trigger, QEvent *event) override; + void drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const override; }; #endif diff --git a/src/schema/kateschemaconfig.h b/src/schema/kateschemaconfig.h index 25e58429..be0dfccd 100644 --- a/src/schema/kateschemaconfig.h +++ b/src/schema/kateschemaconfig.h @@ -1,216 +1,216 @@ /* This file is part of the KDE libraries Copyright (C) 2001-2003 Christoph Cullmann Copyright (C) 2002, 2003 Anders Lund Copyright (C) 2012 Dominik Haumann * * 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. * * 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. * * 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. */ #ifndef __KATE_SCHEMA_CONFIG_H__ #define __KATE_SCHEMA_CONFIG_H__ #include "katedialogs.h" #include "katecolortreewidget.h" #include "kateextendedattribute.h" #include #include class KateStyleTreeWidget; class KComboBox; class KateSchemaConfigColorTab : public QWidget { Q_OBJECT public: KateSchemaConfigColorTab(); ~KateSchemaConfigColorTab(); QColor backgroundColor() const; QColor selectionColor() const; public Q_SLOTS: void apply(); void reload(); void schemaChanged(const QString &newSchema); void importSchema(KConfigGroup &config); void exportSchema(KConfigGroup &config); Q_SIGNALS: void changed(); private: QVector colorItemList() const; QVector readConfig(KConfigGroup &config); private: // multiple shemas may be edited. Hence, we need one ColorList for each schema QMap > m_schemas; QString m_currentSchema; KateColorTreeWidget *ui; }; class KateSchemaConfigFontTab : public QWidget { Q_OBJECT public: KateSchemaConfigFontTab(); ~KateSchemaConfigFontTab(); public: void readConfig(KConfig *config); void importSchema(KConfigGroup &config); void exportSchema(KConfigGroup &config); public Q_SLOTS: void apply(); void reload(); void schemaChanged(const QString &newSchema); Q_SIGNALS: void changed(); private: class KFontChooser *m_fontchooser; QMap m_fonts; QString m_currentSchema; private Q_SLOTS: void slotFontSelected(const QFont &font); }; class KateSchemaConfigDefaultStylesTab : public QWidget { Q_OBJECT public: KateSchemaConfigDefaultStylesTab(KateSchemaConfigColorTab *colorTab); ~KateSchemaConfigDefaultStylesTab(); Q_SIGNALS: void changed(); public: void schemaChanged(const QString &schema); void reload(); void apply(); KateAttributeList *attributeList(const QString &schema); void exportSchema(const QString &schema, KConfig *cfg); void importSchema(const QString &schemaName, const QString &schema, KConfig *cfg); protected: - void showEvent(QShowEvent *event) Q_DECL_OVERRIDE; + void showEvent(QShowEvent *event) override; void updateColorPalette(const QColor &textColor); private: KateStyleTreeWidget *m_defaultStyles; QHash m_defaultStyleLists; KateSchemaConfigColorTab *m_colorTab; QString m_currentSchema; }; class KateSchemaConfigHighlightTab : public QWidget { Q_OBJECT public: explicit KateSchemaConfigHighlightTab(KateSchemaConfigDefaultStylesTab *page, KateSchemaConfigColorTab *colorTab); ~KateSchemaConfigHighlightTab(); void schemaChanged(const QString &schema); void reload(); void apply(); Q_SIGNALS: void changed(); protected Q_SLOTS: void hlChanged(int z); public Q_SLOTS: void exportHl(QString schema = QString(), int hl = -1, KConfig *cfg = nullptr); void importHl(const QString &fromSchemaName = QString(), QString schema = QString(), int hl = -1, KConfig *cfg = nullptr); protected: - void showEvent(QShowEvent *event) Q_DECL_OVERRIDE; + void showEvent(QShowEvent *event) override; void updateColorPalette(const QColor &textColor); private: KateSchemaConfigDefaultStylesTab *m_defaults; KateSchemaConfigColorTab *m_colorTab; KComboBox *hlCombo; KateStyleTreeWidget *m_styles; QString m_schema; int m_hl; QHash > > m_hlDict; public: QList hlsForSchema(const QString &schema); bool loadAllHlsForSchema(const QString &schema); }; class KateSchemaConfigPage : public KateConfigPage { Q_OBJECT public: explicit KateSchemaConfigPage(QWidget *parent); virtual ~KateSchemaConfigPage(); - QString name() const Q_DECL_OVERRIDE; - QString fullName() const Q_DECL_OVERRIDE; - QIcon icon() const Q_DECL_OVERRIDE; + QString name() const override; + QString fullName() const override; + QIcon icon() const override; public Q_SLOTS: - void apply() Q_DECL_OVERRIDE; - void reload() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE; - void defaults() Q_DECL_OVERRIDE; + void apply() override; + void reload() override; + void reset() override; + void defaults() override; void exportFullSchema(); void importFullSchema(); private Q_SLOTS: void deleteSchema(); bool newSchema(const QString &newName = QString()); void schemaChanged(const QString &schema); void comboBoxIndexChanged(int currentIndex); private: void refillCombos(const QString &schemaName, const QString &defaultSchemaName); QString requestSchemaName(const QString &suggestedName); private: QString m_currentSchema; class QPushButton *btndel; class KComboBox *defaultSchemaCombo; class KComboBox *schemaCombo; KateSchemaConfigColorTab *m_colorTab; KateSchemaConfigFontTab *m_fontTab; KateSchemaConfigDefaultStylesTab *m_defaultStylesTab; KateSchemaConfigHighlightTab *m_highlightTab; }; #endif diff --git a/src/schema/katestyletreewidget.cpp b/src/schema/katestyletreewidget.cpp index 55e7e4bd..1f4fec78 100644 --- a/src/schema/katestyletreewidget.cpp +++ b/src/schema/katestyletreewidget.cpp @@ -1,739 +1,739 @@ /* This file is part of the KDE libraries Copyright (C) 2001-2003 Christoph Cullmann Copyright (C) 2002, 2003 Anders Lund Copyright (C) 2005-2006 Hamish Rodda Copyright (C) 2007 Mirko Stocker * * 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. * * 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. * * 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. */ #include "katestyletreewidget.h" #include "kateconfig.h" #include "kateextendedattribute.h" #include "katedefaultcolors.h" #include "kateglobal.h" #include #include #include #include #include #include #include #include #include //BEGIN KateStyleTreeDelegate class KateStyleTreeDelegate : public QStyledItemDelegate { public: KateStyleTreeDelegate(KateStyleTreeWidget *widget); - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; private: QBrush getBrushForColorColumn(const QModelIndex &index, int column) const; KateStyleTreeWidget *m_widget; }; //END //BEGIN KateStyleTreeWidgetItem decl /* QListViewItem subclass to display/edit a style, bold/italic is check boxes, normal and selected colors are boxes, which will display a color chooser when activated. The context name for the style will be drawn using the editor default font and the chosen colors. This widget id designed to handle the default as well as the individual hl style lists. This widget is designed to work with the KateStyleTreeWidget class exclusively. Added by anders, jan 23 2002. */ class KateStyleTreeWidgetItem : public QTreeWidgetItem { public: KateStyleTreeWidgetItem(QTreeWidgetItem *parent, const QString &styleName, KTextEditor::Attribute::Ptr defaultstyle, KTextEditor::Attribute::Ptr data = KTextEditor::Attribute::Ptr()); KateStyleTreeWidgetItem(QTreeWidget *parent, const QString &styleName, KTextEditor::Attribute::Ptr defaultstyle, KTextEditor::Attribute::Ptr data = KTextEditor::Attribute::Ptr()); - ~KateStyleTreeWidgetItem() Q_DECL_OVERRIDE {} + ~KateStyleTreeWidgetItem() override {} enum columns { Context = 0, Bold, Italic, Underline, StrikeOut, Foreground, SelectedForeground, Background, SelectedBackground, UseDefaultStyle, NumColumns }; /* initializes the style from the default and the hldata */ void initStyle(); /* updates the hldata's style */ void updateStyle(); /* For bool fields, toggles them, for color fields, display a color chooser */ void changeProperty(int p); /** unset a color. * c is 100 (BGColor) or 101 (SelectedBGColor) for now. */ void unsetColor(int c); /* style context name */ QString contextName() const { return text(0); } /* only true for a hl mode item using its default style */ bool defStyle() const; /* true for default styles */ bool isDefault() const; /* whichever style is active (currentStyle for hl mode styles not using the default style, defaultStyle otherwise) */ KTextEditor::Attribute::Ptr style() const { return currentStyle; } - QVariant data(int column, int role) const Q_DECL_OVERRIDE; + QVariant data(int column, int role) const override; KateStyleTreeWidget *treeWidget() const; private: /* private methods to change properties */ void toggleDefStyle(); void setColor(int); /* helper function to copy the default style into the KateExtendedAttribute, when a property is changed and we are using default style. */ KTextEditor::Attribute::Ptr currentStyle, // the style currently in use (was "is") defaultStyle; // default style for hl mode contexts and default styles (was "ds") KTextEditor::Attribute::Ptr actualStyle; // itemdata for hl mode contexts (was "st") }; //END //BEGIN KateStyleTreeWidget KateStyleTreeWidget::KateStyleTreeWidget(QWidget *parent, bool showUseDefaults) : QTreeWidget(parent) { setItemDelegate(new KateStyleTreeDelegate(this)); setRootIsDecorated(false); QStringList headers; headers << i18nc("@title:column Meaning of text in editor", "Context") << QString() << QString() << QString() << QString() << i18nc("@title:column Text style", "Normal") << i18nc("@title:column Text style", "Selected") << i18nc("@title:column Text style", "Background") << i18nc("@title:column Text style", "Background Selected"); if (showUseDefaults) { headers << i18n("Use Default Style"); } setHeaderLabels(headers); headerItem()->setIcon(1, QIcon::fromTheme(QStringLiteral("format-text-bold"))); headerItem()->setIcon(2, QIcon::fromTheme(QStringLiteral("format-text-italic"))); headerItem()->setIcon(3, QIcon::fromTheme(QStringLiteral("format-text-underline"))); headerItem()->setIcon(4, QIcon::fromTheme(QStringLiteral("format-text-strikethrough"))); // grap the bg color, selected color and default font const KColorScheme &colors(KTextEditor::EditorPrivate::self()->defaultColors().view()); normalcol = colors.foreground().color(); bgcol = KateRendererConfig::global()->backgroundColor(); selcol = KateRendererConfig::global()->selectionColor(); docfont = KateRendererConfig::global()->font(); QPalette pal = viewport()->palette(); pal.setColor(QPalette::Background, bgcol); viewport()->setPalette(pal); } QIcon brushIcon(const QColor &color) { QPixmap pm(16, 16); QRect all(0, 0, 15, 15); { QPainter p(&pm); p.fillRect(all, color); p.setPen(Qt::black); p.drawRect(all); } return QIcon(pm); } bool KateStyleTreeWidget::edit(const QModelIndex &index, EditTrigger trigger, QEvent *event) { if (index.column() == KateStyleTreeWidgetItem::Context) { return false; } KateStyleTreeWidgetItem *i = dynamic_cast(itemFromIndex(index)); if (!i) { return QTreeWidget::edit(index, trigger, event); } switch (trigger) { case QAbstractItemView::DoubleClicked: case QAbstractItemView::SelectedClicked: case QAbstractItemView::EditKeyPressed: i->changeProperty(index.column()); update(index); update(index.sibling(index.row(), KateStyleTreeWidgetItem::Context)); return false; default: return QTreeWidget::edit(index, trigger, event); } } void KateStyleTreeWidget::resizeColumns() { for (int i = 0; i < columnCount(); ++i) { resizeColumnToContents(i); } } void KateStyleTreeWidget::showEvent(QShowEvent *event) { QTreeWidget::showEvent(event); resizeColumns(); } void KateStyleTreeWidget::contextMenuEvent(QContextMenuEvent *event) { KateStyleTreeWidgetItem *i = dynamic_cast(itemAt(event->pos())); if (!i) { return; } QMenu m(this); KTextEditor::Attribute::Ptr currentStyle = i->style(); // the title is used, because the menu obscures the context name when // displayed on behalf of spacePressed(). QPainter p; p.setPen(Qt::black); const QIcon emptyColorIcon = brushIcon(viewport()->palette().base().color()); QIcon cl = brushIcon(i->style()->foreground().color()); QIcon scl = brushIcon(i->style()->selectedForeground().color()); QIcon bgcl = i->style()->hasProperty(QTextFormat::BackgroundBrush) ? brushIcon(i->style()->background().color()) : emptyColorIcon; QIcon sbgcl = i->style()->hasProperty(CustomProperties::SelectedBackground) ? brushIcon(i->style()->selectedBackground().color()) : emptyColorIcon; m.addSection(i->contextName()); QAction *a = m.addAction(i18n("&Bold"), this, SLOT(changeProperty())); a->setCheckable(true); a->setChecked(currentStyle->fontBold()); a->setData(KateStyleTreeWidgetItem::Bold); a = m.addAction(i18n("&Italic"), this, SLOT(changeProperty())); a->setCheckable(true); a->setChecked(currentStyle->fontItalic()); a->setData(KateStyleTreeWidgetItem::Italic); a = m.addAction(i18n("&Underline"), this, SLOT(changeProperty())); a->setCheckable(true); a->setChecked(currentStyle->fontUnderline()); a->setData(KateStyleTreeWidgetItem::Underline); a = m.addAction(i18n("S&trikeout"), this, SLOT(changeProperty())); a->setCheckable(true); a->setChecked(currentStyle->fontStrikeOut()); a->setData(KateStyleTreeWidgetItem::StrikeOut); m.addSeparator(); a = m.addAction(cl, i18n("Normal &Color..."), this, SLOT(changeProperty())); a->setData(KateStyleTreeWidgetItem::Foreground); a = m.addAction(scl, i18n("&Selected Color..."), this, SLOT(changeProperty())); a->setData(KateStyleTreeWidgetItem::SelectedForeground); a = m.addAction(bgcl, i18n("&Background Color..."), this, SLOT(changeProperty())); a->setData(KateStyleTreeWidgetItem::Background); a = m.addAction(sbgcl, i18n("S&elected Background Color..."), this, SLOT(changeProperty())); a->setData(KateStyleTreeWidgetItem::SelectedBackground); // defaulters m.addSeparator(); a = m.addAction(emptyColorIcon, i18n("Unset Normal Color"), this, SLOT(unsetColor())); a->setData(1); a = m.addAction(emptyColorIcon, i18n("Unset Selected Color"), this, SLOT(unsetColor())); a->setData(2); // unsetters KTextEditor::Attribute::Ptr style = i->style(); if (style->hasProperty(QTextFormat::BackgroundBrush)) { a = m.addAction(emptyColorIcon, i18n("Unset Background Color"), this, SLOT(unsetColor())); a->setData(3); } if (style->hasProperty(CustomProperties::SelectedBackground)) { a = m.addAction(emptyColorIcon, i18n("Unset Selected Background Color"), this, SLOT(unsetColor())); a->setData(4); } if (! i->isDefault() && ! i->defStyle()) { m.addSeparator(); a = m.addAction(i18n("Use &Default Style"), this, SLOT(changeProperty())); a->setCheckable(true); a->setChecked(i->defStyle()); a->setData(KateStyleTreeWidgetItem::UseDefaultStyle); } m.exec(event->globalPos()); } void KateStyleTreeWidget::changeProperty() { static_cast(currentItem())->changeProperty(static_cast(sender())->data().toInt()); } void KateStyleTreeWidget::unsetColor() { static_cast(currentItem())->unsetColor(static_cast(sender())->data().toInt()); } void KateStyleTreeWidget::updateGroupHeadings() { for (int i = 0; i < topLevelItemCount(); i++) { QTreeWidgetItem *currentTopLevelItem = topLevelItem(i); QTreeWidgetItem *firstChild = currentTopLevelItem->child(0); if (firstChild) { QColor foregroundColor = firstChild->data(KateStyleTreeWidgetItem::Foreground, Qt::DisplayRole).value(); QColor backgroundColor = firstChild->data(KateStyleTreeWidgetItem::Background, Qt::DisplayRole).value(); currentTopLevelItem->setForeground(KateStyleTreeWidgetItem::Context, foregroundColor); if (backgroundColor.isValid()) { currentTopLevelItem->setBackground(KateStyleTreeWidgetItem::Context, backgroundColor); } } } } void KateStyleTreeWidget::emitChanged() { updateGroupHeadings(); emit changed(); } void KateStyleTreeWidget::addItem(const QString &styleName, KTextEditor::Attribute::Ptr defaultstyle, KTextEditor::Attribute::Ptr data) { new KateStyleTreeWidgetItem(this, styleName, defaultstyle, data); } void KateStyleTreeWidget::addItem(QTreeWidgetItem *parent, const QString &styleName, KTextEditor::Attribute::Ptr defaultstyle, KTextEditor::Attribute::Ptr data) { new KateStyleTreeWidgetItem(parent, styleName, defaultstyle, data); updateGroupHeadings(); } //END //BEGIN KateStyleTreeWidgetItem KateStyleTreeDelegate::KateStyleTreeDelegate(KateStyleTreeWidget *widget) : m_widget(widget) { } QBrush KateStyleTreeDelegate::getBrushForColorColumn(const QModelIndex &index, int column) const { QModelIndex colorIndex = index.sibling(index.row(), column); QVariant displayData = colorIndex.model()->data(colorIndex); return displayData.value(); } void KateStyleTreeDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { static QSet columns; if (columns.isEmpty()) { columns << KateStyleTreeWidgetItem::Foreground << KateStyleTreeWidgetItem::SelectedForeground << KateStyleTreeWidgetItem::Background << KateStyleTreeWidgetItem::SelectedBackground; } if (index.column() == KateStyleTreeWidgetItem::Context) { QStyleOptionViewItem styleContextItem(option); QBrush brush = getBrushForColorColumn(index, KateStyleTreeWidgetItem::SelectedBackground); if (brush != QBrush()) { styleContextItem.palette.setBrush(QPalette::Highlight, brush); } brush = getBrushForColorColumn(index, KateStyleTreeWidgetItem::SelectedForeground); if (brush != QBrush()) { styleContextItem.palette.setBrush(QPalette::HighlightedText, brush); } return QStyledItemDelegate::paint(painter, styleContextItem, index); } QStyledItemDelegate::paint(painter, option, index); if (!columns.contains(index.column())) { return; } QVariant displayData = index.model()->data(index); if (displayData.type() != QVariant::Brush) { return; } QBrush brush = displayData.value(); QStyleOptionButton opt; opt.rect = option.rect; opt.palette = m_widget->palette(); bool set = brush != QBrush(); if (!set) { opt.text = i18nc("No text or background color set", "None set"); brush = Qt::white; } m_widget->style()->drawControl(QStyle::CE_PushButton, &opt, painter, m_widget); if (set) { painter->fillRect(m_widget->style()->subElementRect(QStyle::SE_PushButtonContents, &opt, m_widget), brush); } } KateStyleTreeWidgetItem::KateStyleTreeWidgetItem(QTreeWidgetItem *parent, const QString &stylename, KTextEditor::Attribute::Ptr defaultAttribute, KTextEditor::Attribute::Ptr actualAttribute) : QTreeWidgetItem(parent), currentStyle(nullptr), defaultStyle(defaultAttribute), actualStyle(actualAttribute) { initStyle(); setText(0, stylename); } KateStyleTreeWidgetItem::KateStyleTreeWidgetItem(QTreeWidget *parent, const QString &stylename, KTextEditor::Attribute::Ptr defaultAttribute, KTextEditor::Attribute::Ptr actualAttribute) : QTreeWidgetItem(parent), currentStyle(nullptr), defaultStyle(defaultAttribute), actualStyle(actualAttribute) { initStyle(); setText(0, stylename); } void KateStyleTreeWidgetItem::initStyle() { if (!actualStyle) { currentStyle = defaultStyle; } else { currentStyle = new KTextEditor::Attribute(*defaultStyle); if (actualStyle->hasAnyProperty()) { *currentStyle += *actualStyle; } } setFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); } static Qt::CheckState toCheckState(bool b) { return b ? Qt::Checked : Qt::Unchecked; } QVariant KateStyleTreeWidgetItem::data(int column, int role) const { if (column == Context) { switch (role) { case Qt::ForegroundRole: if (style()->hasProperty(QTextFormat::ForegroundBrush)) { return style()->foreground().color(); } break; case Qt::BackgroundRole: if (style()->hasProperty(QTextFormat::BackgroundBrush)) { return style()->background().color(); } break; case Qt::FontRole: return style()->font(); break; } } if (role == Qt::CheckStateRole) { switch (column) { case Bold: return toCheckState(style()->fontBold()); case Italic: return toCheckState(style()->fontItalic()); case Underline: return toCheckState(style()->fontUnderline()); case StrikeOut: return toCheckState(style()->fontStrikeOut()); case UseDefaultStyle: /* can't compare all attributes, currentStyle has always more than defaultStyle (e.g. the item's name), * so we just compare the important ones:*/ return toCheckState( currentStyle->foreground() == defaultStyle->foreground() && currentStyle->background() == defaultStyle->background() && currentStyle->selectedForeground() == defaultStyle->selectedForeground() && currentStyle->selectedBackground() == defaultStyle->selectedBackground() && currentStyle->fontBold() == defaultStyle->fontBold() && currentStyle->fontItalic() == defaultStyle->fontItalic() && currentStyle->fontUnderline() == defaultStyle->fontUnderline() && currentStyle->fontStrikeOut() == defaultStyle->fontStrikeOut()); } } if (role == Qt::DisplayRole) { switch (column) { case Foreground: return style()->foreground(); case SelectedForeground: return style()->selectedForeground(); case Background: return style()->background(); case SelectedBackground: return style()->selectedBackground(); } } return QTreeWidgetItem::data(column, role); } void KateStyleTreeWidgetItem::updateStyle() { // nothing there, not update it, will crash if (!actualStyle) { return; } if (currentStyle->hasProperty(QTextFormat::FontWeight)) { if (currentStyle->fontWeight() != actualStyle->fontWeight()) { actualStyle->setFontWeight(currentStyle->fontWeight()); } } else { actualStyle->clearProperty(QTextFormat::FontWeight); } if (currentStyle->hasProperty(QTextFormat::FontItalic)) { if (currentStyle->fontItalic() != actualStyle->fontItalic()) { actualStyle->setFontItalic(currentStyle->fontItalic()); } } else { actualStyle->clearProperty(QTextFormat::FontItalic); } if (currentStyle->hasProperty(QTextFormat::FontStrikeOut)) { if (currentStyle->fontStrikeOut() != actualStyle->fontStrikeOut()) { actualStyle->setFontStrikeOut(currentStyle->fontStrikeOut()); } } else { actualStyle->clearProperty(QTextFormat::FontStrikeOut); } if (currentStyle->hasProperty(QTextFormat::FontUnderline)) { if (currentStyle->fontUnderline() != actualStyle->fontUnderline()) { actualStyle->setFontUnderline(currentStyle->fontUnderline()); } } else { actualStyle->clearProperty(QTextFormat::FontUnderline); } if (currentStyle->hasProperty(CustomProperties::Outline)) { if (currentStyle->outline() != actualStyle->outline()) { actualStyle->setOutline(currentStyle->outline()); } } else { actualStyle->clearProperty(CustomProperties::Outline); } if (currentStyle->hasProperty(QTextFormat::ForegroundBrush)) { if (currentStyle->foreground() != actualStyle->foreground()) { actualStyle->setForeground(currentStyle->foreground()); } } else { actualStyle->clearProperty(QTextFormat::ForegroundBrush); } if (currentStyle->hasProperty(CustomProperties::SelectedForeground)) { if (currentStyle->selectedForeground() != actualStyle->selectedForeground()) { actualStyle->setSelectedForeground(currentStyle->selectedForeground()); } } else { actualStyle->clearProperty(CustomProperties::SelectedForeground); } if (currentStyle->hasProperty(QTextFormat::BackgroundBrush)) { if (currentStyle->background() != actualStyle->background()) { actualStyle->setBackground(currentStyle->background()); } } else { actualStyle->clearProperty(QTextFormat::BackgroundBrush); } if (currentStyle->hasProperty(CustomProperties::SelectedBackground)) { if (currentStyle->selectedBackground() != actualStyle->selectedBackground()) { actualStyle->setSelectedBackground(currentStyle->selectedBackground()); } } else { actualStyle->clearProperty(CustomProperties::SelectedBackground); } } /* only true for a hl mode item using its default style */ bool KateStyleTreeWidgetItem::defStyle() const { return actualStyle && actualStyle->properties() != defaultStyle->properties(); } /* true for default styles */ bool KateStyleTreeWidgetItem::isDefault() const { return actualStyle ? false : true; } void KateStyleTreeWidgetItem::changeProperty(int p) { if (p == Bold) { currentStyle->setFontBold(! currentStyle->fontBold()); } else if (p == Italic) { currentStyle->setFontItalic(! currentStyle->fontItalic()); } else if (p == Underline) { currentStyle->setFontUnderline(! currentStyle->fontUnderline()); } else if (p == StrikeOut) { currentStyle->setFontStrikeOut(! currentStyle->fontStrikeOut()); } else if (p == UseDefaultStyle) { toggleDefStyle(); } else { setColor(p); } updateStyle(); treeWidget()->emitChanged(); } void KateStyleTreeWidgetItem::toggleDefStyle() { if (*currentStyle == *defaultStyle) { KMessageBox::information(treeWidget(), i18n("\"Use Default Style\" will be automatically unset when you change any style properties."), i18n("Kate Styles"), QStringLiteral("Kate hl config use defaults")); } else { currentStyle = KTextEditor::Attribute::Ptr(new KTextEditor::Attribute(*defaultStyle)); updateStyle(); QModelIndex currentIndex = treeWidget()->currentIndex(); while (currentIndex.isValid()) { treeWidget()->update(currentIndex); currentIndex = currentIndex.sibling(currentIndex.row(), currentIndex.column() - 1); } } } void KateStyleTreeWidgetItem::setColor(int column) { QColor c; // use this QColor d; // default color if (column == Foreground) { c = currentStyle->foreground().color(); d = defaultStyle->foreground().color(); } else if (column == SelectedForeground) { c = currentStyle->selectedForeground().color(); d = defaultStyle->selectedForeground().color(); } else if (column == Background) { c = currentStyle->background().color(); d = defaultStyle->background().color(); } else if (column == SelectedBackground) { c = currentStyle->selectedBackground().color(); d = defaultStyle->selectedBackground().color(); } if (!c.isValid()) { c = d; } const QColor selectedColor = QColorDialog::getColor(c, treeWidget()); if (!selectedColor.isValid()) { return; } // if set default, and the attrib is set in the default style use it // else if set default, unset it // else set the selected color switch (column) { case Foreground: currentStyle->setForeground(selectedColor); break; case SelectedForeground: currentStyle->setSelectedForeground(selectedColor); break; case Background: currentStyle->setBackground(selectedColor); break; case SelectedBackground: currentStyle->setSelectedBackground(selectedColor); break; } //FIXME //repaint(); } void KateStyleTreeWidgetItem::unsetColor(int colorId) { switch (colorId) { case 1: if (defaultStyle->hasProperty(QTextFormat::ForegroundBrush)) { currentStyle->setForeground(defaultStyle->foreground()); } else { currentStyle->clearProperty(QTextFormat::ForegroundBrush); } break; case 2: if (defaultStyle->hasProperty(CustomProperties::SelectedForeground)) { currentStyle->setSelectedForeground(defaultStyle->selectedForeground()); } else { currentStyle->clearProperty(CustomProperties::SelectedForeground); } break; case 3: if (currentStyle->hasProperty(QTextFormat::BackgroundBrush)) { currentStyle->clearProperty(QTextFormat::BackgroundBrush); } break; case 4: if (currentStyle->hasProperty(CustomProperties::SelectedBackground)) { currentStyle->clearProperty(CustomProperties::SelectedBackground); } break; } updateStyle(); treeWidget()->emitChanged(); } KateStyleTreeWidget *KateStyleTreeWidgetItem::treeWidget() const { return static_cast(QTreeWidgetItem::treeWidget()); } //END diff --git a/src/schema/katestyletreewidget.h b/src/schema/katestyletreewidget.h index a067993f..8cc78058 100644 --- a/src/schema/katestyletreewidget.h +++ b/src/schema/katestyletreewidget.h @@ -1,82 +1,82 @@ /* This file is part of the KDE libraries Copyright (C) 2001-2003 Christoph Cullmann Copyright (C) 2002, 2003 Anders Lund Copyright (C) 2005-2006 Hamish Rodda Copyright (C) 2007 Mirko Stocker * * 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. * * 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. * * 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. */ #ifndef KATESTYLETREEWIDGET_H #define KATESTYLETREEWIDGET_H #include #include "kateextendedattribute.h" /** * QTreeWidget that automatically adds columns for KateStyleListItems and provides a * popup menu and a slot to edit a style using the keyboard. * Added by anders, jan 23 2002. */ class KateStyleTreeWidget : public QTreeWidget { Q_OBJECT friend class KateStyleListItem; public: explicit KateStyleTreeWidget(QWidget *parent = nullptr, bool showUseDefaults = false); void emitChanged(); void setBgCol(const QColor &c) { bgcol = c; } void setSelCol(const QColor &c) { selcol = c; } void setNormalCol(const QColor &c) { normalcol = c; } void addItem(QTreeWidgetItem *parent, const QString &styleName, KTextEditor::Attribute::Ptr defaultstyle, KTextEditor::Attribute::Ptr data = KTextEditor::Attribute::Ptr()); void addItem(const QString &styleName, KTextEditor::Attribute::Ptr defaultstyle, KTextEditor::Attribute::Ptr data = KTextEditor::Attribute::Ptr()); void resizeColumns(); Q_SIGNALS: void changed(); protected: - void contextMenuEvent(QContextMenuEvent *event) Q_DECL_OVERRIDE; - void showEvent(QShowEvent *event) Q_DECL_OVERRIDE; - bool edit(const QModelIndex &index, EditTrigger trigger, QEvent *event) Q_DECL_OVERRIDE; + void contextMenuEvent(QContextMenuEvent *event) override; + void showEvent(QShowEvent *event) override; + bool edit(const QModelIndex &index, EditTrigger trigger, QEvent *event) override; private Q_SLOTS: void changeProperty(); void unsetColor(); void updateGroupHeadings(); private: QColor bgcol, selcol, normalcol; QFont docfont; }; #endif diff --git a/src/script/katecommandlinescript.h b/src/script/katecommandlinescript.h index 0e98e176..f631d6db 100644 --- a/src/script/katecommandlinescript.h +++ b/src/script/katecommandlinescript.h @@ -1,86 +1,86 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2009 Dominik Haumann * * 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. * * 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. * * 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. */ #ifndef KATE_COMMANDLINE_SCRIPT_H #define KATE_COMMANDLINE_SCRIPT_H #include "katescript.h" #include "kateview.h" #include #include class KateCommandLineScriptHeader { public: KateCommandLineScriptHeader() {} inline void setFunctions(const QStringList &functions) { m_functions = functions; } inline const QStringList &functions() const { return m_functions; } inline void setActions(const QJsonArray &actions) { m_actions = actions; } inline const QJsonArray &actions() const { return m_actions; } private: QStringList m_functions; ///< the functions the script contains QJsonArray m_actions; ///< the action for this script }; /** * A specialized class for scripts that are of type * KateScriptInformation::IndentationScript */ class KateCommandLineScript : public KateScript, public KTextEditor::Command { public: KateCommandLineScript(const QString &url, const KateCommandLineScriptHeader &header); - ~KateCommandLineScript() Q_DECL_OVERRIDE; + ~KateCommandLineScript() override; const KateCommandLineScriptHeader &commandHeader(); bool callFunction(const QString &cmd, const QStringList args, QString &errorMessage); // // KTextEditor::Command interface // public: - bool help(KTextEditor::View *view, const QString &cmd, QString &msg) Q_DECL_OVERRIDE; - bool exec(KTextEditor::View *view, const QString &cmd, QString &msg, const KTextEditor::Range &range = KTextEditor::Range::invalid()) Q_DECL_OVERRIDE; - bool supportsRange(const QString &cmd) Q_DECL_OVERRIDE; + bool help(KTextEditor::View *view, const QString &cmd, QString &msg) override; + bool exec(KTextEditor::View *view, const QString &cmd, QString &msg, const KTextEditor::Range &range = KTextEditor::Range::invalid()) override; + bool supportsRange(const QString &cmd) override; private: KateCommandLineScriptHeader m_commandHeader; }; #endif diff --git a/src/script/katescriptmanager.h b/src/script/katescriptmanager.h index f2724ba0..a9e24ad9 100644 --- a/src/script/katescriptmanager.h +++ b/src/script/katescriptmanager.h @@ -1,140 +1,140 @@ // This file is part of the KDE libraries // Copyright (C) 2008 Paul Giannaros // Copyright (C) 2009 Dominik Haumann // Copyright (C) 2010 Joseph Wenninger // // 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) version 3. // // 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. // // 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. #ifndef KATE_SCRIPT_MANAGER_H #define KATE_SCRIPT_MANAGER_H #include #include #include #include "katescript.h" #include "kateindentscript.h" #include "katecommandlinescript.h" class QString; /** * Manage the scripts on disks -- find them and query them. * Provides access to loaded scripts too. */ class KateScriptManager : public KTextEditor::Command { Q_OBJECT KateScriptManager(); static KateScriptManager *m_instance; public: - ~KateScriptManager() Q_DECL_OVERRIDE; + ~KateScriptManager() override; /** Get all scripts available in the command line */ const QVector &commandLineScripts() { return m_commandLineScripts; } /** * Get an indentation script for the given language -- if there is more than * one result, this will return the script with the highest priority. If * both have the same priority, an arbitrary script will be returned. * If no scripts are found, 0 is returned. */ KateIndentScript *indenter(const QString &language); // // KTextEditor::Command // public: /** * execute command * @param view view to use for execution * @param cmd cmd string * @param errorMsg error to return if no success * @return success */ - bool exec(KTextEditor::View *view, const QString &cmd, QString &errorMsg, const KTextEditor::Range &) Q_DECL_OVERRIDE; + bool exec(KTextEditor::View *view, const QString &cmd, QString &errorMsg, const KTextEditor::Range &) override; /** * get help for a command * @param view view to use * @param cmd cmd name * @param msg help message * @return help available or not */ - bool help(KTextEditor::View *view, const QString &cmd, QString &msg) Q_DECL_OVERRIDE; + bool help(KTextEditor::View *view, const QString &cmd, QString &msg) override; static KateScriptManager *self() { if (m_instance == nullptr) { m_instance = new KateScriptManager(); } return m_instance; } // // Helper methods // public: /** * Collect all scripts. */ void collect(); public: KateIndentScript *indentationScript(const QString &scriptname) { return m_indentationScriptMap.value(scriptname); } int indentationScriptCount() { return m_indentationScripts.size(); } KateIndentScript *indentationScriptByIndex(int index) { return m_indentationScripts[index]; } public: /** explicitly reload all scripts */ void reload(); Q_SIGNALS: /** this signal is emitted when all scripts are _deleted_ and reloaded again. */ void reloaded(); private: /** List of all command line scripts */ QVector m_commandLineScripts; /** list of all indentation scripts */ QList m_indentationScripts; /** hash of all existing indenter scripts, hashes basename -> script */ QHash m_indentationScriptMap; /** Map of language to indent scripts */ QHash > m_languageToIndenters; }; #endif diff --git a/src/search/katesearchbar.h b/src/search/katesearchbar.h index e70f9957..0f38d1e1 100644 --- a/src/search/katesearchbar.h +++ b/src/search/katesearchbar.h @@ -1,210 +1,210 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2009-2010 Bernhard Beschow * Copyright (C) 2007 Sebastian Pipping * * 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. * * 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. * * 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. */ #ifndef KATE_SEARCH_BAR_H #define KATE_SEARCH_BAR_H 1 #include "kateviewhelpers.h" #include #include #include namespace KTextEditor { class ViewPrivate; } class KateViewConfig; class QVBoxLayout; class QComboBox; namespace Ui { class IncrementalSearchBar; class PowerSearchBar; } namespace KTextEditor { class MovingRange; class Message; } class KTEXTEDITOR_EXPORT KateSearchBar : public KateViewBarWidget { Q_OBJECT friend class SearchBarTest; public: enum SearchMode { // NOTE: Concrete values are important here // to work with the combobox index! MODE_PLAIN_TEXT = 0, MODE_WHOLE_WORDS = 1, MODE_ESCAPE_SEQUENCES = 2, MODE_REGEX = 3 }; enum MatchResult { MatchFound, MatchWrappedForward, MatchWrappedBackward, MatchMismatch, MatchNothing, MatchNeutral }; enum SearchDirection { SearchForward, SearchBackward }; public: explicit KateSearchBar(bool initAsPower, KTextEditor::ViewPrivate *view, KateViewConfig *config); ~KateSearchBar(); - void closed() Q_DECL_OVERRIDE; + void closed() override; bool isPower() const; QString searchPattern() const; QString replacementPattern() const; bool selectionOnly() const; bool matchCase() const; // Only used by KTextEditor::ViewPrivate static void nextMatchForSelection(KTextEditor::ViewPrivate *view, SearchDirection searchDirection); public Q_SLOTS: /** * Set the current search pattern. * @param searchPattern the search pattern */ void setSearchPattern(const QString &searchPattern); /** * Set the current replacement pattern. * @param replacementPattern the replacement pattern */ void setReplacementPattern(const QString &replacementPattern); void setSearchMode(SearchMode mode); void setSelectionOnly(bool selectionOnly); void setMatchCase(bool matchCase); // Called for and + void findNext(); void findPrevious(); void findAll(); void replaceNext(); void replaceAll(); // Also used by KTextEditor::ViewPrivate void enterPowerMode(); void enterIncrementalMode(); bool clearHighlights(); void updateHighlightColors(); // read write status of document changed void slotReadWriteChanged(); protected: // Overridden - void showEvent(QShowEvent *event) Q_DECL_OVERRIDE; + void showEvent(QShowEvent *event) override; private Q_SLOTS: void onIncPatternChanged(const QString &pattern); void onMatchCaseToggled(bool matchCase); void onReturnPressed(); void updateSelectionOnly(); void updateIncInitCursor(); void onPowerPatternChanged(const QString &pattern); void onPowerModeChanged(int index); void onPowerPatternContextMenuRequest(); void onPowerPatternContextMenuRequest(const QPoint &); void onPowerReplacmentContextMenuRequest(); void onPowerReplacmentContextMenuRequest(const QPoint &); private: // Helpers bool find(SearchDirection searchDirection = SearchForward, const QString *replacement = nullptr); int findAll(KTextEditor::Range inputRange, const QString *replacement); bool isPatternValid() const; KTextEditor::SearchOptions searchOptions(SearchDirection searchDirection = SearchForward) const; void highlightMatch(const KTextEditor::Range &range); void highlightReplacement(const KTextEditor::Range &range); void indicateMatch(MatchResult matchResult); static void selectRange(KTextEditor::ViewPrivate *view, const KTextEditor::Range &range); void selectRange2(const KTextEditor::Range &range); QVector getCapturePatterns(const QString &pattern) const; void showExtendedContextMenu(bool forPattern, const QPoint &pos); void givePatternFeedback(); void addCurrentTextToHistory(QComboBox *combo); void backupConfig(bool ofPower); void sendConfig(); void fixForSingleLine(KTextEditor::Range &range, SearchDirection searchDirection); void showInfoMessage(const QString &text); private: KTextEditor::ViewPrivate *const m_view; KateViewConfig *const m_config; QList m_hlRanges; QPointer m_infoMessage; QPointer m_wrappedTopMessage; QPointer m_wrappedBottomMessage; // Shared by both dialogs QVBoxLayout *const m_layout; QWidget *m_widget; // Incremental search related Ui::IncrementalSearchBar *m_incUi; KTextEditor::Cursor m_incInitCursor; // Power search related Ui::PowerSearchBar *m_powerUi; // attribute to highlight matches with KTextEditor::Attribute::Ptr highlightMatchAttribute; KTextEditor::Attribute::Ptr highlightReplacementAttribute; // Status backup bool m_incHighlightAll : 1; bool m_incFromCursor : 1; bool m_incMatchCase : 1; bool m_powerMatchCase : 1; bool m_powerFromCursor : 1; bool m_powerHighlightAll : 1; unsigned int m_powerMode : 2; }; #endif // KATE_SEARCH_BAR_H diff --git a/src/spellcheck/ontheflycheck.h b/src/spellcheck/ontheflycheck.h index 4bd38494..2fd2d384 100644 --- a/src/spellcheck/ontheflycheck.h +++ b/src/spellcheck/ontheflycheck.h @@ -1,141 +1,141 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2008-2010 by Michel Ludwig * Copyright (C) 2009 by Joseph Wenninger * * 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. * * 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. * * 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. */ #ifndef ONTHEFLYCHECK_H #define ONTHEFLYCHECK_H #include #include #include #include #include #include #include #include "katedocument.h" namespace Sonnet { class BackgroundChecker; } class KateOnTheFlyChecker : public QObject, private KTextEditor::MovingRangeFeedback { Q_OBJECT enum ModificationType {TEXT_INSERTED = 0, TEXT_REMOVED}; typedef QPair SpellCheckItem; typedef QList MovingRangeList; typedef QPair MisspelledItem; typedef QList MisspelledList; typedef QPair ModificationItem; typedef QList ModificationList; public: explicit KateOnTheFlyChecker(KTextEditor::DocumentPrivate *document); - ~KateOnTheFlyChecker() Q_DECL_OVERRIDE; + ~KateOnTheFlyChecker() override; QPair getMisspelledItem(const KTextEditor::Cursor &cursor) const; QString dictionaryForMisspelledRange(const KTextEditor::Range &range) const; void clearMisspellingForWord(const QString &word); public Q_SLOTS: void textInserted(KTextEditor::Document *document, const KTextEditor::Range &range); void textRemoved(KTextEditor::Document *document, const KTextEditor::Range &range); void updateConfig(); void refreshSpellCheck(const KTextEditor::Range &range = KTextEditor::Range::invalid()); void updateInstalledMovingRanges(KTextEditor::ViewPrivate *view); protected: KTextEditor::DocumentPrivate *const m_document; Sonnet::Speller m_speller; QList m_spellCheckQueue; Sonnet::BackgroundChecker *m_backgroundChecker; SpellCheckItem m_currentlyCheckedItem; MisspelledList m_misspelledList; ModificationList m_modificationList; KTextEditor::DocumentPrivate::OffsetList m_currentDecToEncOffsetList; QMap m_displayRangeMap; void freeDocument(); MovingRangeList installedMovingRanges(const KTextEditor::Range &range); void queueLineSpellCheck(KTextEditor::DocumentPrivate *document, int line); /** * 'range' must be on a single line **/ void queueLineSpellCheck(const KTextEditor::Range &range, const QString &dictionary); void queueSpellCheckVisibleRange(const KTextEditor::Range &range); void queueSpellCheckVisibleRange(KTextEditor::ViewPrivate *view, const KTextEditor::Range &range); void addToSpellCheckQueue(const KTextEditor::Range &range, const QString &dictionary); void addToSpellCheckQueue(KTextEditor::MovingRange *range, const QString &dictionary); QTimer *m_viewRefreshTimer; QPointer m_refreshView; virtual void removeRangeFromEverything(KTextEditor::MovingRange *range); bool removeRangeFromCurrentSpellCheck(KTextEditor::MovingRange *range); bool removeRangeFromSpellCheckQueue(KTextEditor::MovingRange *range); - void rangeEmpty(KTextEditor::MovingRange *range) Q_DECL_OVERRIDE; - void rangeInvalid(KTextEditor::MovingRange *range) Q_DECL_OVERRIDE; - void mouseEnteredRange(KTextEditor::MovingRange *range, KTextEditor::View *view) Q_DECL_OVERRIDE; - void mouseExitedRange(KTextEditor::MovingRange *range, KTextEditor::View *view) Q_DECL_OVERRIDE; - void caretEnteredRange(KTextEditor::MovingRange *range, KTextEditor::View *view) Q_DECL_OVERRIDE; - void caretExitedRange(KTextEditor::MovingRange *range, KTextEditor::View *view) Q_DECL_OVERRIDE; + void rangeEmpty(KTextEditor::MovingRange *range) override; + void rangeInvalid(KTextEditor::MovingRange *range) override; + void mouseEnteredRange(KTextEditor::MovingRange *range, KTextEditor::View *view) override; + void mouseExitedRange(KTextEditor::MovingRange *range, KTextEditor::View *view) override; + void caretEnteredRange(KTextEditor::MovingRange *range, KTextEditor::View *view) override; + void caretExitedRange(KTextEditor::MovingRange *range, KTextEditor::View *view) override; KTextEditor::Range findWordBoundaries(const KTextEditor::Cursor &begin, const KTextEditor::Cursor &end); void deleteMovingRange(KTextEditor::MovingRange *range); void deleteMovingRanges(const QList &list); void deleteMovingRangeQuickly(KTextEditor::MovingRange *range); void stopCurrentSpellCheck(); protected Q_SLOTS: void performSpellCheck(); void misspelling(const QString &word, int start); void spellCheckDone(); void viewDestroyed(QObject *obj); void addView(KTextEditor::Document *document, KTextEditor::View *view); void removeView(KTextEditor::View *view); void restartViewRefreshTimer(KTextEditor::ViewPrivate *view); void viewRefreshTimeout(); void handleModifiedRanges(); void handleInsertedText(const KTextEditor::Range &range); void handleRemovedText(const KTextEditor::Range &range); void handleRespellCheckBlock(int start, int end); bool removeRangeFromModificationList(KTextEditor::MovingRange *range); void clearModificationList(); }; #endif diff --git a/src/spellcheck/spellcheckbar.cpp b/src/spellcheck/spellcheckbar.cpp index 0c87f9e3..20132632 100644 --- a/src/spellcheck/spellcheckbar.cpp +++ b/src/spellcheck/spellcheckbar.cpp @@ -1,453 +1,453 @@ /** * Copyright (C) 2003 Zack Rusin * Copyright (C) 2009-2010 Michel Ludwig * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "spellcheckbar.h" #include "ui_spellcheckbar.h" #include #include "sonnet/backgroundchecker.h" #include "sonnet/speller.h" /* #include "sonnet/filter_p.h" #include "sonnet/settings_p.h" */ #include #include #include #include #include #include #include #include #include //to initially disable sorting in the suggestions listview #define NONSORTINGCOLUMN 2 class ReadOnlyStringListModel: public QStringListModel { public: ReadOnlyStringListModel(QObject *parent): QStringListModel(parent) {} - Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE + Qt::ItemFlags flags(const QModelIndex &index) const override { Q_UNUSED(index); return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } }; /** * Structure abstracts the word and its position in the * parent text. * * @author Zack Rusin * @short struct represents word */ struct Word { Word() {} Word(const QString &w, int st, bool e = false) : word(w), start(st), end(e) {} Word(const Word &other) : word(other.word), start(other.start), end(other.end) {} QString word; int start = 0; bool end = true; }; class SpellCheckBar::Private { public: Ui_SonnetUi ui; ReadOnlyStringListModel *suggestionsModel; QWidget *wdg; QDialogButtonBox *buttonBox; QProgressDialog *progressDialog; QString originalBuffer; Sonnet::BackgroundChecker *checker; Word currentWord; QMap replaceAllMap; bool restart;//used when text is distributed across several qtextedits, eg in KAider QMap dictsMap; int progressDialogTimeout; bool showCompletionMessageBox; bool spellCheckContinuedAfterReplacement; bool canceled; void deleteProgressDialog(bool directly) { if (progressDialog) { progressDialog->hide(); if (directly) { delete progressDialog; } else { progressDialog->deleteLater(); } progressDialog = nullptr; } } }; SpellCheckBar::SpellCheckBar(Sonnet::BackgroundChecker *checker, QWidget *parent) : KateViewBarWidget(true, parent), d(new Private) { d->checker = checker; d->canceled = false; d->showCompletionMessageBox = false; d->spellCheckContinuedAfterReplacement = true; d->progressDialogTimeout = -1; d->progressDialog = nullptr; initGui(); initConnections(); } SpellCheckBar::~SpellCheckBar() { delete d; } void SpellCheckBar::closed() { if (viewBar()) { viewBar()->removeBarWidget(this); } // called from hideMe, so don't call it again! d->canceled = true; d->deleteProgressDialog(false); // this method can be called in response to d->replaceAllMap.clear(); // pressing 'Cancel' on the dialog emit cancel(); emit spellCheckStatus(i18n("Spell check canceled.")); } void SpellCheckBar::initConnections() { connect(d->ui.m_addBtn, SIGNAL(clicked()), SLOT(slotAddWord())); connect(d->ui.m_replaceBtn, SIGNAL(clicked()), SLOT(slotReplaceWord())); connect(d->ui.m_replaceAllBtn, SIGNAL(clicked()), SLOT(slotReplaceAll())); connect(d->ui.m_skipBtn, SIGNAL(clicked()), SLOT(slotSkip())); connect(d->ui.m_skipAllBtn, SIGNAL(clicked()), SLOT(slotSkipAll())); connect(d->ui.m_suggestBtn, SIGNAL(clicked()), SLOT(slotSuggest())); connect(d->ui.m_language, SIGNAL(activated(QString)), SLOT(slotChangeLanguage(QString))); connect(d->checker, SIGNAL(misspelling(QString,int)), SLOT(slotMisspelling(QString,int))); connect(d->checker, SIGNAL(done()), SLOT(slotDone())); /* connect(d->ui.m_suggestions, SIGNAL(doubleClicked(QModelIndex)), SLOT(slotReplaceWord())); */ connect(d->ui.cmbReplacement, SIGNAL(returnPressed()), this, SLOT(slotReplaceWord())); connect(d->ui.m_autoCorrect, SIGNAL(clicked()), SLOT(slotAutocorrect())); // button use by kword/kpresenter // hide by default d->ui.m_autoCorrect->hide(); } void SpellCheckBar::initGui() { QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); centralWidget()->setLayout(layout); d->wdg = new QWidget(this); d->ui.setupUi(d->wdg); layout->addWidget(d->wdg); setGuiEnabled(false); /* d->buttonBox = new QDialogButtonBox(this); d->buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); layout->addWidget(d->buttonBox); */ //d->ui.m_suggestions->setSorting( NONSORTINGCOLUMN ); fillDictionaryComboBox(); d->restart = false; d->suggestionsModel = new ReadOnlyStringListModel(this); d->ui.cmbReplacement->setModel(d->suggestionsModel); } void SpellCheckBar::activeAutoCorrect(bool _active) { if (_active) { d->ui.m_autoCorrect->show(); } else { d->ui.m_autoCorrect->hide(); } } void SpellCheckBar::showProgressDialog(int timeout) { d->progressDialogTimeout = timeout; } void SpellCheckBar::showSpellCheckCompletionMessage(bool b) { d->showCompletionMessageBox = b; } void SpellCheckBar::setSpellCheckContinuedAfterReplacement(bool b) { d->spellCheckContinuedAfterReplacement = b; } void SpellCheckBar::slotAutocorrect() { setGuiEnabled(false); setProgressDialogVisible(true); emit autoCorrect(d->currentWord.word, d->ui.cmbReplacement->lineEdit()->text()); slotReplaceWord(); } void SpellCheckBar::setGuiEnabled(bool b) { d->wdg->setEnabled(b); } void SpellCheckBar::setProgressDialogVisible(bool b) { if (!b) { d->deleteProgressDialog(true); } else if (d->progressDialogTimeout >= 0) { if (d->progressDialog) { return; } d->progressDialog = new QProgressDialog(this); d->progressDialog->setLabelText(i18nc("progress label", "Spell checking in progress...")); d->progressDialog->setWindowTitle(i18nc("@title:window", "Check Spelling")); d->progressDialog->setModal(true); d->progressDialog->setAutoClose(false); d->progressDialog->setAutoReset(false); // create an 'indefinite' progress box as we currently cannot get progress feedback from // the speller d->progressDialog->reset(); d->progressDialog->setRange(0, 0); d->progressDialog->setValue(0); connect(d->progressDialog, SIGNAL(canceled()), this, SLOT(slotCancel())); d->progressDialog->setMinimumDuration(d->progressDialogTimeout); } } void SpellCheckBar::slotCancel() { hideMe(); } QString SpellCheckBar::originalBuffer() const { return d->originalBuffer; } QString SpellCheckBar::buffer() const { return d->checker->text(); } void SpellCheckBar::setBuffer(const QString &buf) { d->originalBuffer = buf; //it is possible to change buffer inside slot connected to done() signal d->restart = true; } void SpellCheckBar::fillDictionaryComboBox() { Sonnet::Speller speller = d->checker->speller(); d->dictsMap = speller.availableDictionaries(); QStringList langs = d->dictsMap.keys(); d->ui.m_language->clear(); d->ui.m_language->addItems(langs); updateDictionaryComboBox(); } void SpellCheckBar::updateDictionaryComboBox() { Sonnet::Speller speller = d->checker->speller(); d->ui.m_language->setCurrentIndex(d->dictsMap.values().indexOf(speller.language())); } void SpellCheckBar::updateDialog(const QString &word) { d->ui.m_unknownWord->setText(word); //d->ui.m_contextLabel->setText(d->checker->currentContext()); const QStringList suggs = d->checker->suggest(word); if (suggs.isEmpty()) { d->ui.cmbReplacement->lineEdit()->clear(); } else { d->ui.cmbReplacement->lineEdit()->setText(suggs.first()); } fillSuggestions(suggs); } void SpellCheckBar::show() { d->canceled = false; fillDictionaryComboBox(); updateDictionaryComboBox(); if (d->originalBuffer.isEmpty()) { d->checker->start(); } else { d->checker->setText(d->originalBuffer); } setProgressDialogVisible(true); } void SpellCheckBar::slotAddWord() { setGuiEnabled(false); setProgressDialogVisible(true); d->checker->addWordToPersonal(d->currentWord.word); d->checker->continueChecking(); } void SpellCheckBar::slotReplaceWord() { setGuiEnabled(false); setProgressDialogVisible(true); const QString replacementText = d->ui.cmbReplacement->lineEdit()->text(); emit replace(d->currentWord.word, d->currentWord.start, replacementText); if (d->spellCheckContinuedAfterReplacement) { d->checker->replace(d->currentWord.start, d->currentWord.word, replacementText); d->checker->continueChecking(); } else { setProgressDialogVisible(false); d->checker->stop(); } } void SpellCheckBar::slotReplaceAll() { setGuiEnabled(false); setProgressDialogVisible(true); d->replaceAllMap.insert(d->currentWord.word, d->ui.cmbReplacement->lineEdit()->text()); slotReplaceWord(); } void SpellCheckBar::slotSkip() { setGuiEnabled(false); setProgressDialogVisible(true); d->checker->continueChecking(); } void SpellCheckBar::slotSkipAll() { setGuiEnabled(false); setProgressDialogVisible(true); //### do we want that or should we have a d->ignoreAll list? Sonnet::Speller speller = d->checker->speller(); speller.addToPersonal(d->currentWord.word); d->checker->setSpeller(speller); d->checker->continueChecking(); } void SpellCheckBar::slotSuggest() { QStringList suggs = d->checker->suggest(d->ui.cmbReplacement->lineEdit()->text()); fillSuggestions(suggs); } void SpellCheckBar::slotChangeLanguage(const QString &lang) { Sonnet::Speller speller = d->checker->speller(); QString languageCode = d->dictsMap[lang]; if (!languageCode.isEmpty()) { d->checker->changeLanguage(languageCode); slotSuggest(); emit languageChanged(languageCode); } } void SpellCheckBar::fillSuggestions(const QStringList &suggs) { d->suggestionsModel->setStringList(suggs); if (!suggs.isEmpty()) { d->ui.cmbReplacement->setCurrentIndex(0); } } void SpellCheckBar::slotMisspelling(const QString &word, int start) { setGuiEnabled(true); setProgressDialogVisible(false); emit misspelling(word, start); //NOTE this is HACK I had to introduce because BackgroundChecker lacks 'virtual' marks on methods //this dramatically reduces spellchecking time in Lokalize //as this doesn't fetch suggestions for words that are present in msgid if (!updatesEnabled()) { return; } d->currentWord = Word(word, start); if (d->replaceAllMap.contains(word)) { d->ui.cmbReplacement->lineEdit()->setText(d->replaceAllMap[ word ]); slotReplaceWord(); } else { updateDialog(word); } } void SpellCheckBar::slotDone() { d->restart = false; emit done(d->checker->text()); if (d->restart) { updateDictionaryComboBox(); d->checker->setText(d->originalBuffer); d->restart = false; } else { setProgressDialogVisible(false); emit spellCheckStatus(i18n("Spell check complete.")); hideMe(); if (!d->canceled && d->showCompletionMessageBox) { QMessageBox::information(this, i18n("Spell check complete."), i18nc("@title:window", "Check Spelling")); } } } diff --git a/src/spellcheck/spellcheckbar.h b/src/spellcheck/spellcheckbar.h index 8fdf409c..94afc268 100644 --- a/src/spellcheck/spellcheckbar.h +++ b/src/spellcheck/spellcheckbar.h @@ -1,160 +1,160 @@ /* * Copyright (C) 2003 Zack Rusin * Copyright (C) 2009-2010 Michel Ludwig * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef SONNET_DIALOG_H #define SONNET_DIALOG_H #include "kateviewhelpers.h" class QListWidgetItem; class QModelIndex; namespace Sonnet { class BackgroundChecker; } /** * @short Spellcheck dialog * * \code * Sonnet::SpellCheckBar dlg = new Sonnet::SpellCheckBar( * new Sonnet::BackgroundChecker(this), this); * //connect signals * ... * dlg->setBuffer( someText ); * dlg->show(); * \endcode * * You can change buffer inside a slot connected to done() signal * and spellcheck will continue with new data automatically. */ class SpellCheckBar : public KateViewBarWidget { Q_OBJECT public: SpellCheckBar(Sonnet::BackgroundChecker *checker, QWidget *parent); - ~SpellCheckBar() Q_DECL_OVERRIDE; + ~SpellCheckBar() override; QString originalBuffer() const; QString buffer() const; - void closed() Q_DECL_OVERRIDE; + void closed() override; void show(); void activeAutoCorrect(bool _active); /** * Controls whether an (indefinite) progress dialog is shown when the spell * checking takes longer than the given time to complete. By default no * progress dialog is shown. If the progress dialog is set to be shown, no * time consuming operation (for example, showing a notification message) should * be performed in a slot connected to the 'done' signal as this might trigger * the progress dialog unnecessarily. * * @param timeout time after which the progress dialog should appear; a negative * value can be used to hide it * @since 4.4 */ void showProgressDialog(int timeout = 500); /** * Controls whether a message box indicating the completion of the spell checking * is shown or not. By default it is not shown. * * @since 4.4 */ void showSpellCheckCompletionMessage(bool b = true); /** * Controls whether the spell checking is continued after the replacement of a * misspelled word has been performed. By default it is continued. * * @since 4.4 */ void setSpellCheckContinuedAfterReplacement(bool b); public Q_SLOTS: void setBuffer(const QString &); Q_SIGNALS: /** * The dialog won't be closed if you setBuffer() in slot connected to this signal * * Also emitted after stop() signal */ void done(const QString &newBuffer); void misspelling(const QString &word, int start); void replace(const QString &oldWord, int start, const QString &newWord); void stop(); void cancel(); void autoCorrect(const QString ¤tWord, const QString &replaceWord); /** * Signal sends when spell checking is finished/stopped/completed * @since 4.1 */ void spellCheckStatus(const QString &); /** * Emitted when the user changes the language used for spellchecking, * which is shown in a combobox of this dialog. * * @param language the new language the user selected * @since 4.1 */ void languageChanged(const QString &language); private Q_SLOTS: void slotMisspelling(const QString &word, int start); void slotDone(); void slotCancel(); void slotAddWord(); void slotReplaceWord(); void slotReplaceAll(); void slotSkip(); void slotSkipAll(); void slotSuggest(); void slotChangeLanguage(const QString &); void slotAutocorrect(); void setGuiEnabled(bool b); void setProgressDialogVisible(bool b); private: void updateDialog(const QString &word); void fillDictionaryComboBox(); void updateDictionaryComboBox(); void fillSuggestions(const QStringList &suggs); void initConnections(); void initGui(); void continueChecking(); private: class Private; Private *const d; Q_DISABLE_COPY(SpellCheckBar) }; #endif diff --git a/src/syntax/katehighlighthelpers.h b/src/syntax/katehighlighthelpers.h index 029adff9..d38388ab 100644 --- a/src/syntax/katehighlighthelpers.h +++ b/src/syntax/katehighlighthelpers.h @@ -1,378 +1,378 @@ /* This file is part of the KDE libraries Copyright (C) 2001,2002 Joseph Wenninger Copyright (C) 2001 Christoph Cullmann Copyright (C) 1999 Jochen Wilhelmy * * 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. * * 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. * * 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. */ #ifndef __KATE_HIGHLIGHTHELPERS_H__ #define __KATE_HIGHLIGHTHELPERS_H__ #include "katehighlight.h" #include class KateHlItem { public: KateHlItem(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2); virtual ~KateHlItem(); public: // caller must keep in mind: LEN > 0 is a must !!!!!!!!!!!!!!!!!!!!!1 // Now, the function returns the offset detected, or 0 if no match is found. // bool linestart isn't needed, this is equivalent to offset == 0. virtual int checkHgl(const QString &text, int offset, int len) = 0; virtual bool lineContinue() { return false; } virtual void capturedTexts(QStringList &) { } virtual KateHlItem *clone(const QStringList *) { return this; } static void dynamicSubstitute(QString &str, const QStringList *args); QVector subItems; int attr; KateHlContextModification ctx; signed char region; signed char region2; bool lookAhead; bool dynamic; bool dynamicChild; bool firstNonSpace; bool onlyConsume; int column; // start enable flags, nicer than the virtual methodes // saves function calls bool alwaysStartEnable; bool customStartEnable; // set to true when you cached something bool haveCache; // internal for doHighlight, don't set it in the items bool cachingHandled; }; class KateHlContext { public: KateHlContext(const QString &_hlId, int attribute, KateHlContextModification _lineEndContext, bool _fallthrough, KateHlContextModification _fallthroughContext, bool _dynamic, bool _noIndentationBasedFolding, bool _emptyLineContex, KateHlContextModification _emptyLineContextModification ); virtual ~KateHlContext(); KateHlContext *clone(const QStringList *args); QVector items; QString hlId; ///< A unique highlight identifier. Used to look up correct properties. int attr; KateHlContextModification lineEndContext; /** @internal anders: possible escape if no rules matches. false unless 'fallthrough="1|true"' (insensitive) if true, go to ftcxt w/o eating of string. ftctx is "fallthroughContext" in xml files, valid values are int or #pop[..] see in KateHighlighting::doHighlight */ bool fallthrough; KateHlContextModification ftctx; // where to go after no rules matched bool dynamic; bool dynamicChild; bool noIndentationBasedFolding; bool emptyLineContext; KateHlContextModification emptyLineContextModification; }; class KateHlIncludeRule { public: explicit KateHlIncludeRule(int ctx_ = 0, uint pos_ = 0, const QString &incCtxN_ = QString(), bool incAttrib = false) : ctx(ctx_) , pos(pos_) , incCtxN(incCtxN_) , includeAttrib(incAttrib) { incCtx = -1; } //KateHlIncludeRule(int ctx_, uint pos_, bool incAttrib) {ctx=ctx_;pos=pos_;incCtx=-1;incCtxN="";includeAttrib=incAttrib} public: int ctx; uint pos; KateHlContextModification incCtx; QString incCtxN; bool includeAttrib; }; class KateHlCharDetect : public KateHlItem { public: KateHlCharDetect(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2, QChar); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; - KateHlItem *clone(const QStringList *args) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; + KateHlItem *clone(const QStringList *args) override; private: QChar sChar; }; class KateHl2CharDetect : public KateHlItem { public: KateHl2CharDetect(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2, QChar ch1, QChar ch2); KateHl2CharDetect(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2, const QChar *ch); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; - KateHlItem *clone(const QStringList *args) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; + KateHlItem *clone(const QStringList *args) override; private: QChar sChar1; QChar sChar2; }; class KateHlStringDetect : public KateHlItem { public: KateHlStringDetect(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2, const QString &, bool inSensitive = false); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; - KateHlItem *clone(const QStringList *args) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; + KateHlItem *clone(const QStringList *args) override; protected: const QString str; const int strLen; const bool _inSensitive; }; class KateHlWordDetect : public KateHlStringDetect { public: KateHlWordDetect(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2, const QString &, bool inSensitive = false); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; - KateHlItem *clone(const QStringList *args) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; + KateHlItem *clone(const QStringList *args) override; }; class KateHlRangeDetect : public KateHlItem { public: KateHlRangeDetect(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2, QChar ch1, QChar ch2); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; private: QChar sChar1; QChar sChar2; }; class KateHlKeyword : public KateHlItem { public: KateHlKeyword(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2, bool insensitive, const QString &delims); virtual ~KateHlKeyword(); QSet allKeywords() const; void addList(const QStringList &); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; private: QVector< QSet* > dict; bool _insensitive; QSet deliminators; int minLen; int maxLen; }; class KateHlInt : public KateHlItem { public: KateHlInt(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; }; class KateHlFloat : public KateHlItem { public: KateHlFloat(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2); virtual ~KateHlFloat() {} - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; }; class KateHlCFloat : public KateHlFloat { public: KateHlCFloat(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; int checkIntHgl(const QString &text, int offset, int len); }; class KateHlCOct : public KateHlItem { public: KateHlCOct(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; }; class KateHlCHex : public KateHlItem { public: KateHlCHex(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; }; class KateHlLineContinue : public KateHlItem { public: KateHlLineContinue(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2, QChar c); virtual bool endEnable(QChar c) { return c == QLatin1Char('\0'); } - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; - bool lineContinue() Q_DECL_OVERRIDE + int checkHgl(const QString &text, int offset, int len) override; + bool lineContinue() override { return true; } private: QChar m_trailer; }; class KateHlCStringChar : public KateHlItem { public: KateHlCStringChar(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; }; class KateHlCChar : public KateHlItem { public: KateHlCChar(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; }; class KateHlAnyChar : public KateHlItem { public: KateHlAnyChar(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2, const QString &charList); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; private: const QString _charList; }; class KateHlRegExpr : public KateHlItem { public: KateHlRegExpr(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2, const QString &expr, bool insensitive, bool minimal); - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE; + int checkHgl(const QString &text, int offset, int len) override; - void capturedTexts(QStringList &) Q_DECL_OVERRIDE; + void capturedTexts(QStringList &) override; - KateHlItem *clone(const QStringList *args) Q_DECL_OVERRIDE; + KateHlItem *clone(const QStringList *args) override; private: /** * regular expression to match */ const QRegularExpression m_regularExpression; /** * does the regular expression start with ^? * allows to skip for any offset > 0 */ const bool m_handlesLineStart; /** * last match, if any */ QRegularExpressionMatch m_lastMatch; }; class KateHlDetectSpaces : public KateHlItem { public: KateHlDetectSpaces(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2) : KateHlItem(attribute, context, regionId, regionId2) {} - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE + int checkHgl(const QString &text, int offset, int len) override { int len2 = offset + len; while ((offset < len2) && text[offset].isSpace()) { offset++; } return offset; } }; class KateHlDetectIdentifier : public KateHlItem { public: KateHlDetectIdentifier(int attribute, KateHlContextModification context, signed char regionId, signed char regionId2) : KateHlItem(attribute, context, regionId, regionId2) { alwaysStartEnable = false; } - int checkHgl(const QString &text, int offset, int len) Q_DECL_OVERRIDE + int checkHgl(const QString &text, int offset, int len) override { // first char should be a letter or underscore if (text[offset].isLetter() || text[offset] == QLatin1Char('_')) { // memorize length int len2 = offset + len; // one char seen offset++; // now loop for all other thingies while ( (offset < len2) && (text[offset].isLetterOrNumber() || (text[offset] == QLatin1Char('_'))) ) { offset++; } return offset; } return 0; } }; //END #endif diff --git a/src/syntax/katehighlightingcmds.h b/src/syntax/katehighlightingcmds.h index d2380073..811e8eaf 100644 --- a/src/syntax/katehighlightingcmds.h +++ b/src/syntax/katehighlightingcmds.h @@ -1,68 +1,68 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2014 Christoph Rüßler * * 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. * * 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. * * 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. */ #ifndef KATE_HIGHLIGHT_RELOAD_H #define KATE_HIGHLIGHT_RELOAD_H #include namespace KateCommands { class Highlighting : public KTextEditor::Command { Highlighting() : KTextEditor::Command({ QStringLiteral("reload-highlighting"), QStringLiteral("edit-highlighting") }) { } static Highlighting* m_instance; public: - ~Highlighting() Q_DECL_OVERRIDE + ~Highlighting() override { m_instance = nullptr; } static Highlighting *self() { if (m_instance == nullptr) { m_instance = new Highlighting(); } return m_instance; } /** * execute command * @param view view to use for execution * @param cmd cmd string * @param errorMsg error to return if no success * @return success */ bool exec(class KTextEditor::View *view, const QString &cmd, QString &errorMsg, - const KTextEditor::Range &range = KTextEditor::Range::invalid()) Q_DECL_OVERRIDE; + const KTextEditor::Range &range = KTextEditor::Range::invalid()) override; /** This command does not have help. @see KTextEditor::Command::help */ - bool help(class KTextEditor::View *, const QString &, QString &) Q_DECL_OVERRIDE; + bool help(class KTextEditor::View *, const QString &, QString &) override; }; } #endif diff --git a/src/undo/katemodifiedundo.h b/src/undo/katemodifiedundo.h index 270d03ce..24b27d6c 100644 --- a/src/undo/katemodifiedundo.h +++ b/src/undo/katemodifiedundo.h @@ -1,139 +1,139 @@ /* This file is part of the Kate project. * * Copyright (C) 2011 Dominik Haumann * * 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. * * 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. * * 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. */ #ifndef KATE_MODIFIED_UNDO_H #define KATE_MODIFIED_UNDO_H #include "kateundo.h" class KateModifiedInsertText : public KateEditInsertTextUndo { public: KateModifiedInsertText(KTextEditor::DocumentPrivate *document, int line, int col, const QString &text); /** * @copydoc KateUndo::undo() */ - void undo() Q_DECL_OVERRIDE; + void undo() override; /** * @copydoc KateUndo::redo() */ - void redo() Q_DECL_OVERRIDE; + void redo() override; - void updateUndoSavedOnDiskFlag(QBitArray &lines) Q_DECL_OVERRIDE; - void updateRedoSavedOnDiskFlag(QBitArray &lines) Q_DECL_OVERRIDE; + void updateUndoSavedOnDiskFlag(QBitArray &lines) override; + void updateRedoSavedOnDiskFlag(QBitArray &lines) override; }; class KateModifiedRemoveText : public KateEditRemoveTextUndo { public: KateModifiedRemoveText(KTextEditor::DocumentPrivate *document, int line, int col, const QString &text); /** * @copydoc KateUndo::undo() */ - void undo() Q_DECL_OVERRIDE; + void undo() override; /** * @copydoc KateUndo::redo() */ - void redo() Q_DECL_OVERRIDE; + void redo() override; - void updateUndoSavedOnDiskFlag(QBitArray &lines) Q_DECL_OVERRIDE; - void updateRedoSavedOnDiskFlag(QBitArray &lines) Q_DECL_OVERRIDE; + void updateUndoSavedOnDiskFlag(QBitArray &lines) override; + void updateRedoSavedOnDiskFlag(QBitArray &lines) override; }; class KateModifiedWrapLine : public KateEditWrapLineUndo { public: KateModifiedWrapLine(KTextEditor::DocumentPrivate *document, int line, int col, int len, bool newLine); /** * @copydoc KateUndo::undo() */ - void undo() Q_DECL_OVERRIDE; + void undo() override; /** * @copydoc KateUndo::redo() */ - void redo() Q_DECL_OVERRIDE; + void redo() override; - void updateUndoSavedOnDiskFlag(QBitArray &lines) Q_DECL_OVERRIDE; - void updateRedoSavedOnDiskFlag(QBitArray &lines) Q_DECL_OVERRIDE; + void updateUndoSavedOnDiskFlag(QBitArray &lines) override; + void updateRedoSavedOnDiskFlag(QBitArray &lines) override; }; class KateModifiedUnWrapLine : public KateEditUnWrapLineUndo { public: KateModifiedUnWrapLine(KTextEditor::DocumentPrivate *document, int line, int col, int len, bool removeLine); /** * @copydoc KateUndo::undo() */ - void undo() Q_DECL_OVERRIDE; + void undo() override; /** * @copydoc KateUndo::redo() */ - void redo() Q_DECL_OVERRIDE; + void redo() override; - void updateUndoSavedOnDiskFlag(QBitArray &lines) Q_DECL_OVERRIDE; - void updateRedoSavedOnDiskFlag(QBitArray &lines) Q_DECL_OVERRIDE; + void updateUndoSavedOnDiskFlag(QBitArray &lines) override; + void updateRedoSavedOnDiskFlag(QBitArray &lines) override; }; class KateModifiedInsertLine : public KateEditInsertLineUndo { public: KateModifiedInsertLine(KTextEditor::DocumentPrivate *document, int line, const QString &text); /** * @copydoc KateUndo::undo() */ - void undo() Q_DECL_OVERRIDE; + void undo() override; /** * @copydoc KateUndo::redo() */ - void redo() Q_DECL_OVERRIDE; + void redo() override; - void updateRedoSavedOnDiskFlag(QBitArray &lines) Q_DECL_OVERRIDE; + void updateRedoSavedOnDiskFlag(QBitArray &lines) override; }; class KateModifiedRemoveLine : public KateEditRemoveLineUndo { public: KateModifiedRemoveLine(KTextEditor::DocumentPrivate *document, int line, const QString &text); /** * @copydoc KateUndo::undo() */ - void undo() Q_DECL_OVERRIDE; + void undo() override; /** * @copydoc KateUndo::redo() */ - void redo() Q_DECL_OVERRIDE; + void redo() override; - void updateUndoSavedOnDiskFlag(QBitArray &lines) Q_DECL_OVERRIDE; + void updateUndoSavedOnDiskFlag(QBitArray &lines) override; }; #endif // KATE_MODIFIED_UNDO_H diff --git a/src/undo/kateundo.h b/src/undo/kateundo.h index 4d8c356e..6face435 100644 --- a/src/undo/kateundo.h +++ b/src/undo/kateundo.h @@ -1,571 +1,571 @@ /* This file is part of the KDE libraries Copyright (C) 2011 Dominik Haumann Copyright (C) 2009-2010 Bernhard Beschow Copyright (C) 2002 John Firebaugh Copyright (C) 2001 Christoph Cullmann Copyright (C) 2001 Joseph Wenninger 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. 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. 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. */ #ifndef kate_undo_h #define kate_undo_h #include #include #include class KateUndoManager; namespace KTextEditor { class DocumentPrivate; } namespace KTextEditor { class View; } /** * Base class for Kate undo commands. */ class KateUndo { public: /** * Constructor * @param document the document the undo item belongs to */ KateUndo(KTextEditor::DocumentPrivate *document); /** * Destructor */ virtual ~KateUndo(); public: /** * Types for undo items */ enum UndoType { editInsertText, editRemoveText, editWrapLine, editUnWrapLine, editInsertLine, editRemoveLine, editMarkLineAutoWrapped, editInvalid }; public: /** * Check whether the item is empty. * * @return whether the item is empty */ virtual bool isEmpty() const; /** * merge an undo item * Saves a bit of memory and potentially many calls when undo/redoing. * @param undo undo item to merge * @return success */ virtual bool mergeWith(const KateUndo *undo); /** * undo this item */ virtual void undo() = 0; /** * redo this item */ virtual void redo() = 0; /** * type of item * @return type */ virtual KateUndo::UndoType type() const = 0; protected: /** * Return the document the undo item belongs to. * @return the document the undo item belongs to */ inline KTextEditor::DocumentPrivate *document() { return m_document; } private: /** * the document the undo item belongs to */ KTextEditor::DocumentPrivate *m_document; // // Line modification system // public: enum ModificationFlag { UndoLine1Modified = 1, UndoLine2Modified = 2, UndoLine1Saved = 4, UndoLine2Saved = 8, RedoLine1Modified = 16, RedoLine2Modified = 32, RedoLine1Saved = 64, RedoLine2Saved = 128 }; inline void setFlag(ModificationFlag flag) { m_lineModFlags |= flag; } inline void unsetFlag(ModificationFlag flag) { m_lineModFlags &= (~flag); } inline bool isFlagSet(ModificationFlag flag) const { return m_lineModFlags & flag; } virtual void updateUndoSavedOnDiskFlag(QBitArray &lines) { Q_UNUSED(lines) } virtual void updateRedoSavedOnDiskFlag(QBitArray &lines) { Q_UNUSED(lines) } private: uchar m_lineModFlags; }; class KateEditInsertTextUndo : public KateUndo { public: KateEditInsertTextUndo(KTextEditor::DocumentPrivate *document, int line, int col, const QString &text); /** * @copydoc KateUndo::isEmpty() */ - bool isEmpty() const Q_DECL_OVERRIDE; + bool isEmpty() const override; /** * @copydoc KateUndo::undo() */ - void undo() Q_DECL_OVERRIDE; + void undo() override; /** * @copydoc KateUndo::redo() */ - void redo() Q_DECL_OVERRIDE; + void redo() override; /** * @copydoc KateUndo::mergeWith(const KateUndo) */ - bool mergeWith(const KateUndo *undo) Q_DECL_OVERRIDE; + bool mergeWith(const KateUndo *undo) override; /** * @copydoc KateUndo::type() */ - KateUndo::UndoType type() const Q_DECL_OVERRIDE + KateUndo::UndoType type() const override { return KateUndo::editInsertText; } protected: inline int len() const { return m_text.length(); } inline int line() const { return m_line; } private: const int m_line; const int m_col; QString m_text; }; class KateEditRemoveTextUndo : public KateUndo { public: KateEditRemoveTextUndo(KTextEditor::DocumentPrivate *document, int line, int col, const QString &text); /** * @copydoc KateUndo::isEmpty() */ - bool isEmpty() const Q_DECL_OVERRIDE; + bool isEmpty() const override; /** * @copydoc KateUndo::undo() */ - void undo() Q_DECL_OVERRIDE; + void undo() override; /** * @copydoc KateUndo::redo() */ - void redo() Q_DECL_OVERRIDE; + void redo() override; /** * @copydoc KateUndo::mergeWith(const KateUndo) */ - bool mergeWith(const KateUndo *undo) Q_DECL_OVERRIDE; + bool mergeWith(const KateUndo *undo) override; /** * @copydoc KateUndo::type() */ - KateUndo::UndoType type() const Q_DECL_OVERRIDE + KateUndo::UndoType type() const override { return KateUndo::editRemoveText; } protected: inline int len() const { return m_text.length(); } inline int line() const { return m_line; } private: const int m_line; int m_col; QString m_text; }; class KateEditMarkLineAutoWrappedUndo : public KateUndo { public: KateEditMarkLineAutoWrappedUndo(KTextEditor::DocumentPrivate *document, int line, bool autowrapped) : KateUndo(document) , m_line(line) , m_autowrapped(autowrapped) {} /** * @copydoc KateUndo::undo() */ - void undo() Q_DECL_OVERRIDE; + void undo() override; /** * @copydoc KateUndo::redo() */ - void redo() Q_DECL_OVERRIDE; + void redo() override; /** * @copydoc KateUndo::type() */ - KateUndo::UndoType type() const Q_DECL_OVERRIDE + KateUndo::UndoType type() const override { return KateUndo::editMarkLineAutoWrapped; } private: const int m_line; const bool m_autowrapped; }; class KateEditWrapLineUndo : public KateUndo { public: KateEditWrapLineUndo(KTextEditor::DocumentPrivate *document, int line, int col, int len, bool newLine); /** * @copydoc KateUndo::undo() */ - void undo() Q_DECL_OVERRIDE; + void undo() override; /** * @copydoc KateUndo::redo() */ - void redo() Q_DECL_OVERRIDE; + void redo() override; /** * @copydoc KateUndo::type() */ - KateUndo::UndoType type() const Q_DECL_OVERRIDE + KateUndo::UndoType type() const override { return KateUndo::editWrapLine; } protected: inline int line() const { return m_line; } private: const int m_line; const int m_col; const int m_len; const bool m_newLine; }; class KateEditUnWrapLineUndo : public KateUndo { public: KateEditUnWrapLineUndo(KTextEditor::DocumentPrivate *document, int line, int col, int len, bool removeLine); /** * @copydoc KateUndo::undo() */ - void undo() Q_DECL_OVERRIDE; + void undo() override; /** * @copydoc KateUndo::redo() */ - void redo() Q_DECL_OVERRIDE; + void redo() override; /** * @copydoc KateUndo::type() */ - KateUndo::UndoType type() const Q_DECL_OVERRIDE + KateUndo::UndoType type() const override { return KateUndo::editUnWrapLine; } protected: inline int line() const { return m_line; } private: const int m_line; const int m_col; const int m_len; const bool m_removeLine; }; class KateEditInsertLineUndo : public KateUndo { public: KateEditInsertLineUndo(KTextEditor::DocumentPrivate *document, int line, const QString &text); /** * @copydoc KateUndo::undo() */ - void undo() Q_DECL_OVERRIDE; + void undo() override; /** * @copydoc KateUndo::redo() */ - void redo() Q_DECL_OVERRIDE; + void redo() override; /** * @copydoc KateUndo::type() */ - KateUndo::UndoType type() const Q_DECL_OVERRIDE + KateUndo::UndoType type() const override { return KateUndo::editInsertLine; } protected: inline int line() const { return m_line; } private: const int m_line; const QString m_text; }; class KateEditRemoveLineUndo : public KateUndo { public: KateEditRemoveLineUndo(KTextEditor::DocumentPrivate *document, int line, const QString &text); /** * @copydoc KateUndo::undo() */ - void undo() Q_DECL_OVERRIDE; + void undo() override; /** * @copydoc KateUndo::redo() */ - void redo() Q_DECL_OVERRIDE; + void redo() override; /** * @copydoc KateUndo::type() */ - KateUndo::UndoType type() const Q_DECL_OVERRIDE + KateUndo::UndoType type() const override { return KateUndo::editRemoveLine; } protected: inline int line() const { return m_line; } private: const int m_line; const QString m_text; }; /** * Class to manage a group of undo items */ class KateUndoGroup { public: /** * Constructor * @param manager KateUndoManager this undo group will belong to */ explicit KateUndoGroup(KateUndoManager *manager, const KTextEditor::Cursor &cursorPosition, const KTextEditor::Range &selectionRange); /** * Destructor */ ~KateUndoGroup(); public: /** * Undo the contained undo items */ void undo(KTextEditor::View *view); /** * Redo the contained undo items */ void redo(KTextEditor::View *view); void editEnd(const KTextEditor::Cursor &cursorPosition, const KTextEditor::Range &selectionRange); /** * merge this group with an other * @param newGroup group to merge into this one * @param complex set if a complex undo * @return success */ bool merge(KateUndoGroup *newGroup, bool complex); /** * set group as as savepoint. the next group will not merge with this one */ void safePoint(bool safePoint = true); /** * is this undogroup empty? */ bool isEmpty() const { return m_items.isEmpty(); } /** * Change all LineSaved flags to LineModified of the line modification system. */ void flagSavedAsModified(); void markUndoAsSaved(QBitArray &lines); void markRedoAsSaved(QBitArray &lines); /** * Set the undo cursor to @p cursor. */ inline void setUndoCursor(const KTextEditor::Cursor &cursor) { m_undoCursor = cursor; } /** * Set the redo cursor to @p cursor. */ inline void setRedoCursor(const KTextEditor::Cursor &cursor) { m_redoCursor = cursor; } inline const KTextEditor::Cursor &redoCursor() const { return m_redoCursor; } private: KTextEditor::Document *document(); /** * singleType * @return the type if it's only one type, or editInvalid if it contains multiple types. */ KateUndo::UndoType singleType() const; /** * are we only of this type ? * @param type type to query * @return we contain only the given type */ bool isOnlyType(KateUndo::UndoType type) const; public: /** * add an undo item * @param u item to add */ void addItem(KateUndo *u); private: KateUndoManager *const m_manager; /** * list of items contained */ QList m_items; /** * prohibit merging with the next group */ bool m_safePoint; /** * the text selection of the active view before the edit step */ const KTextEditor::Range m_undoSelection; /** * the text selection of the active view after the edit step */ KTextEditor::Range m_redoSelection; /** * the cursor position of the active view before the edit step */ KTextEditor::Cursor m_undoCursor; /** * the cursor position of the active view after the edit step */ KTextEditor::Cursor m_redoCursor; }; #endif diff --git a/src/utils/katecmd.h b/src/utils/katecmd.h index 09c0691b..f51e002d 100644 --- a/src/utils/katecmd.h +++ b/src/utils/katecmd.h @@ -1,109 +1,109 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2001-2010 Christoph Cullmann * * 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. * * 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. * * 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. */ #ifndef _KATE_CMD_H #define _KATE_CMD_H #include #include #include #include #include class KTEXTEDITOR_EXPORT KateCmd { public: KateCmd(); ~KateCmd(); static KateCmd *self(); bool registerCommand(KTextEditor::Command *cmd); bool unregisterCommand(KTextEditor::Command *cmd); KTextEditor::Command *queryCommand(const QString &cmd) const; QList commands() const; QStringList commandList() const; QStringList cmds(); void appendHistory(const QString &cmd); const QString fromHistory(int i) const; uint historyLength() const { return m_history.count(); } KCompletion *commandCompletionObject(); private: QHash m_dict; QStringList m_cmds; QStringList m_history; KCompletion m_cmdCompletion; // shared completion object for all KateCmdLineEdits in each KTE::View }; /** * A KCompletion object that completes last ?unquoted? word in the string * passed. Do not mistake "shell" for anything related to quoting, this * simply mimics shell tab completion by completing the last word in the * provided text. */ class KateCmdShellCompletion : public KCompletion { public: KateCmdShellCompletion(); /** * Finds completions to the given text. * The first match is returned and emitted in the signal match(). * @param text the text to complete * @return the first match, or QString() if not found */ - QString makeCompletion(const QString &text) Q_DECL_OVERRIDE; + QString makeCompletion(const QString &text) override; protected: // Called by KCompletion - void postProcessMatch(QString *match) const Q_DECL_OVERRIDE; - void postProcessMatches(QStringList *matches) const Q_DECL_OVERRIDE; - void postProcessMatches(KCompletionMatches *matches) const Q_DECL_OVERRIDE; + void postProcessMatch(QString *match) const override; + void postProcessMatches(QStringList *matches) const override; + void postProcessMatches(KCompletionMatches *matches) const override; private: /** * Split text at the last unquoted space * * @param text_start will be set to the text at the left, including the space * @param text_compl Will be set to the text at the right. This is the text to complete. */ void splitText(const QString &text, QString &text_start, QString &text_compl) const; QChar m_word_break_char; QChar m_quote_char1; QChar m_quote_char2; QChar m_escape_char; QString m_text_start; QString m_text_compl; }; #endif diff --git a/src/utils/katecmds.h b/src/utils/katecmds.h index a6d1ecf3..27ce31aa 100644 --- a/src/utils/katecmds.h +++ b/src/utils/katecmds.h @@ -1,212 +1,212 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2003-2005 Anders Lund * Copyright (C) 2001-2010 Christoph Cullmann * Copyright (C) 2001 Charles Samuels * * 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. * * 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. * * 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. */ #ifndef __KATE_CMDS_H__ #define __KATE_CMDS_H__ #include #include class KCompletion; /** * The KateCommands namespace collects subclasses of KTextEditor::Command * for specific use in kate. */ namespace KateCommands { /** * This KTextEditor::Command provides access to a lot of the core functionality * of kate part, settings, utilities, navigation etc. * it needs to get a kateview pointer, it will cast the kate::view pointer * hard to kateview */ class CoreCommands : public KTextEditor::Command { CoreCommands() : KTextEditor::Command({ QStringLiteral("indent") , QStringLiteral("unindent") , QStringLiteral("cleanindent") , QStringLiteral("fold") , QStringLiteral("tfold") , QStringLiteral("unfold") , QStringLiteral("comment") , QStringLiteral("uncomment") , QStringLiteral("goto") , QStringLiteral("kill-line") , QStringLiteral("set-tab-width") , QStringLiteral("set-replace-tabs") , QStringLiteral("set-show-tabs") , QStringLiteral("set-indent-width") , QStringLiteral("set-indent-mode") , QStringLiteral("set-auto-indent") , QStringLiteral("set-line-numbers") , QStringLiteral("set-folding-markers") , QStringLiteral("set-icon-border") , QStringLiteral("set-indent-pasted-text") , QStringLiteral("set-word-wrap") , QStringLiteral("set-word-wrap-column") , QStringLiteral("set-replace-tabs-save") , QStringLiteral("set-remove-trailing-spaces") , QStringLiteral("set-highlight") , QStringLiteral("set-mode") , QStringLiteral("set-show-indent") , QStringLiteral("print") }) { } static CoreCommands *m_instance; public: - ~CoreCommands() Q_DECL_OVERRIDE + ~CoreCommands() override { m_instance = nullptr; } /** * execute command * @param view view to use for execution * @param cmd cmd string * @param errorMsg error to return if no success * @return success */ bool exec(class KTextEditor::View *view, const QString &cmd, QString &errorMsg); /** * execute command on given range * @param view view to use for execution * @param cmd cmd string * @param errorMsg error to return if no success * @param range range to execute command on * @return success */ bool exec(class KTextEditor::View *view, const QString &cmd, QString &errorMsg, - const KTextEditor::Range &range = KTextEditor::Range(-1, -0, -1, 0)) Q_DECL_OVERRIDE; + const KTextEditor::Range &range = KTextEditor::Range(-1, -0, -1, 0)) override; - bool supportsRange(const QString &range) Q_DECL_OVERRIDE; + bool supportsRange(const QString &range) override; /** This command does not have help. @see KTextEditor::Command::help */ - bool help(class KTextEditor::View *, const QString &, QString &) Q_DECL_OVERRIDE; + bool help(class KTextEditor::View *, const QString &, QString &) override; /** override from KTextEditor::Command */ - KCompletion *completionObject(KTextEditor::View *, const QString &) Q_DECL_OVERRIDE; + KCompletion *completionObject(KTextEditor::View *, const QString &) override; static CoreCommands *self() { if (m_instance == nullptr) { m_instance = new CoreCommands(); } return m_instance; } }; /** * insert a unicode or ascii character * base 9+1: 1234 * hex: 0x1234 or x1234 * octal: 01231 * * prefixed with "char:" **/ class Character : public KTextEditor::Command { Character() : KTextEditor::Command({ QStringLiteral("char") }) { } static Character *m_instance; public: - ~Character() Q_DECL_OVERRIDE + ~Character() override { m_instance = nullptr; } /** * execute command * @param view view to use for execution * @param cmd cmd string * @param errorMsg error to return if no success * @return success */ bool exec(class KTextEditor::View *view, const QString &cmd, QString &errorMsg, - const KTextEditor::Range &range = KTextEditor::Range(-1, -0, -1, 0)) Q_DECL_OVERRIDE; + const KTextEditor::Range &range = KTextEditor::Range(-1, -0, -1, 0)) override; /** This command does not have help. @see KTextEditor::Command::help */ - bool help(class KTextEditor::View *, const QString &, QString &) Q_DECL_OVERRIDE; + bool help(class KTextEditor::View *, const QString &, QString &) override; static Character *self() { if (m_instance == nullptr) { m_instance = new Character(); } return m_instance; } }; /** * insert the current date/time in the given format */ class Date : public KTextEditor::Command { Date() : KTextEditor::Command({ QStringLiteral("date") }) { } static Date *m_instance; public: - ~Date() Q_DECL_OVERRIDE + ~Date() override { m_instance = nullptr; } /** * execute command * @param view view to use for execution * @param cmd cmd string * @param errorMsg error to return if no success * @return success */ bool exec(class KTextEditor::View *view, const QString &cmd, QString &errorMsg, - const KTextEditor::Range &range = KTextEditor::Range(-1, -0, -1, 0)) Q_DECL_OVERRIDE; + const KTextEditor::Range &range = KTextEditor::Range(-1, -0, -1, 0)) override; /** This command does not have help. @see KTextEditor::Command::help */ - bool help(class KTextEditor::View *, const QString &, QString &) Q_DECL_OVERRIDE; + bool help(class KTextEditor::View *, const QString &, QString &) override; static Date *self() { if (m_instance == nullptr) { m_instance = new Date(); } return m_instance; } }; } // namespace KateCommands #endif diff --git a/src/utils/kateconfig.h b/src/utils/kateconfig.h index 98f39100..1f65cc46 100644 --- a/src/utils/kateconfig.h +++ b/src/utils/kateconfig.h @@ -1,865 +1,865 @@ /* This file is part of the KDE libraries Copyright (C) 2003 Christoph Cullmann 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. 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. 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. */ #ifndef __KATE_CONFIG_H__ #define __KATE_CONFIG_H__ #include #include #include "ktexteditor/view.h" #include #include #include #include #include #include class KConfigGroup; namespace KTextEditor { class ViewPrivate; } namespace KTextEditor { class DocumentPrivate; } class KateRenderer; namespace KTextEditor { class EditorPrivate; } class KConfig; class QTextCodec; /** * Base Class for the Kate Config Classes */ class KateConfig { public: /** * Default Constructor */ KateConfig(); /** * Virtual Destructor */ virtual ~KateConfig(); public: /** * start some config changes * this method is needed to init some kind of transaction * for config changes, update will only be done once, at * configEnd() call */ void configStart(); /** * end a config change transaction, update the concerned * documents/views/renderers */ void configEnd(); protected: /** * do the real update */ virtual void updateConfig() = 0; private: /** * recursion depth */ uint configSessionNumber = 0; /** * is a config session running */ bool configIsRunning = false; }; class KTEXTEDITOR_EXPORT KateGlobalConfig : public KateConfig { private: friend class KTextEditor::EditorPrivate; /** * only used in KTextEditor::EditorPrivate for the static global fallback !!! */ KateGlobalConfig(); /** * Destructor */ - ~KateGlobalConfig() Q_DECL_OVERRIDE; + ~KateGlobalConfig() override; public: static KateGlobalConfig *global() { return s_global; } public: /** * Read config from object */ void readConfig(const KConfigGroup &config); /** * Write config to object */ void writeConfig(KConfigGroup &config); protected: - void updateConfig() Q_DECL_OVERRIDE; + void updateConfig() override; public: KEncodingProber::ProberType proberType() const { return m_proberType; } void setProberType(KEncodingProber::ProberType proberType); QTextCodec *fallbackCodec() const; const QString &fallbackEncoding() const; bool setFallbackEncoding(const QString &encoding); private: KEncodingProber::ProberType m_proberType; QString m_fallbackEncoding; private: static KateGlobalConfig *s_global; }; class KTEXTEDITOR_EXPORT KateDocumentConfig : public KateConfig { private: friend class KTextEditor::EditorPrivate; KateDocumentConfig(); public: KateDocumentConfig(const KConfigGroup &cg); /** * Construct a DocumentConfig */ KateDocumentConfig(KTextEditor::DocumentPrivate *doc); /** * Cu DocumentConfig */ - ~KateDocumentConfig() Q_DECL_OVERRIDE; + ~KateDocumentConfig() override; inline static KateDocumentConfig *global() { return s_global; } inline bool isGlobal() const { return (this == global()); } public: /** * Read config from object */ void readConfig(const KConfigGroup &config); /** * Write config to object */ void writeConfig(KConfigGroup &config); protected: - void updateConfig() Q_DECL_OVERRIDE; + void updateConfig() override; public: int tabWidth() const; void setTabWidth(int tabWidth); int indentationWidth() const; void setIndentationWidth(int indentationWidth); const QString &indentationMode() const; void setIndentationMode(const QString &identationMode); enum TabHandling { tabInsertsTab = 0, tabIndents = 1, tabSmart = 2 //!< indents in leading space, otherwise inserts tab }; uint tabHandling() const; void setTabHandling(uint tabHandling); bool wordWrap() const; void setWordWrap(bool on); int wordWrapAt() const; void setWordWrapAt(int col); bool pageUpDownMovesCursor() const; void setPageUpDownMovesCursor(bool on); void setKeepExtraSpaces(bool on); bool keepExtraSpaces() const; void setIndentPastedText(bool on); bool indentPastedText() const; void setBackspaceIndents(bool on); bool backspaceIndents() const; void setSmartHome(bool on); bool smartHome() const; void setShowTabs(bool on); bool showTabs() const; void setShowSpaces(bool on); bool showSpaces() const; void setMarkerSize(uint markerSize); uint markerSize() const; void setReplaceTabsDyn(bool on); bool replaceTabsDyn() const; /** * Remove trailing spaces on save. * triState = 0: never remove trailing spaces * triState = 1: remove trailing spaces of modified lines (line modification system) * triState = 2: remove trailing spaces in entire document */ void setRemoveSpaces(int triState); int removeSpaces() const; void setNewLineAtEof(bool on); bool newLineAtEof() const; void setOvr(bool on); bool ovr() const; void setTabIndents(bool on); bool tabIndentsEnabled() const; QTextCodec *codec() const; const QString &encoding() const; bool setEncoding(const QString &encoding); bool isSetEncoding() const; enum Eol { eolUnix = 0, eolDos = 1, eolMac = 2 }; int eol() const; QString eolString(); void setEol(int mode); bool bom() const; void setBom(bool bom); bool allowEolDetection() const; void setAllowEolDetection(bool on); enum BackupFlags { LocalFiles = 1, RemoteFiles = 2 }; uint backupFlags() const; void setBackupFlags(uint flags); const QString &backupPrefix() const; void setBackupPrefix(const QString &prefix); const QString &backupSuffix() const; void setBackupSuffix(const QString &suffix); const QString &swapDirectory() const; void setSwapDirectory(const QString &directory); enum SwapFileMode { DisableSwapFile = 0, EnableSwapFile, SwapFilePresetDirectory }; uint swapFileModeRaw() const; SwapFileMode swapFileMode() const; void setSwapFileMode(uint mode); uint swapSyncInterval() const; void setSwapSyncInterval(uint interval); bool onTheFlySpellCheck() const; void setOnTheFlySpellCheck(bool on); int lineLengthLimit() const; void setLineLengthLimit(int limit); private: QString m_indentationMode; int m_indentationWidth = 2; int m_tabWidth = 4; uint m_tabHandling = tabSmart; uint m_configFlags = 0; int m_wordWrapAt = 80; bool m_wordWrap; bool m_pageUpDownMovesCursor; bool m_allowEolDetection; int m_eol; bool m_bom; uint m_backupFlags; QString m_encoding; QString m_backupPrefix; QString m_backupSuffix; uint m_swapFileMode; QString m_swapDirectory; uint m_swapSyncInterval; bool m_onTheFlySpellCheck; int m_lineLengthLimit; bool m_tabWidthSet : 1; bool m_indentationWidthSet : 1; bool m_indentationModeSet : 1; bool m_wordWrapSet : 1; bool m_wordWrapAtSet : 1; bool m_pageUpDownMovesCursorSet : 1; bool m_keepExtraSpacesSet : 1; bool m_keepExtraSpaces : 1; bool m_indentPastedTextSet : 1; bool m_indentPastedText : 1; bool m_backspaceIndentsSet : 1; bool m_backspaceIndents : 1; bool m_smartHomeSet : 1; bool m_smartHome : 1; bool m_showTabsSet : 1; bool m_showTabs : 1; bool m_showSpacesSet : 1; bool m_showSpaces : 1; uint m_markerSize = 1; bool m_replaceTabsDynSet : 1; bool m_replaceTabsDyn : 1; bool m_removeSpacesSet : 1; uint m_removeSpaces : 2; bool m_newLineAtEofSet : 1; bool m_newLineAtEof : 1; bool m_overwiteModeSet : 1; bool m_overwiteMode : 1; bool m_tabIndentsSet : 1; bool m_tabIndents : 1; bool m_encodingSet : 1; bool m_eolSet : 1; bool m_bomSet : 1; bool m_allowEolDetectionSet : 1; bool m_backupFlagsSet : 1; bool m_backupPrefixSet : 1; bool m_backupSuffixSet : 1; bool m_swapFileModeSet : 1; bool m_swapDirectorySet : 1; bool m_swapSyncIntervalSet : 1; bool m_onTheFlySpellCheckSet : 1; bool m_lineLengthLimitSet : 1; private: static KateDocumentConfig *s_global; KTextEditor::DocumentPrivate *m_doc = nullptr; }; class KTEXTEDITOR_EXPORT KateViewConfig : public KateConfig { private: friend class KTextEditor::EditorPrivate; /** * only used in KTextEditor::EditorPrivate for the static global fallback !!! */ KateViewConfig(); public: /** * Construct a DocumentConfig */ explicit KateViewConfig(KTextEditor::ViewPrivate *view); /** * Cu DocumentConfig */ - ~KateViewConfig() Q_DECL_OVERRIDE; + ~KateViewConfig() override; inline static KateViewConfig *global() { return s_global; } inline bool isGlobal() const { return (this == global()); } public: /** * Read config from object */ void readConfig(const KConfigGroup &config); /** * Write config to object */ void writeConfig(KConfigGroup &config); protected: - void updateConfig() Q_DECL_OVERRIDE; + void updateConfig() override; public: bool dynWordWrapSet() const { return m_dynWordWrapSet; } bool dynWordWrap() const; void setDynWordWrap(bool wrap); int dynWordWrapIndicators() const; void setDynWordWrapIndicators(int mode); int dynWordWrapAlignIndent() const; void setDynWordWrapAlignIndent(int indent); bool lineNumbers() const; void setLineNumbers(bool on); bool scrollBarMarks() const; void setScrollBarMarks(bool on); bool scrollBarPreview() const; void setScrollBarPreview(bool on); bool scrollBarMiniMap() const; void setScrollBarMiniMap(bool on); bool scrollBarMiniMapAll() const; void setScrollBarMiniMapAll(bool on); int scrollBarMiniMapWidth() const; void setScrollBarMiniMapWidth(int width); /* Whether to show scrollbars */ enum ScrollbarMode { AlwaysOn = 0, ShowWhenNeeded, AlwaysOff }; int showScrollbars() const; void setShowScrollbars(int mode); bool iconBar() const; void setIconBar(bool on); bool foldingBar() const; void setFoldingBar(bool on); bool foldingPreview() const; void setFoldingPreview(bool on); bool lineModification() const; void setLineModification(bool on); int bookmarkSort() const; void setBookmarkSort(int mode); int autoCenterLines() const; void setAutoCenterLines(int lines); enum SearchFlags { IncMatchCase = 1 << 0, IncHighlightAll = 1 << 1, IncFromCursor = 1 << 2, PowerMatchCase = 1 << 3, PowerHighlightAll = 1 << 4, PowerFromCursor = 1 << 5, // PowerSelectionOnly = 1 << 6, Better not save to file // Sebastian PowerModePlainText = 1 << 7, PowerModeWholeWords = 1 << 8, PowerModeEscapeSequences = 1 << 9, PowerModeRegularExpression = 1 << 10, PowerUsePlaceholders = 1 << 11 }; long searchFlags() const; void setSearchFlags(long flags); int maxHistorySize() const; uint defaultMarkType() const; void setDefaultMarkType(uint type); bool allowMarkMenu() const; void setAllowMarkMenu(bool allow); bool persistentSelection() const; void setPersistentSelection(bool on); KTextEditor::View::InputMode inputMode() const; void setInputMode(KTextEditor::View::InputMode mode); void setInputModeRaw(int rawmode); bool viInputModeStealKeys() const; void setViInputModeStealKeys(bool on); bool viRelativeLineNumbers() const; void setViRelativeLineNumbers(bool on); // Do we still need the enum and related functions below? enum TextToSearch { Nowhere = 0, SelectionOnly = 1, SelectionWord = 2, WordOnly = 3, WordSelection = 4 }; bool automaticCompletionInvocation() const; void setAutomaticCompletionInvocation(bool on); bool wordCompletion() const; void setWordCompletion(bool on); bool keywordCompletion () const; void setKeywordCompletion (bool on); int wordCompletionMinimalWordLength() const; void setWordCompletionMinimalWordLength(int length); bool wordCompletionRemoveTail() const; void setWordCompletionRemoveTail(bool on); bool smartCopyCut() const; void setSmartCopyCut(bool on); bool scrollPastEnd() const; void setScrollPastEnd(bool on); bool foldFirstLine() const; void setFoldFirstLine(bool on); bool showWordCount(); void setShowWordCount(bool on); bool autoBrackets() const; void setAutoBrackets(bool on); bool backspaceRemoveComposed() const; void setBackspaceRemoveComposed(bool on); private: bool m_dynWordWrap; int m_dynWordWrapIndicators; int m_dynWordWrapAlignIndent; bool m_lineNumbers; bool m_scrollBarMarks; bool m_scrollBarPreview; bool m_scrollBarMiniMap; bool m_scrollBarMiniMapAll; int m_scrollBarMiniMapWidth; int m_showScrollbars; bool m_iconBar; bool m_foldingBar; bool m_foldingPreview; bool m_lineModification; int m_bookmarkSort; int m_autoCenterLines; long m_searchFlags; int m_maxHistorySize; uint m_defaultMarkType; bool m_persistentSelection; KTextEditor::View::InputMode m_inputMode; bool m_viInputModeStealKeys; bool m_viRelativeLineNumbers; bool m_automaticCompletionInvocation; bool m_wordCompletion; bool m_keywordCompletion; int m_wordCompletionMinimalWordLength; bool m_wordCompletionRemoveTail; bool m_smartCopyCut; bool m_scrollPastEnd; bool m_foldFirstLine; bool m_showWordCount = false; bool m_autoBrackets; bool m_backspaceRemoveComposed; bool m_dynWordWrapSet : 1; bool m_dynWordWrapIndicatorsSet : 1; bool m_dynWordWrapAlignIndentSet : 1; bool m_lineNumbersSet : 1; bool m_scrollBarMarksSet : 1; bool m_scrollBarPreviewSet : 1; bool m_scrollBarMiniMapSet : 1; bool m_scrollBarMiniMapAllSet : 1; bool m_scrollBarMiniMapWidthSet : 1; bool m_showScrollbarsSet : 1; bool m_iconBarSet : 1; bool m_foldingBarSet : 1; bool m_foldingPreviewSet : 1; bool m_lineModificationSet : 1; bool m_bookmarkSortSet : 1; bool m_autoCenterLinesSet : 1; bool m_searchFlagsSet : 1; bool m_defaultMarkTypeSet : 1; bool m_persistentSelectionSet : 1; bool m_inputModeSet : 1; bool m_viInputModeStealKeysSet : 1; bool m_viRelativeLineNumbersSet : 1; bool m_automaticCompletionInvocationSet : 1; bool m_wordCompletionSet : 1; bool m_keywordCompletionSet : 1; bool m_wordCompletionMinimalWordLengthSet : 1; bool m_smartCopyCutSet : 1; bool m_scrollPastEndSet : 1; bool m_allowMarkMenu : 1; bool m_wordCompletionRemoveTailSet : 1; bool m_foldFirstLineSet : 1; bool m_showWordCountSet : 1; bool m_autoBracketsSet : 1; bool m_backspaceRemoveComposedSet : 1; private: static KateViewConfig *s_global; KTextEditor::ViewPrivate *m_view = nullptr; }; class KTEXTEDITOR_EXPORT KateRendererConfig : public KateConfig { private: friend class KTextEditor::EditorPrivate; /** * only used in KTextEditor::EditorPrivate for the static global fallback !!! */ KateRendererConfig(); public: /** * Construct a DocumentConfig */ KateRendererConfig(KateRenderer *renderer); /** * Cu DocumentConfig */ - ~KateRendererConfig() Q_DECL_OVERRIDE; + ~KateRendererConfig() override; inline static KateRendererConfig *global() { return s_global; } inline bool isGlobal() const { return (this == global()); } public: /** * Read config from object */ void readConfig(const KConfigGroup &config); /** * Write config to object */ void writeConfig(KConfigGroup &config); protected: - void updateConfig() Q_DECL_OVERRIDE; + void updateConfig() override; public: const QString &schema() const; void setSchema(const QString &schema); /** * Reload the schema from the schema manager. * For the global instance, have all other instances reload. * Used by the schema config page to apply changes. */ void reloadSchema(); const QFont &font() const; const QFontMetricsF &fontMetrics() const; void setFont(const QFont &font); bool wordWrapMarker() const; void setWordWrapMarker(bool on); const QColor &backgroundColor() const; void setBackgroundColor(const QColor &col); const QColor &selectionColor() const; void setSelectionColor(const QColor &col); const QColor &highlightedLineColor() const; void setHighlightedLineColor(const QColor &col); const QColor &lineMarkerColor(KTextEditor::MarkInterface::MarkTypes type = KTextEditor::MarkInterface::markType01) const; // markType01 == Bookmark void setLineMarkerColor(const QColor &col, KTextEditor::MarkInterface::MarkTypes type = KTextEditor::MarkInterface::markType01); const QColor &highlightedBracketColor() const; void setHighlightedBracketColor(const QColor &col); const QColor &wordWrapMarkerColor() const; void setWordWrapMarkerColor(const QColor &col); const QColor &tabMarkerColor() const; void setTabMarkerColor(const QColor &col); const QColor &indentationLineColor() const; void setIndentationLineColor(const QColor &col); const QColor &iconBarColor() const; void setIconBarColor(const QColor &col); const QColor &foldingColor() const; void setFoldingColor(const QColor &col); // the line number color is used for the line numbers on the left bar const QColor &lineNumberColor() const; void setLineNumberColor(const QColor &col); const QColor ¤tLineNumberColor() const; void setCurrentLineNumberColor(const QColor &col); // the color of the separator between line numbers and icon bar const QColor &separatorColor() const; void setSeparatorColor(const QColor &col); const QColor &spellingMistakeLineColor() const; void setSpellingMistakeLineColor(const QColor &col); bool showIndentationLines() const; void setShowIndentationLines(bool on); bool showWholeBracketExpression() const; void setShowWholeBracketExpression(bool on); bool animateBracketMatching() const; void setAnimateBracketMatching(bool on); const QColor &templateBackgroundColor() const; const QColor &templateEditablePlaceholderColor() const; const QColor &templateFocusedEditablePlaceholderColor() const; const QColor &templateNotEditablePlaceholderColor() const; const QColor &modifiedLineColor() const; void setModifiedLineColor(const QColor &col); const QColor &savedLineColor() const; void setSavedLineColor(const QColor &col); const QColor &searchHighlightColor() const; void setSearchHighlightColor(const QColor &col); const QColor &replaceHighlightColor() const; void setReplaceHighlightColor(const QColor &col); private: /** * Read the schema properties from the config file. */ void setSchemaInternal(const QString &schema); /** * Set the font but drop style name before that. * Otherwise e.g. styles like bold/italic/... will not work */ void setFontWithDroppedStyleName(const QFont &font); QString m_schema; QFont m_font; QFontMetricsF m_fontMetrics; QColor m_backgroundColor; QColor m_selectionColor; QColor m_highlightedLineColor; QColor m_highlightedBracketColor; QColor m_wordWrapMarkerColor; QColor m_tabMarkerColor; QColor m_indentationLineColor; QColor m_iconBarColor; QColor m_foldingColor; QColor m_lineNumberColor; QColor m_currentLineNumberColor; QColor m_separatorColor; QColor m_spellingMistakeLineColor; QVector m_lineMarkerColor; QColor m_templateBackgroundColor; QColor m_templateEditablePlaceholderColor; QColor m_templateFocusedEditablePlaceholderColor; QColor m_templateNotEditablePlaceholderColor; QColor m_modifiedLineColor; QColor m_savedLineColor; QColor m_searchHighlightColor; QColor m_replaceHighlightColor; bool m_wordWrapMarker = false; bool m_showIndentationLines = false; bool m_showWholeBracketExpression = false; bool m_animateBracketMatching = false; bool m_schemaSet : 1; bool m_fontSet : 1; bool m_wordWrapMarkerSet : 1; bool m_showIndentationLinesSet : 1; bool m_showWholeBracketExpressionSet : 1; bool m_backgroundColorSet : 1; bool m_selectionColorSet : 1; bool m_highlightedLineColorSet : 1; bool m_highlightedBracketColorSet : 1; bool m_wordWrapMarkerColorSet : 1; bool m_tabMarkerColorSet : 1; bool m_indentationLineColorSet : 1; bool m_iconBarColorSet : 1; bool m_foldingColorSet : 1; bool m_lineNumberColorSet : 1; bool m_currentLineNumberColorSet : 1; bool m_separatorColorSet : 1; bool m_spellingMistakeLineColorSet : 1; bool m_templateColorsSet : 1; bool m_modifiedLineColorSet : 1; bool m_savedLineColorSet : 1; bool m_searchHighlightColorSet : 1; bool m_replaceHighlightColorSet : 1; QBitArray m_lineMarkerColorSet; private: static KateRendererConfig *s_global; KateRenderer *m_renderer = nullptr; }; #endif diff --git a/src/utils/kateglobal.h b/src/utils/kateglobal.h index 89b4d182..416773ff 100644 --- a/src/utils/kateglobal.h +++ b/src/utils/kateglobal.h @@ -1,568 +1,568 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2001-2010 Christoph Cullmann * Copyright (C) 2009 Erlend Hamberg * * 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. * * 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. * * 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. */ #ifndef __KATE_GLOBAL_H__ #define __KATE_GLOBAL_H__ #include #include "katescript.h" #include #include "ktexteditor/view.h" #include #include #include #include #include #include #include #include #include class QStringListModel; class KateCmd; class KateModeManager; class KateSchemaManager; class KateGlobalConfig; class KateDocumentConfig; class KateViewConfig; class KateRendererConfig; namespace KTextEditor { class DocumentPrivate; } namespace KTextEditor { class ViewPrivate; } class KateScriptManager; class KDirWatch; class KateHlManager; class KateSpellCheckManager; class KateWordCompletionModel; class KateAbstractInputModeFactory; class KateKeywordCompletionModel; class KateDefaultColors; namespace KTextEditor { /** * KTextEditor::EditorPrivate * One instance of this class is hold alive during * a kate part session, as long as any factory, document * or view stay around, here is the place to put things * which are needed and shared by all this objects ;) */ class KTEXTEDITOR_EXPORT EditorPrivate : public KTextEditor::Editor { Q_OBJECT friend class KTextEditor::Editor; // unit testing support public: /** * Calling this function internally sets a flag such that unitTestMode() * returns \p true. */ static void enableUnitTestMode(); /** * Returns \p true, if the unit test mode was enabled through a call of * enableUnitTestMode(), otherwise \p false. */ static bool unitTestMode(); // for setDefaultEncoding friend class KateDocumentConfig; private: /** * Default constructor, private, as singleton * @param staticInstance pointer to fill with content of this */ EditorPrivate(QPointer &staticInstance); public: /** * Destructor */ ~EditorPrivate(); /** * Create a new document object * @param parent parent object * @return created KTextEditor::Document */ - KTextEditor::Document *createDocument(QObject *parent) Q_DECL_OVERRIDE; + KTextEditor::Document *createDocument(QObject *parent) override; /** * Returns a list of all documents of this editor. * @return list of all existing documents */ - QList documents() Q_DECL_OVERRIDE + QList documents() override { return m_documents.keys(); } /** * Set the global application object. * This will allow the editor component to access * the hosting application. * @param application application object */ - void setApplication(KTextEditor::Application *application) Q_DECL_OVERRIDE + void setApplication(KTextEditor::Application *application) override { // switch back to dummy application? m_application = application ? application : &m_dummyApplication; } /** * Current hosting application, if any set. * @return current application object or nullptr */ - KTextEditor::Application *application() const Q_DECL_OVERRIDE + KTextEditor::Application *application() const override { return m_application; } /** * General Information about this editor */ public: /** * return the about data * @return about data of this editor part */ - const KAboutData &aboutData() const Q_DECL_OVERRIDE + const KAboutData &aboutData() const override { return m_aboutData; } /** * Configuration management */ public: /** * Shows a config dialog for the part, changes will be applied * to the editor, but not saved anywhere automagically, call * writeConfig to save them */ - void configDialog(QWidget *parent) Q_DECL_OVERRIDE; + void configDialog(QWidget *parent) override; /** * Number of available config pages * If the editor returns a number < 1, it doesn't support this * and the embedding app should use the configDialog () instead * @return number of config pages */ - int configPages() const Q_DECL_OVERRIDE; + int configPages() const override; /** * returns config page with the given number, * config pages from 0 to configPages()-1 are available * if configPages() > 0 */ - KTextEditor::ConfigPage *configPage(int number, QWidget *parent) Q_DECL_OVERRIDE; + KTextEditor::ConfigPage *configPage(int number, QWidget *parent) override; /** * Kate Part Internal stuff ;) */ public: /** * singleton accessor * @return instance of the factory */ static KTextEditor::EditorPrivate *self(); /** * register document at the factory * this allows us to loop over all docs for example on config changes * @param doc document to register */ void registerDocument(KTextEditor::DocumentPrivate *doc); /** * unregister document at the factory * @param doc document to register */ void deregisterDocument(KTextEditor::DocumentPrivate *doc); /** * register view at the factory * this allows us to loop over all views for example on config changes * @param view view to register */ void registerView(KTextEditor::ViewPrivate *view); /** * unregister view at the factory * @param view view to unregister */ void deregisterView(KTextEditor::ViewPrivate *view); /** * return a list of all registered views * @return all known views */ QList views() { return m_views.toList(); } /** * global dirwatch * @return dirwatch instance */ KDirWatch *dirWatch() { return m_dirWatch; } /** * The global configuration of katepart, e.g. katepartrc * @return global shared access to katepartrc config */ static KSharedConfigPtr config() { // use dummy config for unit tests! return KTextEditor::EditorPrivate::unitTestMode() ? KSharedConfig::openConfig(QStringLiteral("katepartrc-unittest"), KConfig::SimpleConfig, QStandardPaths::TempLocation) : KSharedConfig::openConfig(QStringLiteral("katepartrc")); } /** * global mode manager * used to manage the modes centrally * @return mode manager */ KateModeManager *modeManager() { return m_modeManager; } /** * manager for the katepart schemas * @return schema manager */ KateSchemaManager *schemaManager() { return m_schemaManager; } /** * fallback document config * @return default config for all documents */ KateDocumentConfig *documentConfig() { return m_documentConfig; } /** * fallback view config * @return default config for all views */ KateViewConfig *viewConfig() { return m_viewConfig; } /** * fallback renderer config * @return default config for all renderers */ KateRendererConfig *rendererConfig() { return m_rendererConfig; } /** * Global script collection */ KateScriptManager *scriptManager() { return m_scriptManager; } /** * hl manager * @return hl manager */ KateHlManager *hlManager() { return m_hlManager; } /** * command manager * @return command manager */ KateCmd *cmdManager() { return m_cmdManager; } /** * spell check manager * @return spell check manager */ KateSpellCheckManager *spellCheckManager() { return m_spellCheckManager; } /** * global instance of the simple word completion mode * @return global instance of the simple word completion mode */ KateWordCompletionModel *wordCompletionModel() { return m_wordCompletionModel; } /** * Global instance of the language-aware keyword completion model * @return global instance of the keyword completion model */ KateKeywordCompletionModel *keywordCompletionModel () { return m_keywordCompletionModel; } /** * query for command * @param cmd name of command to query for * @return found command or 0 */ - KTextEditor::Command *queryCommand(const QString &cmd) const Q_DECL_OVERRIDE; + KTextEditor::Command *queryCommand(const QString &cmd) const override; /** * Get a list of all registered commands. * \return list of all commands */ - QList commands() const Q_DECL_OVERRIDE; + QList commands() const override; /** * Get a list of available commandline strings. * \return commandline strings */ - QStringList commandList() const Q_DECL_OVERRIDE; + QStringList commandList() const override; /** * Copy text to clipboard an remember it in the history * @param text text to copy to clipboard, does nothing if empty! */ void copyToClipboard(const QString &text); /** * Clipboard history, filled with text we ever copied * to clipboard via copyToClipboard. */ const QStringList &clipboardHistory() const { return m_clipboardHistory; } /** * return a list of all registered docs * @return all known documents */ QList kateDocuments() { return m_documents.values(); } /** * Dummy main window to be null safe. * @return dummy main window */ KTextEditor::MainWindow *dummyMainWindow() { return &m_dummyMainWindow; } /** * @return list of available input mode factories */ QList inputModeFactories(); /** * Default colors, once constructed, as expensive * @return default colors */ const KateDefaultColors &defaultColors() const { return *m_defaultColors; } /** * Search pattern history shared among simple/power search instances. */ QStringListModel *searchHistoryModel(); /** * Replace pattern history shared among simple/power search instances. */ QStringListModel *replaceHistoryModel(); /** * Call this function to store the history models to the application config. */ void saveSearchReplaceHistoryModels(); Q_SIGNALS: /** * Emitted if the history of clipboard changes via copyToClipboard */ void clipboardHistoryChanged(); protected: - bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE; + bool eventFilter(QObject *, QEvent *) override; private Q_SLOTS: void updateColorPalette(); private: /** * about data (authors and more) */ KAboutData m_aboutData; /** * registered docs, map from general to specialized pointer */ QHash m_documents; /** * registered views */ QSet m_views; /** * global dirwatch object */ KDirWatch *m_dirWatch; /** * mode manager */ KateModeManager *m_modeManager; /** * schema manager */ KateSchemaManager *m_schemaManager; /** * global config */ KateGlobalConfig *m_globalConfig; /** * fallback document config */ KateDocumentConfig *m_documentConfig; /** * fallback view config */ KateViewConfig *m_viewConfig; /** * fallback renderer config */ KateRendererConfig *m_rendererConfig; /** * internal commands */ QList m_cmds; /** * script manager */ KateScriptManager *m_scriptManager; /** * hl manager */ KateHlManager *m_hlManager; /** * command manager */ KateCmd *m_cmdManager; /** * spell check manager */ KateSpellCheckManager *m_spellCheckManager; /** * global instance of the simple word completion mode */ KateWordCompletionModel *m_wordCompletionModel; /** * global instance of the language-specific keyword completion model */ KateKeywordCompletionModel *m_keywordCompletionModel; /** * clipboard history */ QStringList m_clipboardHistory; /** * Dummy application object to be null safe */ KTextEditor::Application m_dummyApplication; /** * access to application */ QPointer m_application; /** * Dummy main window to be null safe */ KTextEditor::MainWindow m_dummyMainWindow; /** * input modes map */ QMap m_inputModeFactories; /** * default colors */ QScopedPointer m_defaultColors; /** * Shared history models for search & replace. */ QStringListModel *m_searchHistoryModel; QStringListModel *m_replaceHistoryModel; }; } #endif diff --git a/src/utils/katesedcmd.h b/src/utils/katesedcmd.h index 2dc9e5a8..647ba0d1 100644 --- a/src/utils/katesedcmd.h +++ b/src/utils/katesedcmd.h @@ -1,145 +1,145 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2003-2005 Anders Lund * Copyright (C) 2001-2010 Christoph Cullmann * Copyright (C) 2001 Charles Samuels * * 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. * * 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. * * 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. */ #ifndef __KATE_SED_CMD_H__ #define __KATE_SED_CMD_H__ #include #include "kateregexpsearch.h" #include #include namespace KTextEditor { class DocumentPrivate; class ViewPrivate; } /** * The KateCommands namespace collects subclasses of KTextEditor::Command * for specific use in kate. */ namespace KateCommands { /** * Support vim/sed style search and replace * @author Charles Samuels **/ class SedReplace : public KTextEditor::Command { static SedReplace *m_instance; protected: SedReplace() : KTextEditor::Command({ QStringLiteral("s"), QStringLiteral("%s"), QStringLiteral("$s") }) { } public: - ~SedReplace() Q_DECL_OVERRIDE + ~SedReplace() override { m_instance = nullptr; } /** * Execute command. Valid command strings are: * - s/search/replace/ find @c search, replace it with @c replace * on this line * - \%s/search/replace/ do the same to the whole file * - s/search/replace/i do the search and replace case insensitively * - $s/search/replace/ do the search are replacement to the * selection only * * @note $s/// is currently unsupported * @param view view to use for execution * @param cmd cmd string * @param errorMsg error to return if no success * @return success */ bool exec(class KTextEditor::View *view, const QString &cmd, QString &errorMsg, - const KTextEditor::Range &r) Q_DECL_OVERRIDE; + const KTextEditor::Range &r) override; - bool supportsRange(const QString &) Q_DECL_OVERRIDE + bool supportsRange(const QString &) override { return true; } /** This command does not have help. @see KTextEditor::Command::help */ - bool help(class KTextEditor::View *, const QString &, QString &) Q_DECL_OVERRIDE + bool help(class KTextEditor::View *, const QString &, QString &) override { return false; } static SedReplace *self() { if (m_instance == nullptr) { m_instance = new SedReplace(); } return m_instance; } /** * Parses @c sedReplaceString to see if it is a valid sed replace expression (e.g. "s/find/replace/gi"). * If it is, returns true and sets @c delimiter to the delimiter used in the expression; * @c destFindBeginPos and @c destFindEndPos to the positions in * @c sedReplaceString of the * begin and end of the "find" term; and @c destReplaceBeginPos and @c destReplaceEndPos to the begin * and end positions of the "replace" term. */ static bool parse(const QString &sedReplaceString, QString &destDelim, int &destFindBeginPos, int &destFindEndPos, int &destReplaceBeginPos, int &destReplaceEndPos); class InteractiveSedReplacer { public: InteractiveSedReplacer(KTextEditor::DocumentPrivate *doc, const QString &findPattern, const QString &replacePattern, bool caseSensitive, bool onlyOnePerLine, int startLine, int endLine); /** * Will return invalid Range if there are no further matches. */ KTextEditor::Range currentMatch(); void skipCurrentMatch(); void replaceCurrentMatch(); void replaceAllRemaining(); QString currentMatchReplacementConfirmationMessage(); QString finalStatusReportMessage(); private: const QString m_findPattern; const QString m_replacePattern; bool m_onlyOnePerLine; int m_endLine; KTextEditor::DocumentPrivate *m_doc; KateRegExpSearch m_regExpSearch; int m_numReplacementsDone; int m_numLinesTouched; int m_lastChangedLineNum; KTextEditor::Cursor m_currentSearchPos; const QVector fullCurrentMatch(); QString replacementTextForCurrentMatch(); }; protected: virtual bool interactiveSedReplace(KTextEditor::ViewPrivate *kateView, QSharedPointer interactiveSedReplace); }; } // namespace KateCommands #endif diff --git a/src/utils/katetemplatehandler.h b/src/utils/katetemplatehandler.h index 474fb4dd..a4a6e821 100644 --- a/src/utils/katetemplatehandler.h +++ b/src/utils/katetemplatehandler.h @@ -1,252 +1,252 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2004,2010 Joseph Wenninger * Copyright (C) 2009 Milian Wolff * Copyright (C) 2014 Sven Brauch * * 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. * * 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. * * 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. */ #ifndef _KATE_TEMPLATE_HANDLER_H_ #define _KATE_TEMPLATE_HANDLER_H_ #include #include #include #include #include #include class KateUndoManager; namespace KTextEditor { class DocumentPrivate; class ViewPrivate; class MovingCursor; class MovingRange; } /** * \brief Inserts a template and offers advanced snippet features, like navigation and mirroring. * * For each template inserted a new KateTemplateHandler will be created. * * The handler has the following features: * * \li It inserts the template string into the document at the requested position. * \li When the template contains at least one variable, the cursor will be placed * at the start of the first variable and its range gets selected. * \li When more than one variable exists,TAB and SHIFT TAB can be used to navigate * to the next/previous variable. * \li When a variable occurs more than once in the template, edits to any of the * occurrences will be mirroed to the other ones. * \li When ESC is pressed, the template handler closes. * \li When ALT + RETURN is pressed and a \c ${cursor} variable * exists in the template,the cursor will be placed there. Else the cursor will * be placed at the end of the template. * * \author Milian Wolff */ class KateTemplateHandler: public QObject { Q_OBJECT public: /** * Setup the template handler, insert the template string. * * NOTE: The handler deletes itself when required, you do not need to * keep track of it. */ KateTemplateHandler(KTextEditor::ViewPrivate *view, KTextEditor::Cursor position, const QString &templateString, const QString& script, KateUndoManager *undoManager); - ~KateTemplateHandler() Q_DECL_OVERRIDE; + ~KateTemplateHandler() override; protected: /** * \brief Provide keyboard interaction for the template handler. * * The event filter handles the following shortcuts: * * TAB: jump to next editable (i.e. not mirrored) range. * NOTE: this prevents indenting via TAB. * SHIFT + TAB: jump to previous editable (i.e. not mirrored) range. * NOTE: this prevents un-indenting via SHIFT + TAB. * ESC: terminate template handler (only when no completion is active). * ALT + RETURN: accept template and jump to the end-cursor. * if %{cursor} was given in the template, that will be the * end-cursor. * else just jump to the end of the inserted text. */ - bool eventFilter(QObject *object, QEvent *event) Q_DECL_OVERRIDE; + bool eventFilter(QObject *object, QEvent *event) override; private: /** * Inserts the @p text template at @p position and performs * all necessary initializations, such as populating default values * and placing the cursor. */ void initializeTemplate(); /** * Parse @p templateText and populate m_fields. */ void parseFields(const QString& templateText); /** * Set necessary attributes (esp. background colour) on all moving * ranges for the fields in m_fields. */ void setupFieldRanges(); /** * Evaluate default values for all fields in m_fields and * store them in the fields. This updates the @property defaultValue property * of the TemplateField instances in m_fields from the raw, user-entered * default value to its evaluated equivalent (e.g. "func()" -> result of function call) * * @sa TemplateField */ void setupDefaultValues(); /** * Install an event filter on the filter proxy of \p view for * navigation between the ranges and terminating the KateTemplateHandler. * * \see eventFilter() */ void setupEventHandler(KTextEditor::View *view); /** * Jumps to the previous editable range. If there is none, wrap and jump to the first range. * * \see jumpToNextRange() */ void jumpToPreviousRange(); /** * Jumps to the next editable range. If there is none, wrap and jump to the last range. * * \see jumpToPreviousRange() */ void jumpToNextRange(); /** * Helper function for jumpTo{Next,Previous} * if initial is set to true, assumes the cursor is before the snippet * and selects the first field */ void jump(int by, bool initial = false); /** * Jumps to the final cursor position. This is either \p m_finalCursorPosition, or * if that is not set, the end of \p m_templateRange. */ void jumpToFinalCursorPosition(); /** * Go through all template fields and decide if their moving ranges expand * when edited at the corners. Expansion is turned off if two fields are * directly adjacent to avoid overlaps when characters are inserted between * them. */ void updateRangeBehaviours(); /** * Sort all template fields in m_fields by tab order, which means, * by range; except for ${cursor} which is always sorted last. */ void sortFields(); private Q_SLOTS: /** * Saves the range of the inserted template. This is required since * tabs could get expanded on insert. While we are at it, we can * use it to auto-indent the code after insert. */ void slotTemplateInserted(KTextEditor::Document *document, const KTextEditor::Range &range); /** * Install event filter on new views. */ void slotViewCreated(KTextEditor::Document *document, KTextEditor::View *view); /** * Update content of all dependent fields, i.e. mirror or script fields. */ void updateDependentFields(KTextEditor::Document *document, const KTextEditor::Range &oldRange); public: KTextEditor::ViewPrivate* view() const; KTextEditor::DocumentPrivate* doc() const; private: /// The view we operate on KTextEditor::ViewPrivate* m_view; /// The undo manager associated with our document KateUndoManager* const m_undoManager; // Describes a single template field, e.g. ${foo}. struct TemplateField { // up-to-date range for the field QSharedPointer range; // contents of the field, i.e. identifier or function to call QString identifier; // default value, if applicable; else empty QString defaultValue; enum Kind { Invalid, // not an actual field Editable, // normal, user-editable field (green by default) [non-dependent field] Mirror, // field mirroring contents of another field [dependent field] FunctionCall, // field containing the up-to-date result of a function call [dependent field] FinalCursorPosition // field marking the final cursor position }; Kind kind = Invalid; // true if this field was edited by the user before bool touched = false; bool operator==(const TemplateField& other) { return range == other.range; } }; // List of all template fields in the inserted snippet. @see sortFields() QVector m_fields; // Get the template field which contains @p range. const TemplateField fieldForRange(const KTextEditor::Range& range) const; /// Construct a map of master fields and their current value, for use in scripts. KateScript::FieldMap fieldMap() const; /// A range that occupies the whole range of the inserted template. /// When the an edit happens outside it, the template handler gets closed. QSharedPointer m_wholeTemplateRange; /// Set to true when currently updating dependent fields, to prevent recursion. bool m_internalEdit; /// template script (i.e. javascript stuff), which can be used by the current template KateScript m_templateScript; }; #endif diff --git a/src/variableeditor/variableeditor.h b/src/variableeditor/variableeditor.h index 14f5e93d..3a5a15b8 100644 --- a/src/variableeditor/variableeditor.h +++ b/src/variableeditor/variableeditor.h @@ -1,187 +1,187 @@ /* This file is part of the KDE project Copyright (C) 2011 Dominik Haumann 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. 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. 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. */ #ifndef VARIABLE_EDITOR_H #define VARIABLE_EDITOR_H #include class KateHelpButton; class VariableBoolItem; class VariableColorItem; class VariableFontItem; class VariableItem; class VariableStringListItem; class VariableIntItem; class VariableStringItem; class VariableSpellCheckItem; class VariableRemoveSpacesItem; class KColorCombo; class QFontComboBox; class QCheckBox; class QComboBox; class QLabel; class QLineEdit; class QSpinBox; namespace Sonnet { class DictionaryComboBox; } class VariableEditor : public QWidget { Q_OBJECT public: VariableEditor(VariableItem *item, QWidget *parent = nullptr); - ~VariableEditor() Q_DECL_OVERRIDE; + ~VariableEditor() override; VariableItem *item() const; Q_SIGNALS: void valueChanged(); protected Q_SLOTS: void itemEnabled(bool enabled); void activateItem(); protected: - void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; - void enterEvent(QEvent *event) Q_DECL_OVERRIDE; - void leaveEvent(QEvent *event) Q_DECL_OVERRIDE; + void paintEvent(QPaintEvent *event) override; + void enterEvent(QEvent *event) override; + void leaveEvent(QEvent *event) override; private: VariableItem *m_item; QCheckBox *m_checkBox; QLabel *m_variable; QLabel *m_helpText; KateHelpButton *m_btnHelp; }; class VariableIntEditor : public VariableEditor { Q_OBJECT public: VariableIntEditor(VariableIntItem *item, QWidget *parent); protected Q_SLOTS: void setItemValue(int newValue); private: QSpinBox *m_spinBox; }; class VariableBoolEditor : public VariableEditor { Q_OBJECT public: VariableBoolEditor(VariableBoolItem *item, QWidget *parent); protected Q_SLOTS: void setItemValue(int enabled); private: QComboBox *m_comboBox; }; class VariableStringListEditor : public VariableEditor { Q_OBJECT public: VariableStringListEditor(VariableStringListItem *item, QWidget *parent); protected Q_SLOTS: void setItemValue(const QString &newValue); private: QComboBox *m_comboBox; }; class VariableColorEditor : public VariableEditor { Q_OBJECT public: VariableColorEditor(VariableColorItem *item, QWidget *parent); protected Q_SLOTS: void setItemValue(const QColor &newValue); private: KColorCombo *m_comboBox; }; class VariableFontEditor : public VariableEditor { Q_OBJECT public: VariableFontEditor(VariableFontItem *item, QWidget *parent); protected Q_SLOTS: void setItemValue(const QFont &newValue); private: QFontComboBox *m_comboBox; }; class VariableStringEditor : public VariableEditor { Q_OBJECT public: VariableStringEditor(VariableStringItem *item, QWidget *parent); protected Q_SLOTS: void setItemValue(const QString &newValue); private: QLineEdit *m_lineEdit; }; class VariableSpellCheckEditor : public VariableEditor { Q_OBJECT public: VariableSpellCheckEditor(VariableSpellCheckItem *item, QWidget *parent); protected Q_SLOTS: void setItemValue(const QString &newValue); private: Sonnet::DictionaryComboBox *m_dictionaryCombo; }; class VariableRemoveSpacesEditor : public VariableEditor { Q_OBJECT public: VariableRemoveSpacesEditor(VariableRemoveSpacesItem *item, QWidget *parent); protected Q_SLOTS: void setItemValue(int enabled); private: QComboBox *m_comboBox; }; #endif diff --git a/src/variableeditor/variableitem.h b/src/variableeditor/variableitem.h index 4771ac7e..efbc7c5d 100644 --- a/src/variableeditor/variableitem.h +++ b/src/variableeditor/variableitem.h @@ -1,228 +1,228 @@ /* This file is part of the KDE project Copyright (C) 2011 Dominik Haumann 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. 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. 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. */ #ifndef VARIABLE_ITEM_H #define VARIABLE_ITEM_H #include #include #include #include class VariableEditor; //BEGIN class VariableItem class VariableItem { public: VariableItem(const QString &variable); virtual ~VariableItem(); QString variable() const; QString helpText() const; void setHelpText(const QString &text); bool isActive() const; void setActive(bool active); virtual void setValueByString(const QString &value) = 0; virtual QString valueAsString() const = 0; virtual VariableEditor *createEditor(QWidget *parent) = 0; private: // not implemented: copy constructor and operator= VariableItem(const VariableItem ©); VariableItem &operator=(const VariableItem &other); QString m_variable; QString m_helpText; bool m_active; }; //END class VariableItem // // DERIVE A CLASS FOR EACH TYPE // //BEGIN class VariableIntItem class VariableIntItem : public VariableItem { public: VariableIntItem(const QString &variable, int value); int value() const; void setValue(int newValue); void setRange(int minValue, int maxValue); int minValue() const; int maxValue() const; public: - void setValueByString(const QString &value) Q_DECL_OVERRIDE; - QString valueAsString() const Q_DECL_OVERRIDE; - VariableEditor *createEditor(QWidget *parent) Q_DECL_OVERRIDE; + void setValueByString(const QString &value) override; + QString valueAsString() const override; + VariableEditor *createEditor(QWidget *parent) override; private: int m_value; int m_minValue; int m_maxValue; }; //END class VariableIntItem //BEGIN class VariableStringListItem class VariableStringListItem : public VariableItem { public: VariableStringListItem(const QString &variable, const QStringList &slist, const QString &value); QStringList stringList() const; QString value() const; void setValue(const QString &newValue); public: - void setValueByString(const QString &value) Q_DECL_OVERRIDE; - QString valueAsString() const Q_DECL_OVERRIDE; - VariableEditor *createEditor(QWidget *parent) Q_DECL_OVERRIDE; + void setValueByString(const QString &value) override; + QString valueAsString() const override; + VariableEditor *createEditor(QWidget *parent) override; private: QStringList m_list; QString m_value; }; //END class VariableStringListItem //BEGIN class VariableBoolItem class VariableBoolItem : public VariableItem { public: VariableBoolItem(const QString &variable, bool value); bool value() const; void setValue(bool enabled); public: - void setValueByString(const QString &value) Q_DECL_OVERRIDE; - QString valueAsString() const Q_DECL_OVERRIDE; - VariableEditor *createEditor(QWidget *parent) Q_DECL_OVERRIDE; + void setValueByString(const QString &value) override; + QString valueAsString() const override; + VariableEditor *createEditor(QWidget *parent) override; private: bool m_value; }; //END class VariableBoolItem //BEGIN class VariableColorItem class VariableColorItem : public VariableItem { public: VariableColorItem(const QString &variable, const QColor &value); QColor value() const; void setValue(const QColor &color); public: - void setValueByString(const QString &value) Q_DECL_OVERRIDE; - QString valueAsString() const Q_DECL_OVERRIDE; - VariableEditor *createEditor(QWidget *parent) Q_DECL_OVERRIDE; + void setValueByString(const QString &value) override; + QString valueAsString() const override; + VariableEditor *createEditor(QWidget *parent) override; private: QColor m_value; }; //END class VariableColorItem //BEGIN class VariableFontItem class VariableFontItem : public VariableItem { public: VariableFontItem(const QString &variable, const QFont &value); QFont value() const; void setValue(const QFont &value); public: - void setValueByString(const QString &value) Q_DECL_OVERRIDE; - QString valueAsString() const Q_DECL_OVERRIDE; - VariableEditor *createEditor(QWidget *parent) Q_DECL_OVERRIDE; + void setValueByString(const QString &value) override; + QString valueAsString() const override; + VariableEditor *createEditor(QWidget *parent) override; private: QFont m_value; }; //END class VariableFontItem //BEGIN class VariableStringItem class VariableStringItem : public VariableItem { public: VariableStringItem(const QString &variable, const QString &value); QString value() const; void setValue(const QString &value); public: - void setValueByString(const QString &value) Q_DECL_OVERRIDE; // Same as setValue() in this case, implemented for uniformity - QString valueAsString() const Q_DECL_OVERRIDE; // Same as value() in this case, implemented for uniformity - VariableEditor *createEditor(QWidget *parent) Q_DECL_OVERRIDE; + void setValueByString(const QString &value) override; // Same as setValue() in this case, implemented for uniformity + QString valueAsString() const override; // Same as value() in this case, implemented for uniformity + VariableEditor *createEditor(QWidget *parent) override; private: QString m_value; }; //END class VariableStringItem //BEGIN class VariableSpellCheckItem class VariableSpellCheckItem : public VariableItem { public: VariableSpellCheckItem(const QString &variable, const QString &value); QString value() const; void setValue(const QString &value); public: - void setValueByString(const QString &value) Q_DECL_OVERRIDE; // Same as setValue() in this case, implemented for uniformity - QString valueAsString() const Q_DECL_OVERRIDE; // Same as value() in this case, implemented for uniformity - VariableEditor *createEditor(QWidget *parent) Q_DECL_OVERRIDE; + void setValueByString(const QString &value) override; // Same as setValue() in this case, implemented for uniformity + QString valueAsString() const override; // Same as value() in this case, implemented for uniformity + VariableEditor *createEditor(QWidget *parent) override; private: QString m_value; }; //END class VariableSpellCheckItem //BEGIN class VariableRemoveSpacesItem class VariableRemoveSpacesItem : public VariableItem { public: VariableRemoveSpacesItem(const QString &variable, int value); int value() const; void setValue(int value); public: - void setValueByString(const QString &value) Q_DECL_OVERRIDE; // Same as setValue() in this case, implemented for uniformity - QString valueAsString() const Q_DECL_OVERRIDE; // Same as value() in this case, implemented for uniformity - VariableEditor *createEditor(QWidget *parent) Q_DECL_OVERRIDE; + void setValueByString(const QString &value) override; // Same as setValue() in this case, implemented for uniformity + QString valueAsString() const override; // Same as value() in this case, implemented for uniformity + VariableEditor *createEditor(QWidget *parent) override; private: int m_value; }; //END class VariableRemoveSpacesItem #endif diff --git a/src/variableeditor/variablelistview.h b/src/variableeditor/variablelistview.h index 70d408bf..f30f9a00 100644 --- a/src/variableeditor/variablelistview.h +++ b/src/variableeditor/variablelistview.h @@ -1,60 +1,60 @@ /* This file is part of the KDE project Copyright (C) 2011 Dominik Haumann 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. 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. 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. */ #ifndef VARIABLE_LIST_VIEW_H #define VARIABLE_LIST_VIEW_H #include #include class VariableItem; class VariableEditor; class VariableListView : public QScrollArea { Q_OBJECT public: VariableListView(const QString &variableLine, QWidget *parent = nullptr); - ~VariableListView() Q_DECL_OVERRIDE; + ~VariableListView() override; void addItem(VariableItem *item); /// always returns the up-to-date variables line QString variableLine(); Q_SIGNALS: void aboutToHide(); void changed(); // unused right now protected: - void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE; - void hideEvent(QHideEvent *event) Q_DECL_OVERRIDE; + void resizeEvent(QResizeEvent *event) override; + void hideEvent(QHideEvent *event) override; void parseVariables(const QString &line); QVector m_items; QVector m_editors; QMap m_variables; }; #endif diff --git a/src/view/katestatusbar.h b/src/view/katestatusbar.h index 486e1c1e..a9e39fb8 100644 --- a/src/view/katestatusbar.h +++ b/src/view/katestatusbar.h @@ -1,109 +1,109 @@ /* This file is part of the KDE and the Kate project * * Copyright (C) 2013 Dominik Haumann * * 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. * * 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. * * 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. */ #ifndef KATE_STATUS_BAR_H #define KATE_STATUS_BAR_H #include "kateview.h" #include "kateviewhelpers.h" #include #include #include #include #include class WordCounter; class KateStatusBarOpenUpMenu: public QMenu { Q_OBJECT public: KateStatusBarOpenUpMenu(QWidget *parent); - ~KateStatusBarOpenUpMenu() Q_DECL_OVERRIDE; - void setVisible(bool) Q_DECL_OVERRIDE; + ~KateStatusBarOpenUpMenu() override; + void setVisible(bool) override; }; class KateStatusBar : public KateViewBarWidget { Q_OBJECT public: explicit KateStatusBar(KTextEditor::ViewPrivate *view); public Q_SLOTS: void updateStatus (); void viewModeChanged (); void cursorPositionChanged (); void selectionChanged (); void modifiedChanged(); void documentConfigChanged (); void modeChanged (); void wordCountChanged(int, int, int, int); void toggleWordCount(bool on); void configChanged(); protected: - bool eventFilter(QObject *obj, QEvent *event) Q_DECL_OVERRIDE; + bool eventFilter(QObject *obj, QEvent *event) override; private: KTextEditor::ViewPrivate *const m_view; QLabel* m_lineColLabel; QLabel* m_wordCountLabel; QToolButton* m_modifiedLabel; QLabel* m_insertModeLabel; QPushButton* m_mode; QPushButton* m_encoding; QPushButton* m_tabsIndent; KLocalizedString m_spacesOnly; KLocalizedString m_tabsOnly; KLocalizedString m_tabSpacesMixed; KLocalizedString m_spacesOnlyShowTabs; QMenu *m_indentSettingsMenu; unsigned int m_modifiedStatus; unsigned int m_selectionMode; QActionGroup *m_tabGroup; QActionGroup *m_indentGroup; QAction *m_mixedAction; QAction *m_hardAction; QAction *m_softAction; WordCounter *m_wordCounter; private: void addNumberAction(QActionGroup *group, QMenu *menu, int data); void updateGroup(QActionGroup *group, int w); public Q_SLOTS: void slotTabGroup(QAction*); void slotIndentGroup(QAction*); void slotIndentTabMode(QAction*); }; #endif diff --git a/src/view/katetextpreview.h b/src/view/katetextpreview.h index 00568240..8e6b2f3e 100644 --- a/src/view/katetextpreview.h +++ b/src/view/katetextpreview.h @@ -1,106 +1,106 @@ /* This file is part of the KDE libraries Copyright (C) 2016 Dominik Haumann This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 6 of version 3 of the license. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see . */ #ifndef KATE_TEXT_PREVIEW_H #define KATE_TEXT_PREVIEW_H #include //namespace KTextEditor { class DocumentPrivate; } namespace KTextEditor { class ViewPrivate; } /** * TODO */ class KateTextPreview : public QFrame { Q_OBJECT Q_PROPERTY(qreal line READ line WRITE setLine) Q_PROPERTY(bool showFoldedLines READ showFoldedLines WRITE setShowFoldedLines) Q_PROPERTY(bool centerView READ centerView WRITE setCenterView) Q_PROPERTY(qreal scaleFactor READ scaleFactor WRITE setScaleFactor) public: KateTextPreview(KTextEditor::ViewPrivate *view); - ~KateTextPreview() Q_DECL_OVERRIDE; + ~KateTextPreview() override; KTextEditor::ViewPrivate *view() const; /** * Sets @p line as preview line. */ void setLine(qreal line); /** * Returns the line set with setLine(). */ qreal line() const; /** * Enabled/disable centering the view on the line set with setLine(). * If @p center is false, the first visible line is the once specified in * setLine(). If @p center is true, the specified line is vertically * centered. By default, centering the preview is set to true. */ void setCenterView(bool center); /** * Returns whether view centering is enabled. */ bool centerView() const; /** * Sets the scale factor. * The default scale factor is 1.0. For text previews, you may want a scale * factor of e.g. 0.8 or 0.9. Negative scale factors are not allowed. */ void setScaleFactor(qreal factor); /** * Returns the scale factor set with setScale(). * The default value is 1.0. */ qreal scaleFactor() const; /** * Sets whether folded lines are hidden or not. * By default, folded liens are not visible. */ void setShowFoldedLines(bool on); /** * Returns whether folded lines are hidden. */ bool showFoldedLines() const; protected: - void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; + void paintEvent(QPaintEvent *event) override; private: KTextEditor::ViewPrivate *m_view; qreal m_line; bool m_showFoldedLines; bool m_center; qreal m_scale; }; #endif diff --git a/src/view/kateview.h b/src/view/kateview.h index 078b5fa1..359be8ac 100644 --- a/src/view/kateview.h +++ b/src/view/kateview.h @@ -1,997 +1,997 @@ /* This file is part of the KDE libraries Copyright (C) 2002 John Firebaugh Copyright (C) 2001 Christoph Cullmann Copyright (C) 2001-2010 Joseph Wenninger Copyright (C) 1999 Jochen Wilhelmy This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. 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. 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. */ #ifndef kate_view_h #define kate_view_h #include #include #include #include #include #include #include #include #include #include #include #include #include #include "katetextrange.h" #include "katetextfolding.h" #include "katerenderer.h" namespace KTextEditor { class AnnotationModel; class Message; } namespace KTextEditor { class DocumentPrivate; } class KateBookmarks; class KateViewConfig; class KateRenderer; class KateSpellCheckDialog; class KateCompletionWidget; class KateViewInternal; class KateViewBar; class KateTextPreview; class KateGotoBar; class KateDictionaryBar; class KateSpellingMenu; class KateMessageWidget; class KateIconBorder; class KateStatusBar; class KateViewEncodingAction; class KateModeMenu; class KateAbstractInputMode; class KateScriptActionMenu; class KateMessageLayout; class KToggleAction; class KSelectAction; class QAction; namespace KTextEditor { // // Kate KTextEditor::View class ;) // class KTEXTEDITOR_EXPORT ViewPrivate : public KTextEditor::View, public KTextEditor::TextHintInterface, public KTextEditor::CodeCompletionInterface, public KTextEditor::ConfigInterface, public KTextEditor::AnnotationViewInterface { Q_OBJECT Q_INTERFACES(KTextEditor::TextHintInterface) Q_INTERFACES(KTextEditor::ConfigInterface) Q_INTERFACES(KTextEditor::CodeCompletionInterface) Q_INTERFACES(KTextEditor::AnnotationViewInterface) friend class KTextEditor::View; friend class ::KateViewInternal; friend class ::KateIconBorder; friend class ::KateTextPreview; public: ViewPrivate (KTextEditor::DocumentPrivate *doc, QWidget *parent, KTextEditor::MainWindow *mainWindow = nullptr); - ~ViewPrivate() Q_DECL_OVERRIDE; + ~ViewPrivate() override; /** * Get the view's main window, if any * \return the view's main window */ - KTextEditor::MainWindow *mainWindow() const Q_DECL_OVERRIDE + KTextEditor::MainWindow *mainWindow() const override { return m_mainWindow; } - KTextEditor::Document *document() const Q_DECL_OVERRIDE; + KTextEditor::Document *document() const override; - ViewMode viewMode() const Q_DECL_OVERRIDE; - QString viewModeHuman() const Q_DECL_OVERRIDE; - InputMode viewInputMode() const Q_DECL_OVERRIDE; - QString viewInputModeHuman() const Q_DECL_OVERRIDE; + ViewMode viewMode() const override; + QString viewModeHuman() const override; + InputMode viewInputMode() const override; + QString viewInputModeHuman() const override; void setInputMode(InputMode mode); // // KTextEditor::ClipboardInterface // public Q_SLOTS: void paste(const QString *textToPaste = nullptr); void cut(); void copy() const; private Q_SLOTS: /** * internal use, apply word wrap */ void applyWordWrap(); // // KTextEditor::PopupMenuInterface // public: - void setContextMenu(QMenu *menu) Q_DECL_OVERRIDE; - QMenu *contextMenu() const Q_DECL_OVERRIDE; - QMenu *defaultContextMenu(QMenu *menu = nullptr) const Q_DECL_OVERRIDE; + void setContextMenu(QMenu *menu) override; + QMenu *contextMenu() const override; + QMenu *defaultContextMenu(QMenu *menu = nullptr) const override; private Q_SLOTS: void aboutToShowContextMenu(); void aboutToHideContextMenu(); private: QPointer m_contextMenu; // // KTextEditor::ViewCursorInterface // public: - bool setCursorPosition(KTextEditor::Cursor position) Q_DECL_OVERRIDE; + bool setCursorPosition(KTextEditor::Cursor position) override; - KTextEditor::Cursor cursorPosition() const Q_DECL_OVERRIDE; + KTextEditor::Cursor cursorPosition() const override; - KTextEditor::Cursor cursorPositionVirtual() const Q_DECL_OVERRIDE; + KTextEditor::Cursor cursorPositionVirtual() const override; - QPoint cursorToCoordinate(const KTextEditor::Cursor &cursor) const Q_DECL_OVERRIDE; + QPoint cursorToCoordinate(const KTextEditor::Cursor &cursor) const override; - KTextEditor::Cursor coordinatesToCursor(const QPoint &coord) const Q_DECL_OVERRIDE; + KTextEditor::Cursor coordinatesToCursor(const QPoint &coord) const override; - QPoint cursorPositionCoordinates() const Q_DECL_OVERRIDE; + QPoint cursorPositionCoordinates() const override; bool setCursorPositionVisual(const KTextEditor::Cursor &position); /** * Return the virtual cursor column, each tab is expanded into the * document's tabWidth characters. If word wrap is off, the cursor may be * behind the line's length. */ int virtualCursorColumn() const; - bool mouseTrackingEnabled() const Q_DECL_OVERRIDE; - bool setMouseTrackingEnabled(bool enable) Q_DECL_OVERRIDE; + bool mouseTrackingEnabled() const override; + bool setMouseTrackingEnabled(bool enable) override; private: void notifyMousePositionChanged(const KTextEditor::Cursor &newPosition); // Internal public: bool setCursorPositionInternal(const KTextEditor::Cursor &position, uint tabwidth = 1, bool calledExternally = false); // // KTextEditor::ConfigInterface // public: - QStringList configKeys() const Q_DECL_OVERRIDE; - QVariant configValue(const QString &key) Q_DECL_OVERRIDE; - void setConfigValue(const QString &key, const QVariant &value) Q_DECL_OVERRIDE; + QStringList configKeys() const override; + QVariant configValue(const QString &key) override; + void setConfigValue(const QString &key, const QVariant &value) override; Q_SIGNALS: void configChanged(); public: /** * Try to fold starting at the given line. * This will both try to fold existing folding ranges of this line and to query the highlighting what to fold. * @param startLine start line to fold at */ void foldLine(int startLine); /** * Try to unfold all foldings starting at the given line. * @param startLine start line to unfold at */ void unfoldLine(int startLine); // // KTextEditor::CodeCompletionInterface2 // public: - bool isCompletionActive() const Q_DECL_OVERRIDE; - void startCompletion(const KTextEditor::Range &word, KTextEditor::CodeCompletionModel *model) Q_DECL_OVERRIDE; - void abortCompletion() Q_DECL_OVERRIDE; - void forceCompletion() Q_DECL_OVERRIDE; - void registerCompletionModel(KTextEditor::CodeCompletionModel *model) Q_DECL_OVERRIDE; - void unregisterCompletionModel(KTextEditor::CodeCompletionModel *model) Q_DECL_OVERRIDE; + bool isCompletionActive() const override; + void startCompletion(const KTextEditor::Range &word, KTextEditor::CodeCompletionModel *model) override; + void abortCompletion() override; + void forceCompletion() override; + void registerCompletionModel(KTextEditor::CodeCompletionModel *model) override; + void unregisterCompletionModel(KTextEditor::CodeCompletionModel *model) override; bool isCompletionModelRegistered(KTextEditor::CodeCompletionModel *model) const; - bool isAutomaticInvocationEnabled() const Q_DECL_OVERRIDE; - void setAutomaticInvocationEnabled(bool enabled = true) Q_DECL_OVERRIDE; + bool isAutomaticInvocationEnabled() const override; + void setAutomaticInvocationEnabled(bool enabled = true) override; Q_SIGNALS: void completionExecuted(KTextEditor::View *view, const KTextEditor::Cursor &position, KTextEditor::CodeCompletionModel *model, const QModelIndex &); void completionAborted(KTextEditor::View *view); public Q_SLOTS: void userInvokedCompletion(); public: KateCompletionWidget *completionWidget() const; mutable KateCompletionWidget *m_completionWidget; void sendCompletionExecuted(const KTextEditor::Cursor &position, KTextEditor::CodeCompletionModel *model, const QModelIndex &index); void sendCompletionAborted(); // // KTextEditor::TextHintInterface // public: - void registerTextHintProvider(KTextEditor::TextHintProvider *provider) Q_DECL_OVERRIDE; - void unregisterTextHintProvider(KTextEditor::TextHintProvider *provider) Q_DECL_OVERRIDE; - void setTextHintDelay(int delay) Q_DECL_OVERRIDE; - int textHintDelay() const Q_DECL_OVERRIDE; + void registerTextHintProvider(KTextEditor::TextHintProvider *provider) override; + void unregisterTextHintProvider(KTextEditor::TextHintProvider *provider) override; + void setTextHintDelay(int delay) override; + int textHintDelay() const override; public: bool dynWordWrap() const { return m_hasWrap; } // // KTextEditor::SelectionInterface stuff // public Q_SLOTS: - bool setSelection(const KTextEditor::Range &selection) Q_DECL_OVERRIDE; + bool setSelection(const KTextEditor::Range &selection) override; - bool removeSelection() Q_DECL_OVERRIDE + bool removeSelection() override { return clearSelection(); } - bool removeSelectionText() Q_DECL_OVERRIDE + bool removeSelectionText() override { return removeSelectedText(); } - bool setBlockSelection(bool on) Q_DECL_OVERRIDE; + bool setBlockSelection(bool on) override; bool toggleBlockSelection(); bool clearSelection(); bool clearSelection(bool redraw, bool finishedChangingSelection = true); bool removeSelectedText(); bool selectAll(); public: - bool selection() const Q_DECL_OVERRIDE; - QString selectionText() const Q_DECL_OVERRIDE; - bool blockSelection() const Q_DECL_OVERRIDE; - KTextEditor::Range selectionRange() const Q_DECL_OVERRIDE; + bool selection() const override; + QString selectionText() const override; + bool blockSelection() const override; + KTextEditor::Range selectionRange() const override; static void blockFix(KTextEditor::Range &range); // // Arbitrary Syntax HL + Action extensions // public: // Action association extension void deactivateEditActions(); void activateEditActions(); // // internal helper stuff, for katerenderer and so on // public: // should cursor be wrapped ? take config + blockselection state in account bool wrapCursor() const; // some internal functions to get selection state of a line/col bool cursorSelected(const KTextEditor::Cursor &cursor); bool lineSelected(int line); bool lineEndSelected(const KTextEditor::Cursor &lineEndPos); bool lineHasSelected(int line); bool lineIsSelection(int line); void ensureCursorColumnValid(); void tagSelection(const KTextEditor::Range &oldSelection); void selectWord(const KTextEditor::Cursor &cursor); void selectLine(const KTextEditor::Cursor &cursor); //BEGIN EDIT STUFF public: void editStart(); void editEnd(int editTagLineStart, int editTagLineEnd, bool tagFrom); void editSetCursor(const KTextEditor::Cursor &cursor); //END //BEGIN TAG & CLEAR public: bool tagLine(const KTextEditor::Cursor &virtualCursor); bool tagRange(const KTextEditor::Range &range, bool realLines = false); bool tagLines(int start, int end, bool realLines = false); bool tagLines(KTextEditor::Cursor start, KTextEditor::Cursor end, bool realCursors = false); bool tagLines(KTextEditor::Range range, bool realRange = false); void tagAll(); void clear(); void repaintText(bool paintOnlyDirty = false); void updateView(bool changed = false); //END // // KTextEditor::AnnotationView // public: - void setAnnotationModel(KTextEditor::AnnotationModel *model) Q_DECL_OVERRIDE; - KTextEditor::AnnotationModel *annotationModel() const Q_DECL_OVERRIDE; - void setAnnotationBorderVisible(bool visible) Q_DECL_OVERRIDE; - bool isAnnotationBorderVisible() const Q_DECL_OVERRIDE; + void setAnnotationModel(KTextEditor::AnnotationModel *model) override; + KTextEditor::AnnotationModel *annotationModel() const override; + void setAnnotationBorderVisible(bool visible) override; + bool isAnnotationBorderVisible() const override; Q_SIGNALS: - void annotationContextMenuAboutToShow(KTextEditor::View *view, QMenu *menu, int line) Q_DECL_OVERRIDE; - void annotationActivated(KTextEditor::View *view, int line) Q_DECL_OVERRIDE; + void annotationContextMenuAboutToShow(KTextEditor::View *view, QMenu *menu, int line) override; + void annotationActivated(KTextEditor::View *view, int line) override; // KF6: fix View -> KTextEditor::View - void annotationBorderVisibilityChanged(View *view, bool visible) Q_DECL_OVERRIDE; + void annotationBorderVisibilityChanged(View *view, bool visible) override; void navigateLeft(); void navigateRight(); void navigateUp(); void navigateDown(); void navigateAccept(); void navigateBack(); private: KTextEditor::AnnotationModel *m_annotationModel; // // KTextEditor::View // public: void emitNavigateLeft() { emit navigateLeft(); } void emitNavigateRight() { emit navigateRight(); } void emitNavigateUp() { emit navigateUp(); } void emitNavigateDown() { emit navigateDown(); } void emitNavigateAccept() { emit navigateAccept(); } void emitNavigateBack() { emit navigateBack(); } /** Return values for "save" related commands. */ bool isOverwriteMode() const; QString currentTextLine(); QTextLayout * textLayout(int line) const; QTextLayout * textLayout(const KTextEditor::Cursor &pos) const; public Q_SLOTS: void indent(); void unIndent(); void cleanIndent(); void align(); void comment(); void uncomment(); void toggleComment(); void killLine(); /** * Sets the cursor to the previous editing position in this document */ void goToPreviousEditingPosition(); /** * Sets the cursor to the next editing position in this document */ void goToNextEditingPosition(); /** Uppercases selected text, or an alphabetic character next to the cursor. */ void uppercase(); /** Lowercases selected text, or an alphabetic character next to the cursor. */ void lowercase(); /** Capitalizes the selection (makes each word start with an uppercase) or the word under the cursor. */ void capitalize(); /** Joins lines touched by the selection */ void joinLines(); // Note - the following functions simply forward to KateViewInternal void keyReturn(); void smartNewline(); void backspace(); void deleteWordLeft(); void keyDelete(); void deleteWordRight(); void transpose(); void cursorLeft(); void shiftCursorLeft(); void cursorRight(); void shiftCursorRight(); void wordLeft(); void shiftWordLeft(); void wordRight(); void shiftWordRight(); void home(); void shiftHome(); void end(); void shiftEnd(); void up(); void shiftUp(); void down(); void shiftDown(); void scrollUp(); void scrollDown(); void topOfView(); void shiftTopOfView(); void bottomOfView(); void shiftBottomOfView(); void pageUp(); void shiftPageUp(); void pageDown(); void shiftPageDown(); void top(); void shiftTop(); void bottom(); void shiftBottom(); void toMatchingBracket(); void shiftToMatchingBracket(); void toPrevModifiedLine(); void toNextModifiedLine(); void insertTab(); void gotoLine(); // config file / session management functions public: /** * Read session settings from the given \p config. * * Known flags: * "SkipUrl" => don't save/restore the file * "SkipMode" => don't save/restore the mode * "SkipHighlighting" => don't save/restore the highlighting * "SkipEncoding" => don't save/restore the encoding * * \param config read the session settings from this KConfigGroup * \param flags additional flags * \see writeSessionConfig() */ - void readSessionConfig(const KConfigGroup &config, const QSet &flags = QSet()) Q_DECL_OVERRIDE; + void readSessionConfig(const KConfigGroup &config, const QSet &flags = QSet()) override; /** * Write session settings to the \p config. * See readSessionConfig() for more details. * * \param config write the session settings to this KConfigGroup * \param flags additional flags * \see readSessionConfig() */ - void writeSessionConfig(KConfigGroup &config, const QSet &flags = QSet()) Q_DECL_OVERRIDE; + void writeSessionConfig(KConfigGroup &config, const QSet &flags = QSet()) override; public Q_SLOTS: void setEol(int eol); void setAddBom(bool enabled); void find(); void findSelectedForwards(); void findSelectedBackwards(); void replace(); void findNext(); void findPrevious(); void setFoldingMarkersOn(bool enable); // Not in KTextEditor::View, but should be void setIconBorder(bool enable); void setLineNumbersOn(bool enable); void setScrollBarMarks(bool enable); void setScrollBarMiniMap(bool enable); void setScrollBarMiniMapAll(bool enable); void setScrollBarMiniMapWidth(int width); void toggleFoldingMarkers(); void toggleIconBorder(); void toggleLineNumbersOn(); void toggleScrollBarMarks(); void toggleScrollBarMiniMap(); void toggleScrollBarMiniMapAll(); void toggleDynWordWrap(); void setDynWrapIndicators(int mode); public: int getEol() const; public: KateRenderer *renderer(); bool iconBorder(); bool lineNumbersOn(); bool scrollBarMarks(); bool scrollBarMiniMap(); bool scrollBarMiniMapAll(); int dynWrapIndicators(); bool foldingMarkersOn(); private Q_SLOTS: /** * used to update actions after selection changed */ void slotSelectionChanged(); void toggleInputMode(); void cycleInputMode(); public: /** * accessor to katedocument pointer * @return pointer to document */ KTextEditor::DocumentPrivate *doc() { return m_doc; } const KTextEditor::DocumentPrivate *doc() const { return m_doc; } public Q_SLOTS: void slotUpdateUndo(); void toggleInsert(); void reloadFile(); void toggleWWMarker(); void toggleNPSpaces(); void toggleWordCount(bool on); void toggleWriteLock(); void switchToCmdLine(); void slotReadWriteChanged(); void slotClipboardHistoryChanged(); Q_SIGNALS: void dropEventPass(QDropEvent *); public: /** * Folding handler for this view. * @return folding handler */ Kate::TextFolding &textFolding() { return m_textFolding; } public: void slotTextInserted(KTextEditor::View *view, const KTextEditor::Cursor &position, const QString &text); void exportHtmlToFile(const QString &file); private Q_SLOTS: void slotGotFocus(); void slotLostFocus(); void slotSaveCanceled(const QString &error); void slotConfigDialog(); void exportHtmlToClipboard (); void exportHtmlToFile (); public Q_SLOTS: void slotFoldToplevelNodes(); void slotExpandToplevelNodes(); void slotCollapseLocal(); void slotExpandLocal(); private: void setupLayout(); void setupConnections(); void setupActions(); void setupEditActions(); void setupCodeFolding(); QList m_editActions; QAction *m_editUndo; QAction *m_editRedo; QAction *m_pasteMenu; KToggleAction *m_toggleFoldingMarkers; KToggleAction *m_toggleIconBar; KToggleAction *m_toggleLineNumbers; KToggleAction *m_toggleScrollBarMarks; KToggleAction *m_toggleScrollBarMiniMap; KToggleAction *m_toggleScrollBarMiniMapAll; KToggleAction *m_toggleDynWrap; KSelectAction *m_setDynWrapIndicators; KToggleAction *m_toggleWWMarker; KToggleAction *m_toggleNPSpaces; KToggleAction *m_toggleWordCount; QAction *m_switchCmdLine; KToggleAction *m_viInputModeAction; KSelectAction *m_setEndOfLine; KToggleAction *m_addBom; QAction *m_cut; QAction *m_copy; QAction *m_copyHtmlAction; QAction *m_paste; QAction *m_selectAll; QAction *m_deSelect; QActionGroup *m_inputModeActions; KToggleAction *m_toggleBlockSelection; KToggleAction *m_toggleInsert; KToggleAction *m_toggleWriteLock; bool m_hasWrap; KTextEditor::DocumentPrivate *const m_doc; Kate::TextFolding m_textFolding; KateViewConfig *const m_config; KateRenderer *const m_renderer; KateViewInternal *const m_viewInternal; KateSpellCheckDialog *m_spell; KateBookmarks *const m_bookmarks; //* margins QSpacerItem *m_topSpacer; QSpacerItem *m_leftSpacer; QSpacerItem *m_rightSpacer; QSpacerItem *m_bottomSpacer; private Q_SLOTS: void slotHlChanged(); /** * Configuration */ public: inline KateViewConfig *config() { return m_config; } void updateConfig(); void updateDocumentConfig(); void updateRendererConfig(); private Q_SLOTS: void updateFoldingConfig(); private: bool m_startingUp; bool m_updatingDocumentConfig; // stores the current selection Kate::TextRange m_selection; // do we select normal or blockwise ? bool blockSelect; // templates public: bool insertTemplateInternal(const KTextEditor::Cursor& insertPosition, const QString& templateString, const QString& script = QString()); /** * Accessors to the bars... */ public: KateViewBar *bottomViewBar() const; KateDictionaryBar *dictionaryBar(); private: KateGotoBar *gotoBar(); /** * viewbar + its widgets * they are created on demand... */ private: // created in constructor of the view KateViewBar *m_bottomViewBar; // created on demand..., only access them through the above accessors.... KateGotoBar *m_gotoBar; KateDictionaryBar *m_dictionaryBar; // input modes public: KateAbstractInputMode *currentInputMode() const; public: KTextEditor::Range visibleRange(); Q_SIGNALS: void displayRangeChanged(KTextEditor::ViewPrivate *view); protected: - bool event(QEvent *e) Q_DECL_OVERRIDE; - void paintEvent(QPaintEvent *e) Q_DECL_OVERRIDE; + bool event(QEvent *e) override; + void paintEvent(QPaintEvent *e) override; KToggleAction *m_toggleOnTheFlySpellCheck; KateSpellingMenu *m_spellingMenu; protected Q_SLOTS: void toggleOnTheFlySpellCheck(bool b); public Q_SLOTS: void changeDictionary(); void reflectOnTheFlySpellCheckStatus(bool enabled); public: KateSpellingMenu *spellingMenu(); private: bool m_userContextMenuSet; private Q_SLOTS: /** * save folding state before document reload */ void saveFoldingState(); /** * restore folding state after document reload */ void applyFoldingState(); void clearHighlights(); void createHighlights(); private: void selectionChangedForHighlights(); /** * saved folding state */ QJsonDocument m_savedFoldingState; QString m_currentTextForHighlights; QList m_rangesForHighlights; public: /** * Attribute of a range changed or range with attribute changed in given line range. * @param startLine start line of change * @param endLine end line of change * @param rangeWithAttribute attribute changed or is active, this will perhaps lead to repaints */ void notifyAboutRangeChange(int startLine, int endLine, bool rangeWithAttribute); private Q_SLOTS: /** * Delayed update for view after text ranges changed */ void slotDelayedUpdateOfView(); Q_SIGNALS: /** * Delayed update for view after text ranges changed */ void delayedUpdateOfView(); public: /** * set of ranges which had the mouse inside last time, used for rendering * @return set of ranges which had the mouse inside last time checked */ const QSet *rangesMouseIn() const { return &m_rangesMouseIn; } /** * set of ranges which had the caret inside last time, used for rendering * @return set of ranges which had the caret inside last time checked */ const QSet *rangesCaretIn() const { return &m_rangesCaretIn; } /** * check if ranges changed for mouse in and caret in * @param activationType type of activation to check */ void updateRangesIn(KTextEditor::Attribute::ActivationType activationType); // // helpers for delayed view update after ranges changes // private: /** * update already inited? */ bool m_delayedUpdateTriggered; /** * minimal line to update */ int m_lineToUpdateMin; /** * maximal line to update */ int m_lineToUpdateMax; /** * set of ranges which had the mouse inside last time */ QSet m_rangesMouseIn; /** * set of ranges which had the caret inside last time */ QSet m_rangesCaretIn; // // forward impl for KTextEditor::MessageInterface // public: /** * Used by Document::postMessage(). */ void postMessage(KTextEditor::Message *message, QList > actions); private: /** * Message widgets showing KTextEditor::Messages. * The index of the array maps to the enum KTextEditor::Message::MessagePosition. */ std::array m_messageWidgets{{nullptr}}; /** Layout for floating notifications */ KateMessageLayout *m_notificationLayout = nullptr; // for unit test 'tests/messagetest.cpp' public: KateMessageWidget *messageWidget(); private: /** * The main window responsible for this view, if any */ QPointer m_mainWindow; // // KTextEditor::PrintInterface // public Q_SLOTS: - bool print() Q_DECL_OVERRIDE; - void printPreview() Q_DECL_OVERRIDE; + bool print() override; + void printPreview() override; public: /** * Get the view status bar * @return status bar, in enabled */ KateStatusBar *statusBar () const { return m_statusBar; } /** * Toogle status bar, e.g. create or remove it */ void toggleStatusBar (); /** * Get the encoding menu * @return the encoding menu */ KateViewEncodingAction *encodingAction () const { return m_encodingAction; } /** * Get the mode menu * @return the mode menu */ KateModeMenu *modeAction () const { return m_modeAction; } private: /** * the status bar of this view */ KateStatusBar *m_statusBar; /** * the encoding selection menu, used by view + status bar */ KateViewEncodingAction *m_encodingAction; /** * the mode selection menu, used by view + status bar */ KateModeMenu *m_modeAction; /** * is automatic invocation of completion disabled temporarily? */ bool m_temporaryAutomaticInvocationDisabled; public: /** * Returns the attribute for the default style \p defaultStyle. */ - Attribute::Ptr defaultStyleAttribute(DefaultStyle defaultStyle) const Q_DECL_OVERRIDE; + Attribute::Ptr defaultStyleAttribute(DefaultStyle defaultStyle) const override; /** * Get the list of AttributeBlocks for a given \p line in the document. * * \return list of AttributeBlocks for given \p line. */ - QList lineAttributes(int line) Q_DECL_OVERRIDE; + QList lineAttributes(int line) override; private: // remember folding state to prevent refolding the first line if it was manually unfolded, // e.g. when saving a file or changing other config vars bool m_autoFoldedFirstLine; public: void setScrollPositionInternal(KTextEditor::Cursor &cursor); void setHorizontalScrollPositionInternal(int x); KTextEditor::Cursor maxScrollPositionInternal() const; int firstDisplayedLineInternal(LineType lineType) const; int lastDisplayedLineInternal(LineType lineType) const; QRect textAreaRectInternal() const; private: /** * script action menu, stored in scoped pointer to ensure * destruction before other QObject auto-cleanup as it * manage sub objects on its own that have this view as parent */ QScopedPointer m_scriptActionMenu; }; } #endif diff --git a/src/view/kateviewaccessible.h b/src/view/kateviewaccessible.h index ebaecbee..51dfda77 100644 --- a/src/view/kateviewaccessible.h +++ b/src/view/kateviewaccessible.h @@ -1,294 +1,294 @@ /* This file is part of the KDE libraries Copyright (C) 2010 Sebastian Sauer Copyright (C) 2012 Frederik Gladhorn 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. 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. 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. */ #ifndef _KATE_VIEW_ACCESSIBLE_ #define _KATE_VIEW_ACCESSIBLE_ #ifndef QT_NO_ACCESSIBILITY #include "kateviewinternal.h" #include "katedocument.h" #include #include #include /** * This class implements a QAccessible-interface for a KateViewInternal. * * This is the root class for the kateview. The \a KateCursorAccessible class * represents the cursor in the kateview and is a child of this class. */ class KateViewAccessible : public QAccessibleWidget, public QAccessibleTextInterface // FIXME maybe:, public QAccessibleEditableTextInterface { public: explicit KateViewAccessible(KateViewInternal *view) : QAccessibleWidget(view, QAccessible::EditableText) { // to invalidate positionFromCursor cache when the document is changed m_conn = QObject::connect(view->view()->document(), &KTextEditor::Document::textChanged, [this](){ m_lastPosition = -1; }); } - void *interface_cast(QAccessible::InterfaceType t) Q_DECL_OVERRIDE + void *interface_cast(QAccessible::InterfaceType t) override { if (t == QAccessible::TextInterface) return static_cast(this); return nullptr; } - ~KateViewAccessible() Q_DECL_OVERRIDE + ~KateViewAccessible() override { QObject::disconnect(m_conn); } - QAccessibleInterface *childAt(int x, int y) const Q_DECL_OVERRIDE + QAccessibleInterface *childAt(int x, int y) const override { Q_UNUSED(x); Q_UNUSED(y); return nullptr; } - void setText(QAccessible::Text t, const QString &text) Q_DECL_OVERRIDE + void setText(QAccessible::Text t, const QString &text) override { if (t == QAccessible::Value && view()->view()->document()) { view()->view()->document()->setText(text); m_lastPosition = -1; } } - QAccessible::State state() const Q_DECL_OVERRIDE + QAccessible::State state() const override { QAccessible::State s = QAccessibleWidget::state(); s.focusable = view()->focusPolicy() != Qt::NoFocus; s.focused = view()->hasFocus(); s.editable = true; s.multiLine = true; s.selectableText = true; return s; } - QString text(QAccessible::Text t) const Q_DECL_OVERRIDE + QString text(QAccessible::Text t) const override { QString s; if (view()->view()->document()) { if (t == QAccessible::Name) { s = view()->view()->document()->documentName(); } if (t == QAccessible::Value) { s = view()->view()->document()->text(); } } return s; } - int characterCount() const Q_DECL_OVERRIDE + int characterCount() const override { return view()->view()->document()->text().size(); } - void addSelection(int startOffset, int endOffset) Q_DECL_OVERRIDE + void addSelection(int startOffset, int endOffset) override { KTextEditor::Range range; range.setRange(cursorFromInt(startOffset), cursorFromInt(endOffset)); view()->view()->setSelection(range); view()->view()->setCursorPosition(cursorFromInt(endOffset)); } - QString attributes(int offset, int *startOffset, int *endOffset) const Q_DECL_OVERRIDE + QString attributes(int offset, int *startOffset, int *endOffset) const override { Q_UNUSED(offset); *startOffset = 0; *endOffset = characterCount(); return QString(); } - QRect characterRect(int offset) const Q_DECL_OVERRIDE + QRect characterRect(int offset) const override { KTextEditor::Cursor c = cursorFromInt(offset); if (!c.isValid()) { return QRect(); } QPoint p = view()->cursorToCoordinate(c); KTextEditor::Cursor endCursor = KTextEditor::Cursor(c.line(), c.column() + 1); QPoint size = view()->cursorToCoordinate(endCursor) - p; return QRect(view()->mapToGlobal(p), QSize(size.x(), size.y())); } - int cursorPosition() const Q_DECL_OVERRIDE + int cursorPosition() const override { KTextEditor::Cursor c = view()->getCursor(); return positionFromCursor(view(), c); } - int offsetAtPoint(const QPoint & /*point*/) const Q_DECL_OVERRIDE + int offsetAtPoint(const QPoint & /*point*/) const override { return 0; } - void removeSelection(int selectionIndex) Q_DECL_OVERRIDE + void removeSelection(int selectionIndex) override { if (selectionIndex != 0) { return; } view()->view()->clearSelection(); } - void scrollToSubstring(int /*startIndex*/, int /*endIndex*/) Q_DECL_OVERRIDE + void scrollToSubstring(int /*startIndex*/, int /*endIndex*/) override { // FIXME } - void selection(int selectionIndex, int *startOffset, int *endOffset) const Q_DECL_OVERRIDE + void selection(int selectionIndex, int *startOffset, int *endOffset) const override { if (selectionIndex != 0 || !view()->view()->selection()) { *startOffset = 0; *endOffset = 0; return; } KTextEditor::Range range = view()->view()->selectionRange(); *startOffset = positionFromCursor(view(), range.start()); *endOffset = positionFromCursor(view(), range.end()); } - int selectionCount() const Q_DECL_OVERRIDE + int selectionCount() const override { return view()->view()->selection() ? 1 : 0; } - void setCursorPosition(int position) Q_DECL_OVERRIDE + void setCursorPosition(int position) override { view()->view()->setCursorPosition(cursorFromInt(position)); } - void setSelection(int selectionIndex, int startOffset, int endOffset) Q_DECL_OVERRIDE + void setSelection(int selectionIndex, int startOffset, int endOffset) override { if (selectionIndex != 0) { return; } KTextEditor::Range range = KTextEditor::Range(cursorFromInt(startOffset), cursorFromInt(endOffset)); view()->view()->setSelection(range); } - QString text(int startOffset, int endOffset) const Q_DECL_OVERRIDE + QString text(int startOffset, int endOffset) const override { if (startOffset > endOffset) { return QString(); } return view()->view()->document()->text().mid(startOffset, endOffset - startOffset); } /** * When possible, using the last returned value m_lastPosition do the count * from the last cursor position m_lastCursor. * @return the number of chars (including one character for new lines) * from the beggining of the file. */ int positionFromCursor(KateViewInternal *view, const KTextEditor::Cursor &cursor) const { int pos = m_lastPosition; const auto *doc = view->view()->document(); // m_lastPosition < 0 is invalid, calculate from the beginning of the document if (m_lastPosition < 0 || view != m_lastView) { pos = 0; // Default (worst) case for (int line = 0; line < cursor.line(); ++line) { pos += doc->line(line).size(); } // new line for each line pos += cursor.line(); m_lastView = view; } else { // if the lines are the same, just add the cursor.column(), otherwise if (cursor.line() != m_lastCursor.line()) { // If the cursor is after the previous cursor if (m_lastCursor.line() < cursor.line()) { for (int line = m_lastCursor.line(); line < cursor.line(); ++line) { pos += doc->line(line).size(); } // add new line character for each line pos += cursor.line() - m_lastCursor.line(); } else { for (int line = cursor.line(); line < m_lastCursor.line(); ++line) { pos -= doc->line(line).size(); } // remove new line character for each line pos -= m_lastCursor.line() - cursor.line(); } } } m_lastCursor = cursor; m_lastPosition = pos; return pos + cursor.column(); } private: inline KateViewInternal *view() const { return static_cast(object()); } KTextEditor::Cursor cursorFromInt(int position) const { int line = 0; for (;;) { const QString lineString = view()->view()->document()->line(line); if (position > lineString.length()) { // one is the newline position -= lineString.length() + 1; ++line; } else { break; } } return KTextEditor::Cursor(line, position); } QString textLine(int shiftLines, int offset, int *startOffset, int *endOffset) const { KTextEditor::Cursor pos = cursorFromInt(offset); pos.setColumn(0); if (shiftLines) { pos.setLine(pos.line() + shiftLines); } *startOffset = positionFromCursor(view(), pos); QString line = view()->view()->document()->line(pos.line()) + QLatin1Char('\n'); *endOffset = *startOffset + line.length(); return line; } private: // Cache data for positionFromCursor mutable KateViewInternal *m_lastView; mutable KTextEditor::Cursor m_lastCursor; // m_lastPosition stores the positionFromCursor, with the cursor always in column 0 mutable int m_lastPosition; // to disconnect the signal QMetaObject::Connection m_conn; }; /** * Factory-function used to create \a KateViewAccessible instances for KateViewInternal * to make the KateViewInternal accessible. */ QAccessibleInterface *accessibleInterfaceFactory(const QString &key, QObject *object) { Q_UNUSED(key) //if (key == QLatin1String("KateViewInternal")) if (KateViewInternal *view = qobject_cast(object)) { return new KateViewAccessible(view); } return nullptr; } #endif #endif diff --git a/src/view/kateviewhelpers.cpp b/src/view/kateviewhelpers.cpp index 989b6609..0d8b1e4c 100644 --- a/src/view/kateviewhelpers.cpp +++ b/src/view/kateviewhelpers.cpp @@ -1,2892 +1,2892 @@ /* This file is part of the KDE libraries Copyright (C) 2008, 2009 Matthew Woehlke Copyright (C) 2007 Mirko Stocker Copyright (C) 2002 John Firebaugh Copyright (C) 2001 Anders Lund Copyright (C) 2001 Christoph Cullmann Copyright (C) 2011 Svyatoslav Kuzmich Copyright (C) 2012 Kåre Särs (Minimap) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. 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. 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. */ #include "kateviewhelpers.h" #include "katecmd.h" #include #include #include #include "kateconfig.h" #include "katedocument.h" #include #include "katerenderer.h" #include "kateview.h" #include "kateviewinternal.h" #include "katelayoutcache.h" #include "katetextlayout.h" #include "kateglobal.h" #include "katepartdebug.h" #include "katecommandrangeexpressionparser.h" #include "kateabstractinputmode.h" #include "katetextpreview.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //BEGIN KateMessageLayout KateMessageLayout::KateMessageLayout(QWidget *parent) : QLayout(parent) { } KateMessageLayout::~KateMessageLayout() { while (QLayoutItem *item = takeAt(0)) delete item; } void KateMessageLayout::addItem(QLayoutItem *item) { Q_ASSERT(false); add(item, KTextEditor::Message::CenterInView); } void KateMessageLayout::addWidget(QWidget *widget, KTextEditor::Message::MessagePosition pos) { add(new QWidgetItem(widget), pos); } int KateMessageLayout::count() const { return m_items.size(); } QLayoutItem *KateMessageLayout::itemAt(int index) const { if (index < 0 || index >= m_items.size()) return nullptr; return m_items[index]->item; } void KateMessageLayout::setGeometry(const QRect &rect) { QLayout::setGeometry(rect); const int s = spacing(); const QRect adjustedRect = rect.adjusted(s, s, -s, -s); for (auto wrapper : m_items) { QLayoutItem *item = wrapper->item; auto position = wrapper->position; if (position == KTextEditor::Message::TopInView) { const QRect r(adjustedRect.width() - item->sizeHint().width(), s, item->sizeHint().width(), item->sizeHint().height()); item->setGeometry(r); } else if (position == KTextEditor::Message::BottomInView) { const QRect r(adjustedRect.width() - item->sizeHint().width(), adjustedRect.height() - item->sizeHint().height(), item->sizeHint().width(), item->sizeHint().height()); item->setGeometry(r); } else if (position == KTextEditor::Message::CenterInView) { QRect r(0, 0, item->sizeHint().width(), item->sizeHint().height()); r.moveCenter(adjustedRect.center()); item->setGeometry(r); } else { Q_ASSERT_X(false, "setGeometry", "Only TopInView, CenterInView, and BottomInView are supported."); } } } QSize KateMessageLayout::sizeHint() const { return QSize(); } QLayoutItem *KateMessageLayout::takeAt(int index) { if (index >= 0 && index < m_items.size()) { ItemWrapper *layoutStruct = m_items.takeAt(index); return layoutStruct->item; } return 0; } void KateMessageLayout::add(QLayoutItem *item, KTextEditor::Message::MessagePosition pos) { m_items.push_back(new ItemWrapper(item, pos)); } //END KateMessageLayout //BEGIN KateScrollBar static const int s_lineWidth = 100; static const int s_pixelMargin = 8; static const int s_linePixelIncLimit = 6; const unsigned char KateScrollBar::characterOpacity[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // <- 15 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 255, 0, 0, 0, 0, 0, // <- 31 0, 125, 41, 221, 138, 195, 218, 21, 142, 142, 137, 137, 97, 87, 87, 140, // <- 47 223, 164, 183, 190, 191, 193, 214, 158, 227, 216, 103, 113, 146, 140, 146, 149, // <- 63 248, 204, 240, 174, 217, 197, 178, 205, 209, 176, 168, 211, 160, 246, 238, 218, // <- 79 195, 229, 227, 196, 167, 212, 188, 238, 197, 169, 189, 158, 21, 151, 115, 90, // <- 95 15, 192, 209, 153, 208, 187, 162, 221, 183, 149, 161, 191, 146, 203, 167, 182, // <- 111 208, 203, 139, 166, 158, 167, 157, 189, 164, 179, 156, 167, 145, 166, 109, 0, // <- 127 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // <- 143 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // <- 159 0, 125, 184, 187, 146, 201, 127, 203, 89, 194, 156, 141, 117, 87, 202, 88, // <- 175 115, 165, 118, 121, 85, 190, 236, 87, 88, 111, 151, 140, 194, 191, 203, 148, // <- 191 215, 215, 222, 224, 223, 234, 230, 192, 208, 208, 216, 217, 187, 187, 194, 195, // <- 207 228, 255, 228, 228, 235, 239, 237, 150, 255, 222, 222, 229, 232, 180, 197, 225, // <- 223 208, 208, 216, 217, 212, 230, 218, 170, 202, 202, 211, 204, 156, 156, 165, 159, // <- 239 214, 194, 197, 197, 206, 206, 201, 132, 214, 183, 183, 192, 187, 195, 227, 198 }; KateScrollBar::KateScrollBar(Qt::Orientation orientation, KateViewInternal *parent) : QScrollBar(orientation, parent->m_view) , m_middleMouseDown(false) , m_leftMouseDown(false) , m_view(parent->m_view) , m_doc(parent->doc()) , m_viewInternal(parent) , m_textPreview(nullptr) , m_showMarks(false) , m_showMiniMap(false) , m_miniMapAll(true) , m_miniMapWidth(40) , m_grooveHeight(height()) , m_linesModified(0) { connect(this, SIGNAL(valueChanged(int)), this, SLOT(sliderMaybeMoved(int))); connect(m_doc, SIGNAL(marksChanged(KTextEditor::Document*)), this, SLOT(marksChanged())); m_updateTimer.setInterval(300); m_updateTimer.setSingleShot(true); QTimer::singleShot(10, this, SLOT(updatePixmap())); // track mouse for text preview widget setMouseTracking(orientation == Qt::Vertical); // setup text preview timer m_delayTextPreviewTimer.setSingleShot(true); m_delayTextPreviewTimer.setInterval(250); connect(&m_delayTextPreviewTimer, SIGNAL(timeout()), this, SLOT(showTextPreview())); } KateScrollBar::~KateScrollBar() { delete m_textPreview; } void KateScrollBar::setShowMiniMap(bool b) { if (b && !m_showMiniMap) { connect(m_view, SIGNAL(selectionChanged(KTextEditor::View*)), &m_updateTimer, SLOT(start()), Qt::UniqueConnection); connect(m_doc, SIGNAL(textChanged(KTextEditor::Document*)), &m_updateTimer, SLOT(start()), Qt::UniqueConnection); connect(m_view, SIGNAL(delayedUpdateOfView()), &m_updateTimer, SLOT(start()), Qt::UniqueConnection); connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(updatePixmap()), Qt::UniqueConnection); connect(&(m_view->textFolding()), SIGNAL(foldingRangesChanged()), &m_updateTimer, SLOT(start()), Qt::UniqueConnection); } else if (!b) { disconnect(&m_updateTimer); } m_showMiniMap = b; updateGeometry(); update(); } QSize KateScrollBar::sizeHint() const { if (m_showMiniMap) { return QSize(m_miniMapWidth, QScrollBar::sizeHint().height()); } return QScrollBar::sizeHint(); } int KateScrollBar::minimapYToStdY(int y) { // Check if the minimap fills the whole scrollbar if (m_stdGroveRect.height() == m_mapGroveRect.height()) { return y; } // check if y is on the step up/down if ((y < m_stdGroveRect.top()) || (y > m_stdGroveRect.bottom())) { return y; } if (y < m_mapGroveRect.top()) { return m_stdGroveRect.top() + 1; } if (y > m_mapGroveRect.bottom()) { return m_stdGroveRect.bottom() - 1; } // check for div/0 if (m_mapGroveRect.height() == 0) { return y; } int newY = (y - m_mapGroveRect.top()) * m_stdGroveRect.height() / m_mapGroveRect.height(); newY += m_stdGroveRect.top(); return newY; } void KateScrollBar::mousePressEvent(QMouseEvent *e) { // delete text preview hideTextPreview(); if (e->button() == Qt::MidButton) { m_middleMouseDown = true; } else if (e->button() == Qt::LeftButton) { m_leftMouseDown = true; } if (m_showMiniMap) { if (m_leftMouseDown) { // if we show the minimap left-click jumps directly to the selected position int newVal = (e->pos().y()-m_mapGroveRect.top()) / (double)m_mapGroveRect.height() * (double)(maximum()+pageStep()) - pageStep()/2; newVal = qBound(0, newVal, maximum()); setSliderPosition(newVal); } QMouseEvent eMod(QEvent::MouseButtonPress, QPoint(6, minimapYToStdY(e->pos().y())), e->button(), e->buttons(), e->modifiers()); QScrollBar::mousePressEvent(&eMod); } else { QScrollBar::mousePressEvent(e); } m_toolTipPos = e->globalPos() - QPoint(e->pos().x(), 0); const int fromLine = m_viewInternal->toRealCursor(m_viewInternal->startPos()).line() + 1; const int lastLine = m_viewInternal->toRealCursor(m_viewInternal->endPos()).line() + 1; QToolTip::showText(m_toolTipPos, i18nc("from line - to line", "
%1

%2
", fromLine, lastLine), this); redrawMarks(); } void KateScrollBar::mouseReleaseEvent(QMouseEvent *e) { if (e->button() == Qt::MidButton) { m_middleMouseDown = false; } else if (e->button() == Qt::LeftButton) { m_leftMouseDown = false; } redrawMarks(); if (m_leftMouseDown || m_middleMouseDown) { QToolTip::hideText(); } if (m_showMiniMap) { QMouseEvent eMod(QEvent::MouseButtonRelease, QPoint(e->pos().x(), minimapYToStdY(e->pos().y())), e->button(), e->buttons(), e->modifiers()); QScrollBar::mouseReleaseEvent(&eMod); } else { QScrollBar::mouseReleaseEvent(e); } } void KateScrollBar::mouseMoveEvent(QMouseEvent *e) { if (m_showMiniMap) { QMouseEvent eMod(QEvent::MouseMove, QPoint(e->pos().x(), minimapYToStdY(e->pos().y())), e->button(), e->buttons(), e->modifiers()); QScrollBar::mouseMoveEvent(&eMod); } else { QScrollBar::mouseMoveEvent(e); } if (e->buttons() & (Qt::LeftButton | Qt::MidButton)) { redrawMarks(); // current line tool tip m_toolTipPos = e->globalPos() - QPoint(e->pos().x(), 0); const int fromLine = m_viewInternal->toRealCursor(m_viewInternal->startPos()).line() + 1; const int lastLine = m_viewInternal->toRealCursor(m_viewInternal->endPos()).line() + 1; QToolTip::showText(m_toolTipPos, i18nc("from line - to line", "
%1

%2
", fromLine, lastLine), this); } showTextPreviewDelayed(); } void KateScrollBar::leaveEvent(QEvent *event) { hideTextPreview(); QAbstractSlider::leaveEvent(event); } bool KateScrollBar::eventFilter(QObject *object, QEvent *event) { Q_UNUSED(object) if (m_textPreview && event->type() == QEvent::WindowDeactivate) { // We need hide the scrollbar TextPreview widget hideTextPreview(); } return false; } void KateScrollBar::paintEvent(QPaintEvent *e) { if (m_doc->marks().size() != m_lines.size()) { recomputeMarksPositions(); } if (m_showMiniMap) { miniMapPaintEvent(e); } else { normalPaintEvent(e); } } void KateScrollBar::showTextPreviewDelayed() { if (!m_textPreview) { if (!m_delayTextPreviewTimer.isActive()) { m_delayTextPreviewTimer.start(); } } else { showTextPreview(); } } void KateScrollBar::showTextPreview() { if (orientation() != Qt::Vertical || isSliderDown() || (minimum() == maximum()) || !m_view->config()->scrollBarPreview()) { return; } QRect grooveRect; if (m_showMiniMap) { // If mini-map is shown, the height of the map might not be the whole height grooveRect = m_mapGroveRect; } else { QStyleOptionSlider opt; opt.init(this); opt.subControls = QStyle::SC_None; opt.activeSubControls = QStyle::SC_None; opt.orientation = orientation(); opt.minimum = minimum(); opt.maximum = maximum(); opt.sliderPosition = sliderPosition(); opt.sliderValue = value(); opt.singleStep = singleStep(); opt.pageStep = pageStep(); grooveRect = style()->subControlRect(QStyle::CC_ScrollBar, &opt, QStyle::SC_ScrollBarGroove, this); } if (m_view->config()->scrollPastEnd()) { // Adjust the grove size to accommodate the added pageStep at the bottom int adjust = pageStep()*grooveRect.height() / (maximum() + pageStep() - minimum()); grooveRect.adjust(0,0,0, -adjust); } const QPoint cursorPos = mapFromGlobal(QCursor::pos()); if (grooveRect.contains(cursorPos)) { if (!m_textPreview) { m_textPreview = new KateTextPreview(m_view); m_textPreview->setAttribute(Qt::WA_ShowWithoutActivating); m_textPreview->setFrameStyle(QFrame::StyledPanel); // event filter to catch application WindowDeactivate event, to hide the preview window qApp->installEventFilter(this); } const qreal posInPercent = static_cast(cursorPos.y() - grooveRect.top()) / grooveRect.height(); const qreal startLine = posInPercent * m_view->textFolding().visibleLines(); m_textPreview->resize(m_view->width() / 2, m_view->height() / 5); const int xGlobal = mapToGlobal(QPoint(0, 0)).x(); const int yGlobal = qMin(mapToGlobal(QPoint(0, height())).y() - m_textPreview->height(), qMax(mapToGlobal(QPoint(0, 0)).y(), mapToGlobal(cursorPos).y() - m_textPreview->height() / 2)); m_textPreview->move(xGlobal - m_textPreview->width(), yGlobal); m_textPreview->setLine(startLine); m_textPreview->setCenterView(true); m_textPreview->setScaleFactor(0.8); m_textPreview->raise(); m_textPreview->show(); } else { hideTextPreview(); } } void KateScrollBar::hideTextPreview() { if (m_delayTextPreviewTimer.isActive()) { m_delayTextPreviewTimer.stop(); } qApp->removeEventFilter(this); delete m_textPreview; } // This function is optimized for bing called in sequence. const QColor KateScrollBar::charColor(const QVector &attributes, int &attributeIndex, const QList &decorations, const QColor &defaultColor, int x, QChar ch) { QColor color = defaultColor; bool styleFound = false; // Query the decorations, that is, things like search highlighting, or the // KDevelop DUChain highlighting, for a color to use foreach (const QTextLayout::FormatRange &range, decorations) { if (range.start <= x && range.start + range.length > x) { // If there's a different background color set (search markers, ...) // use that, otherwise use the foreground color. if (range.format.hasProperty(QTextFormat::BackgroundBrush)) { color = range.format.background().color(); } else { color = range.format.foreground().color(); } styleFound = true; break; } } // If there's no decoration set for the current character (this will mostly be the case for // plain Kate), query the styles, that is, the default kate syntax highlighting. if (!styleFound) { // go to the block containing x while ((attributeIndex < attributes.size()) && ((attributes[attributeIndex].offset + attributes[attributeIndex].length) < x)) { ++attributeIndex; } if ((attributeIndex < attributes.size()) && (x < attributes[attributeIndex].offset + attributes[attributeIndex].length)) { color = m_view->renderer()->attribute(attributes[attributeIndex].attributeValue)->foreground().color(); } } // Query how much "blackness" the character has. // This causes for example a dot or a dash to appear less intense // than an A or similar. // This gives the pixels created a bit of structure, which makes it look more // like real text. color.setAlpha((ch.unicode() < 256) ? characterOpacity[ch.unicode()] : 222); return color; } void KateScrollBar::updatePixmap() { //QTime time; //time.start(); if (!m_showMiniMap) { // make sure no time is wasted if the option is disabled return; } // For performance reason, only every n-th line will be drawn if the widget is // sufficiently small compared to the amount of lines in the document. int docLineCount = m_view->textFolding().visibleLines(); int pixmapLineCount = docLineCount; if (m_view->config()->scrollPastEnd()) { pixmapLineCount += pageStep(); } int pixmapLinesUnscaled = pixmapLineCount; if (m_grooveHeight < 5) { m_grooveHeight = 5; } int lineDivisor = pixmapLinesUnscaled / m_grooveHeight; if (lineDivisor < 1) { lineDivisor = 1; } int charIncrement = 1; int lineIncrement = 1; if ((m_grooveHeight > 10) && (pixmapLineCount >= m_grooveHeight * 2)) { charIncrement = pixmapLineCount / m_grooveHeight; while (charIncrement > s_linePixelIncLimit) { lineIncrement++; pixmapLineCount = pixmapLinesUnscaled / lineIncrement; charIncrement = pixmapLineCount / m_grooveHeight; } pixmapLineCount /= charIncrement; } int pixmapLineWidth = s_pixelMargin + s_lineWidth / charIncrement; //qCDebug(LOG_KTE) << "l" << lineIncrement << "c" << charIncrement << "d" << lineDivisor; //qCDebug(LOG_KTE) << "pixmap" << pixmapLineCount << pixmapLineWidth << "docLines" << m_view->textFolding().visibleLines() << "height" << m_grooveHeight; const QColor backgroundColor = m_view->defaultStyleAttribute(KTextEditor::dsNormal)->background().color(); const QColor defaultTextColor = m_view->defaultStyleAttribute(KTextEditor::dsNormal)->foreground().color(); const QColor selectionBgColor = m_view->renderer()->config()->selectionColor(); QColor modifiedLineColor = m_view->renderer()->config()->modifiedLineColor(); QColor savedLineColor = m_view->renderer()->config()->savedLineColor(); // move the modified line color away from the background color modifiedLineColor.setHsv(modifiedLineColor.hue(), 255, 255 - backgroundColor.value() / 3); savedLineColor.setHsv(savedLineColor.hue(), 100, 255 - backgroundColor.value() / 3); // increase dimensions by ratio m_pixmap = QPixmap(pixmapLineWidth * m_view->devicePixelRatioF(), pixmapLineCount * m_view->devicePixelRatioF()); m_pixmap.fill(QColor("transparent")); // The text currently selected in the document, to be drawn later. const KTextEditor::Range &selection = m_view->selectionRange(); QPainter painter; if (painter.begin(&m_pixmap)) { // init pen once, afterwards, only change it if color changes to avoid a lot of allocation for setPen painter.setPen(selectionBgColor); // Do not force updates of the highlighting if the document is very large bool simpleMode = m_doc->lines() > 7500; int pixelY = 0; int drawnLines = 0; // Iterate over all visible lines, drawing them. for (int virtualLine = 0; virtualLine < docLineCount; virtualLine += lineIncrement) { int realLineNumber = m_view->textFolding().visibleLineToLine(virtualLine); QString lineText = m_doc->line(realLineNumber); if (!simpleMode) { m_doc->buffer().ensureHighlighted(realLineNumber); } const Kate::TextLine &kateline = m_doc->plainKateTextLine(realLineNumber); const QVector &attributes = kateline->attributesList(); QList< QTextLayout::FormatRange > decorations = m_view->renderer()->decorationsForLine(kateline, realLineNumber); int attributeIndex = 0; // Draw selection if it is on an empty line if (selection.contains(KTextEditor::Cursor(realLineNumber, 0)) && lineText.size() == 0) { if (selectionBgColor != painter.pen().color()) { painter.setPen(selectionBgColor); } painter.drawLine(s_pixelMargin, pixelY, s_pixelMargin + s_lineWidth - 1, pixelY); } // Iterate over the line to draw the background int selStartX = -1; int selEndX = -1; int pixelX = s_pixelMargin; // use this to control the offset of the text from the left for (int x = 0; (x < lineText.size() && x < s_lineWidth); x += charIncrement) { if (pixelX >= s_lineWidth + s_pixelMargin) { break; } // Query the selection and draw it behind the character if (selection.contains(KTextEditor::Cursor(realLineNumber, x))) { if (selStartX == -1) selStartX = pixelX; selEndX = pixelX; if (lineText.size() - 1 == x) { selEndX = s_lineWidth + s_pixelMargin-1; } } if (lineText[x] == QLatin1Char('\t')) { pixelX += qMax(4 / charIncrement, 1); // FIXME: tab width... } else { pixelX++; } } if (selStartX != -1) { if (selectionBgColor != painter.pen().color()) { painter.setPen(selectionBgColor); } painter.drawLine(selStartX, pixelY, selEndX, pixelY); } // Iterate over all the characters in the current line pixelX = s_pixelMargin; for (int x = 0; (x < lineText.size() && x < s_lineWidth); x += charIncrement) { if (pixelX >= s_lineWidth + s_pixelMargin) { break; } // draw the pixels if (lineText[x] == QLatin1Char(' ')) { pixelX++; } else if (lineText[x] == QLatin1Char('\t')) { pixelX += qMax(4 / charIncrement, 1); // FIXME: tab width... } else { const QColor newPenColor(charColor(attributes, attributeIndex, decorations, defaultTextColor, x, lineText[x])); if (newPenColor != painter.pen().color()) { painter.setPen(newPenColor); } // Actually draw the pixel with the color queried from the renderer. painter.drawPoint(pixelX, pixelY); pixelX++; } } drawnLines++; if (((drawnLines) % charIncrement) == 0) { pixelY++; } } //qCDebug(LOG_KTE) << drawnLines; // Draw line modification marker map. // Disable this if the document is really huge, // since it requires querying every line. if (m_doc->lines() < 50000) { for (int lineno = 0; lineno < docLineCount; lineno++) { int realLineNo = m_view->textFolding().visibleLineToLine(lineno); const Kate::TextLine &line = m_doc->plainKateTextLine(realLineNo); const QColor & col = line->markedAsModified() ? modifiedLineColor : savedLineColor; if (line->markedAsModified() || line->markedAsSavedOnDisk()) { painter.fillRect(2, lineno / lineDivisor, 3, 1, col); } } } // end painting painter.end(); } // set right ratio m_pixmap.setDevicePixelRatio(m_view->devicePixelRatioF()); //qCDebug(LOG_KTE) << time.elapsed(); // Redraw the scrollbar widget with the updated pixmap. update(); } void KateScrollBar::miniMapPaintEvent(QPaintEvent *e) { QScrollBar::paintEvent(e); QPainter painter(this); QStyleOptionSlider opt; opt.init(this); opt.subControls = QStyle::SC_None; opt.activeSubControls = QStyle::SC_None; opt.orientation = orientation(); opt.minimum = minimum(); opt.maximum = maximum(); opt.sliderPosition = sliderPosition(); opt.sliderValue = value(); opt.singleStep = singleStep(); opt.pageStep = pageStep(); QRect grooveRect = style()->subControlRect(QStyle::CC_ScrollBar, &opt, QStyle::SC_ScrollBarGroove, this); m_stdGroveRect = grooveRect; if (style()->subControlRect(QStyle::CC_ScrollBar, &opt, QStyle::SC_ScrollBarSubLine, this).height() == 0) { int alignMargin = style()->pixelMetric(QStyle::PM_FocusFrameVMargin, &opt, this); grooveRect.moveTop(alignMargin); grooveRect.setHeight(grooveRect.height() - alignMargin); } if (style()->subControlRect(QStyle::CC_ScrollBar, &opt, QStyle::SC_ScrollBarAddLine, this).height() == 0) { int alignMargin = style()->pixelMetric(QStyle::PM_FocusFrameVMargin, &opt, this); grooveRect.setHeight(grooveRect.height() - alignMargin); } m_grooveHeight = grooveRect.height(); const int docXMargin = 1; QRect sliderRect = style()->subControlRect(QStyle::CC_ScrollBar, &opt, QStyle::SC_ScrollBarSlider, this); sliderRect.adjust(docXMargin, 0, 0, 0); //style()->drawControl(QStyle::CE_ScrollBarAddLine, &opt, &painter, this); //style()->drawControl(QStyle::CE_ScrollBarSubLine, &opt, &painter, this); // calculate the document size and position const int docHeight = qMin(grooveRect.height(), int(m_pixmap.height() / m_pixmap.devicePixelRatio() * 2)) - 2 * docXMargin; const int yoffset = 1; // top-aligned in stead of center-aligned (grooveRect.height() - docHeight) / 2; const QRect docRect(QPoint(grooveRect.left() + docXMargin, yoffset + grooveRect.top()), QSize(grooveRect.width() - docXMargin, docHeight)); m_mapGroveRect = docRect; // calculate the visible area int max = qMax(maximum() + 1, 1); int visibleStart = value() * docHeight / (max + pageStep()) + docRect.top() + 0.5; int visibleEnd = (value() + pageStep()) * docHeight / (max + pageStep()) + docRect.top(); QRect visibleRect = docRect; visibleRect.moveTop(visibleStart); visibleRect.setHeight(visibleEnd - visibleStart); // calculate colors const QColor backgroundColor = m_view->defaultStyleAttribute(KTextEditor::dsNormal)->background().color(); const QColor foregroundColor = m_view->defaultStyleAttribute(KTextEditor::dsNormal)->foreground().color(); const QColor highlightColor = palette().link().color(); const int backgroundLightness = backgroundColor.lightness(); const int foregroundLightness = foregroundColor.lightness(); const int lighnessDiff = (foregroundLightness - backgroundLightness); // get a color suited for the color theme QColor darkShieldColor = palette().color(QPalette::Mid); int hue, sat, light; darkShieldColor.getHsl(&hue, &sat, &light); // apply suitable lightness darkShieldColor.setHsl(hue, sat, backgroundLightness + lighnessDiff * 0.35); // gradient for nicer results QLinearGradient gradient(0, 0, width(), 0); gradient.setColorAt(0, darkShieldColor); gradient.setColorAt(0.3, darkShieldColor.lighter(115)); gradient.setColorAt(1, darkShieldColor); QColor lightShieldColor; lightShieldColor.setHsl(hue, sat, backgroundLightness + lighnessDiff * 0.15); QColor outlineColor; outlineColor.setHsl(hue, sat, backgroundLightness + lighnessDiff * 0.5); // draw the grove background in case the document is small painter.setPen(Qt::NoPen); painter.setBrush(backgroundColor); painter.drawRect(grooveRect); // adjust the rectangles if ((docHeight + 2 * docXMargin >= grooveRect.height()) && (sliderRect.height() > visibleRect.height() + 2)) { visibleRect.adjust(2, 0, -3, 0); } else { visibleRect.adjust(1, 0, -1, 2); sliderRect.setTop(visibleRect.top() - 1); sliderRect.setBottom(visibleRect.bottom() + 1); } // Smooth transform only when squeezing if (grooveRect.height() < m_pixmap.height() / m_pixmap.devicePixelRatio()) { painter.setRenderHint(QPainter::SmoothPixmapTransform); } // draw the modified lines margin QRect pixmapMarginRect(QPoint(0, 0), QSize(s_pixelMargin, m_pixmap.height() / m_pixmap.devicePixelRatio())); QRect docPixmapMarginRect(QPoint(0, docRect.top()), QSize(s_pixelMargin, docRect.height())); painter.drawPixmap(docPixmapMarginRect, m_pixmap, pixmapMarginRect); // calculate the stretch and draw the stretched lines (scrollbar marks) QRect pixmapRect(QPoint(s_pixelMargin, 0), QSize(m_pixmap.width() / m_pixmap.devicePixelRatio() - s_pixelMargin, m_pixmap.height() / m_pixmap.devicePixelRatio())); QRect docPixmapRect(QPoint(s_pixelMargin, docRect.top()), QSize(docRect.width() - s_pixelMargin, docRect.height())); painter.drawPixmap(docPixmapRect, m_pixmap, pixmapRect); // delimit the end of the document const int y = docPixmapRect.height() + grooveRect.y(); if (y+2 < grooveRect.y() + grooveRect.height()) { QColor fg(foregroundColor); fg.setAlpha(30); painter.setBrush(Qt::NoBrush); painter.setPen(QPen(fg, 1)); painter.drawLine(grooveRect.x()+1,y+2,width()-1,y+2); } // fade the invisible sections const QRect top( grooveRect.x(), grooveRect.y(), grooveRect.width(), visibleRect.y()-grooveRect.y() //Pen width ); const QRect bottom( grooveRect.x(), grooveRect.y()+visibleRect.y()+visibleRect.height()-grooveRect.y(), //Pen width grooveRect.width(), grooveRect.height() - (visibleRect.y()-grooveRect.y())-visibleRect.height() ); QColor faded(backgroundColor); faded.setAlpha(110); painter.fillRect(top, faded); painter.fillRect(bottom, faded); // add a thin line to limit the scrollbar QColor c(foregroundColor); c.setAlpha(10); painter.setPen(QPen(c,1)); painter.drawLine(0, 0, 0, height()); if (m_showMarks) { QHashIterator it = m_lines; QPen penBg; penBg.setWidth(4); lightShieldColor.setAlpha(180); penBg.setColor(lightShieldColor); painter.setPen(penBg); while (it.hasNext()) { it.next(); int y = (it.key() - grooveRect.top()) * docHeight / grooveRect.height() + docRect.top();; painter.drawLine(6, y, width() - 6, y); } it = m_lines; QPen pen; pen.setWidth(2); while (it.hasNext()) { it.next(); pen.setColor(it.value()); painter.setPen(pen); int y = (it.key() - grooveRect.top()) * docHeight / grooveRect.height() + docRect.top(); painter.drawLine(6, y, width() - 6, y); } } // slider outline QColor sliderColor(highlightColor); sliderColor.setAlpha(50); painter.fillRect(sliderRect, sliderColor); painter.setPen(QPen(highlightColor, 0)); // rounded rect looks ugly for some reason, so we draw 4 lines. painter.drawLine(sliderRect.left(), sliderRect.top() + 1, sliderRect.left(), sliderRect.bottom() - 1); painter.drawLine(sliderRect.right(), sliderRect.top() + 1, sliderRect.right(), sliderRect.bottom() - 1); painter.drawLine(sliderRect.left() + 1, sliderRect.top(), sliderRect.right() - 1, sliderRect.top()); painter.drawLine(sliderRect.left() + 1, sliderRect.bottom(), sliderRect.right() - 1, sliderRect.bottom()); } void KateScrollBar::normalPaintEvent(QPaintEvent *e) { QScrollBar::paintEvent(e); if (!m_showMarks) { return; } QPainter painter(this); QStyleOptionSlider opt; opt.init(this); opt.subControls = QStyle::SC_None; opt.activeSubControls = QStyle::SC_None; opt.orientation = orientation(); opt.minimum = minimum(); opt.maximum = maximum(); opt.sliderPosition = sliderPosition(); opt.sliderValue = value(); opt.singleStep = singleStep(); opt.pageStep = pageStep(); QRect rect = style()->subControlRect(QStyle::CC_ScrollBar, &opt, QStyle::SC_ScrollBarSlider, this); int sideMargin = width() - rect.width(); if (sideMargin < 4) { sideMargin = 4; } sideMargin /= 2; QHashIterator it = m_lines; while (it.hasNext()) { it.next(); painter.setPen(it.value()); if (it.key() < rect.top() || it.key() > rect.bottom()) { painter.drawLine(0, it.key(), width(), it.key()); } else { painter.drawLine(0, it.key(), sideMargin, it.key()); painter.drawLine(width() - sideMargin, it.key(), width(), it.key()); } } } void KateScrollBar::resizeEvent(QResizeEvent *e) { QScrollBar::resizeEvent(e); m_updateTimer.start(); m_lines.clear(); update(); } void KateScrollBar::sliderChange(SliderChange change) { // call parents implementation QScrollBar::sliderChange(change); if (change == QAbstractSlider::SliderValueChange) { redrawMarks(); } else if (change == QAbstractSlider::SliderRangeChange) { marksChanged(); } if (m_leftMouseDown || m_middleMouseDown) { const int fromLine = m_viewInternal->toRealCursor(m_viewInternal->startPos()).line() + 1; const int lastLine = m_viewInternal->toRealCursor(m_viewInternal->endPos()).line() + 1; QToolTip::showText(m_toolTipPos, i18nc("from line - to line", "
%1

%2
", fromLine, lastLine), this); } } void KateScrollBar::marksChanged() { m_lines.clear(); update(); } void KateScrollBar::redrawMarks() { if (!m_showMarks) { return; } update(); } void KateScrollBar::recomputeMarksPositions() { // get the style options to compute the scrollbar pixels QStyleOptionSlider opt; initStyleOption(&opt); QRect grooveRect = style()->subControlRect(QStyle::CC_ScrollBar, &opt, QStyle::SC_ScrollBarGroove, this); // cache top margin and groove height const int top = grooveRect.top(); const int h = grooveRect.height() - 1; // make sure we have a sane height if (h <= 0) { return; } // get total visible (=without folded) lines in the document int visibleLines = m_view->textFolding().visibleLines() - 1; if (m_view->config()->scrollPastEnd()) { visibleLines += m_viewInternal->linesDisplayed() - 1; visibleLines -= m_view->config()->autoCenterLines(); } // now repopulate the scrollbar lines list m_lines.clear(); const QHash &marks = m_doc->marks(); for (QHash::const_iterator i = marks.constBegin(); i != marks.constEnd(); ++i) { KTextEditor::Mark *mark = i.value(); const int line = m_view->textFolding().lineToVisibleLine(mark->line); const double ratio = static_cast(line) / visibleLines; m_lines.insert(top + (int)(h * ratio), KateRendererConfig::global()->lineMarkerColor((KTextEditor::MarkInterface::MarkTypes)mark->type)); } } void KateScrollBar::sliderMaybeMoved(int value) { if (m_middleMouseDown) { // we only need to emit this signal once, as for the following slider // movements the signal sliderMoved() is already emitted. // Thus, set m_middleMouseDown to false right away. m_middleMouseDown = false; emit sliderMMBMoved(value); } } //END //BEGIN KateCmdLineEditFlagCompletion /** * This class provide completion of flags. It shows a short description of * each flag, and flags are appended. */ class KateCmdLineEditFlagCompletion : public KCompletion { public: KateCmdLineEditFlagCompletion() { ; } - QString makeCompletion(const QString & /*s*/) Q_DECL_OVERRIDE + QString makeCompletion(const QString & /*s*/) override { return QString(); } }; //END KateCmdLineEditFlagCompletion //BEGIN KateCmdLineEdit KateCommandLineBar::KateCommandLineBar(KTextEditor::ViewPrivate *view, QWidget *parent) : KateViewBarWidget(true, parent) { QHBoxLayout *topLayout = new QHBoxLayout(); centralWidget()->setLayout(topLayout); topLayout->setMargin(0); m_lineEdit = new KateCmdLineEdit(this, view); connect(m_lineEdit, SIGNAL(hideRequested()), SIGNAL(hideMe())); topLayout->addWidget(m_lineEdit); QToolButton *helpButton = new QToolButton(this); helpButton->setAutoRaise(true); helpButton->setIcon(QIcon::fromTheme(QStringLiteral("help-contextual"))); topLayout->addWidget(helpButton); connect(helpButton, SIGNAL(clicked()), this, SLOT(showHelpPage())); setFocusProxy(m_lineEdit); } void KateCommandLineBar::showHelpPage() { KHelpClient::invokeHelp(QStringLiteral("advanced-editing-tools-commandline"), QStringLiteral("kate")); } KateCommandLineBar::~KateCommandLineBar() { } // inserts the given string in the command line edit and (if selected = true) selects it so the user // can type over it if they want to void KateCommandLineBar::setText(const QString &text, bool selected) { m_lineEdit->setText(text); if (selected) { m_lineEdit->selectAll(); } } void KateCommandLineBar::execute(const QString &text) { m_lineEdit->slotReturnPressed(text); } KateCmdLineEdit::KateCmdLineEdit(KateCommandLineBar *bar, KTextEditor::ViewPrivate *view) : KLineEdit() , m_view(view) , m_bar(bar) , m_msgMode(false) , m_histpos(0) , m_cmdend(0) , m_command(nullptr) { connect(this, SIGNAL(returnPressed(QString)), this, SLOT(slotReturnPressed(QString))); setCompletionObject(KateCmd::self()->commandCompletionObject()); setAutoDeleteCompletionObject(false); m_hideTimer = new QTimer(this); m_hideTimer->setSingleShot(true); connect(m_hideTimer, SIGNAL(timeout()), this, SLOT(hideLineEdit())); // make sure the timer is stopped when the user switches views. if not, focus will be given to the // wrong view when KateViewBar::hideCurrentBarWidget() is called after 4 seconds. (the timer is // used for showing things like "Success" for four seconds after the user has used the kate // command line) connect(m_view, SIGNAL(focusOut(KTextEditor::View*)), m_hideTimer, SLOT(stop())); } void KateCmdLineEdit::hideEvent(QHideEvent *e) { Q_UNUSED(e); } QString KateCmdLineEdit::helptext(const QPoint &) const { QString beg = QStringLiteral("
Help: "); QString mid = QStringLiteral("
"); QString end = QStringLiteral("
"); QString t = text(); QRegExp re(QLatin1String("\\s*help\\s+(.*)")); if (re.indexIn(t) > -1) { QString s; // get help for command QString name = re.cap(1); if (name == QLatin1String("list")) { return beg + i18n("Available Commands") + mid + KateCmd::self()->commandList().join(QLatin1Char(' ')) + i18n("

For help on individual commands, do 'help <command>'

") + end; } else if (! name.isEmpty()) { KTextEditor::Command *cmd = KateCmd::self()->queryCommand(name); if (cmd) { if (cmd->help(m_view, name, s)) { return beg + name + mid + s + end; } else { return beg + name + mid + i18n("No help for '%1'", name) + end; } } else { return beg + mid + i18n("No such command %1", name) + end; } } } return beg + mid + i18n( "

This is the Katepart command line.
" "Syntax: command [ arguments ]
" "For a list of available commands, enter help list
" "For help for individual commands, enter help <command>

") + end; } bool KateCmdLineEdit::event(QEvent *e) { if (e->type() == QEvent::QueryWhatsThis) { setWhatsThis(helptext(QPoint())); e->accept(); return true; } return KLineEdit::event(e); } /** * Parse the text as a command. * * The following is a simple PEG grammar for the syntax of the command. * (A PEG grammar is like a BNF grammar, except that "/" stands for * ordered choice: only the first matching rule is used. In other words, * the parsing is short-circuited in the manner of the "or" operator in * programming languages, and so the grammar is unambiguous.) * * Text <- Range? Command * / Position * Range <- Position ("," Position)? * / "%" * Position <- Base Offset? * Base <- Line * / LastLine * / ThisLine * / Mark * Offset <- [+-] Base * Line <- [0-9]+ * LastLine <- "$" * ThisLine <- "." * Mark <- "'" [a-z] */ void KateCmdLineEdit::slotReturnPressed(const QString &text) { if (text.isEmpty()) { return; } // silently ignore leading space characters uint n = 0; const uint textlen = text.length(); while ((n < textlen) && (text[n].isSpace())) { n++; } if (n >= textlen) { return; } QString cmd = text.mid(n); // Parse any leading range expression, and strip it (and maybe do some other transforms on the command). QString leadingRangeExpression; KTextEditor::Range range = CommandRangeExpressionParser::parseRangeExpression(cmd, m_view, leadingRangeExpression, cmd); // Built in help: if the command starts with "help", [try to] show some help if (cmd.startsWith(QLatin1String("help"))) { QWhatsThis::showText(mapToGlobal(QPoint(0, 0)), helptext(QPoint())); clear(); KateCmd::self()->appendHistory(cmd); m_histpos = KateCmd::self()->historyLength(); m_oldText.clear(); return; } if (cmd.length() > 0) { KTextEditor::Command *p = KateCmd::self()->queryCommand(cmd); m_oldText = leadingRangeExpression + cmd; m_msgMode = true; // the following commands changes the focus themselves, so bar should be hidden before execution. if (QRegExp(QLatin1String("buffer|b|new|vnew|bp|bprev|bn|bnext|bf|bfirst|bl|blast|edit|e")).exactMatch(cmd.split(QLatin1Char(' ')).at(0))) { emit hideRequested(); } if (!p) { setText(i18n("No such command: \"%1\"", cmd)); } else if (range.isValid() && !p->supportsRange(cmd)) { // Raise message, when the command does not support ranges. setText(i18n("Error: No range allowed for command \"%1\".", cmd)); } else { QString msg; if (p->exec(m_view, cmd, msg, range)) { // append command along with range (will be empty if none given) to history KateCmd::self()->appendHistory(leadingRangeExpression + cmd); m_histpos = KateCmd::self()->historyLength(); m_oldText.clear(); if (msg.length() > 0) { setText(i18n("Success: ") + msg); } else if (isVisible()) { // always hide on success without message emit hideRequested(); } } else { if (msg.length() > 0) { if (msg.contains(QLatin1Char('\n'))) { // multiline error, use widget with more space QWhatsThis::showText(mapToGlobal(QPoint(0, 0)), msg); } else { setText(msg); } } else { setText(i18n("Command \"%1\" failed.", cmd)); } } } } // clean up if (completionObject() != KateCmd::self()->commandCompletionObject()) { KCompletion *c = completionObject(); setCompletionObject(KateCmd::self()->commandCompletionObject()); delete c; } m_command = nullptr; m_cmdend = 0; // the following commands change the focus themselves if (!QRegExp(QLatin1String("buffer|b|new|vnew|bp|bprev|bn|bnext|bf|bfirst|bl|blast|edit|e")).exactMatch(cmd.split(QLatin1Char(' ')).at(0))) { m_view->setFocus(); } if (isVisible()) { m_hideTimer->start(4000); } } void KateCmdLineEdit::hideLineEdit() // unless i have focus ;) { if (! hasFocus()) { emit hideRequested(); } } void KateCmdLineEdit::focusInEvent(QFocusEvent *ev) { if (m_msgMode) { m_msgMode = false; setText(m_oldText); selectAll(); } KLineEdit::focusInEvent(ev); } void KateCmdLineEdit::keyPressEvent(QKeyEvent *ev) { if (ev->key() == Qt::Key_Escape || (ev->key() == Qt::Key_BracketLeft && ev->modifiers() == Qt::ControlModifier)) { m_view->setFocus(); hideLineEdit(); clear(); } else if (ev->key() == Qt::Key_Up) { fromHistory(true); } else if (ev->key() == Qt::Key_Down) { fromHistory(false); } uint cursorpos = cursorPosition(); KLineEdit::keyPressEvent(ev); // during typing, let us see if we have a valid command if (! m_cmdend || cursorpos <= m_cmdend) { QChar c; if (! ev->text().isEmpty()) { c = ev->text().at(0); } if (! m_cmdend && ! c.isNull()) { // we have no command, so lets see if we got one if (! c.isLetterOrNumber() && c != QLatin1Char('-') && c != QLatin1Char('_')) { m_command = KateCmd::self()->queryCommand(text().trimmed()); if (m_command) { //qCDebug(LOG_KTE)<<"keypress in commandline: We have a command! "<queryCommand(text().trimmed()); if (m_command) { //qCDebug(LOG_KTE)<<"keypress in commandline: We have a command! "<commandCompletionObject()) { KCompletion *c = completionObject(); setCompletionObject(KateCmd::self()->commandCompletionObject()); delete c; } m_cmdend = 0; } } // if we got a command, check if it wants to do something. if (m_command) { KCompletion *cmpl = m_command->completionObject(m_view, text().left(m_cmdend).trimmed()); if (cmpl) { // We need to prepend the current command name + flag string // when completion is done //qCDebug(LOG_KTE)<<"keypress in commandline: Setting completion object!"; setCompletionObject(cmpl); } } } else if (m_command && !ev->text().isEmpty()) { // check if we should call the commands processText() if (m_command->wantsToProcessText(text().left(m_cmdend).trimmed())) { m_command->processText(m_view, text()); } } } void KateCmdLineEdit::fromHistory(bool up) { if (! KateCmd::self()->historyLength()) { return; } QString s; if (up) { if (m_histpos > 0) { m_histpos--; s = KateCmd::self()->fromHistory(m_histpos); } } else { if (m_histpos < (KateCmd::self()->historyLength() - 1)) { m_histpos++; s = KateCmd::self()->fromHistory(m_histpos); } else { m_histpos = KateCmd::self()->historyLength(); setText(m_oldText); } } if (! s.isEmpty()) { // Select the argument part of the command, so that it is easy to overwrite setText(s); static QRegExp reCmd = QRegExp(QLatin1String(".*[\\w\\-]+(?:[^a-zA-Z0-9_-]|:\\w+)(.*)")); if (reCmd.indexIn(text()) == 0) { setSelection(text().length() - reCmd.cap(1).length(), reCmd.cap(1).length()); } } } //END KateCmdLineEdit //BEGIN KateIconBorder using namespace KTextEditor; KateIconBorder::KateIconBorder(KateViewInternal *internalView, QWidget *parent) : QWidget(parent) , m_view(internalView->m_view) , m_doc(internalView->doc()) , m_viewInternal(internalView) , m_iconBorderOn(false) , m_lineNumbersOn(false) , m_relLineNumbersOn(false) , m_updateRelLineNumbers(false) , m_foldingMarkersOn(false) , m_dynWrapIndicatorsOn(false) , m_annotationBorderOn(false) , m_dynWrapIndicators(0) , m_lastClickedLine(-1) , m_cachedLNWidth(0) , m_maxCharWidth(0.0) , iconPaneWidth(16) , m_annotationBorderWidth(6) , m_foldingPreview(nullptr) , m_foldingRange(nullptr) , m_nextHighlightBlock(-2) , m_currentBlockLine(-1) { setAttribute(Qt::WA_StaticContents); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum); setMouseTracking(true); m_doc->setMarkDescription(MarkInterface::markType01, i18n("Bookmark")); m_doc->setMarkPixmap(MarkInterface::markType01, QIcon::fromTheme(QStringLiteral("bookmarks")).pixmap(16, 16)); updateFont(); m_delayFoldingHlTimer.setSingleShot(true); m_delayFoldingHlTimer.setInterval(150); connect(&m_delayFoldingHlTimer, SIGNAL(timeout()), this, SLOT(showBlock())); // user interaction (scrolling) hides e.g. preview connect(m_view, SIGNAL(displayRangeChanged(KTextEditor::ViewPrivate*)), this, SLOT(displayRangeChanged())); } KateIconBorder::~KateIconBorder() { delete m_foldingPreview; delete m_foldingRange; } void KateIconBorder::setIconBorderOn(bool enable) { if (enable == m_iconBorderOn) { return; } m_iconBorderOn = enable; updateGeometry(); QTimer::singleShot(0, this, SLOT(update())); } void KateIconBorder::setAnnotationBorderOn(bool enable) { if (enable == m_annotationBorderOn) { return; } m_annotationBorderOn = enable; emit m_view->annotationBorderVisibilityChanged(m_view, enable); updateGeometry(); QTimer::singleShot(0, this, SLOT(update())); } void KateIconBorder::removeAnnotationHovering() { // remove hovering if it's still there if (m_annotationBorderOn && !m_hoveredAnnotationGroupIdentifier.isEmpty()) { m_hoveredAnnotationGroupIdentifier.clear(); hideAnnotationTooltip(); QTimer::singleShot(0, this, SLOT(update())); } } void KateIconBorder::setLineNumbersOn(bool enable) { if (enable == m_lineNumbersOn) { return; } m_lineNumbersOn = enable; m_dynWrapIndicatorsOn = (m_dynWrapIndicators == 1) ? enable : m_dynWrapIndicators; updateGeometry(); QTimer::singleShot(0, this, SLOT(update())); } void KateIconBorder::setRelLineNumbersOn(bool enable) { if (enable == m_relLineNumbersOn) { return; } m_relLineNumbersOn = enable; /* * We don't have to touch the m_dynWrapIndicatorsOn because * we already got it right from the m_lineNumbersOn */ updateGeometry(); QTimer::singleShot( 0, this, SLOT(update()) ); } void KateIconBorder::updateForCursorLineChange() { if (m_relLineNumbersOn) { m_updateRelLineNumbers = true; } // always do normal update, e.g. for different current line color! update(); } void KateIconBorder::setDynWrapIndicators(int state) { if (state == m_dynWrapIndicators) { return; } m_dynWrapIndicators = state; m_dynWrapIndicatorsOn = (state == 1) ? m_lineNumbersOn : state; updateGeometry(); QTimer::singleShot(0, this, SLOT(update())); } void KateIconBorder::setFoldingMarkersOn(bool enable) { if (enable == m_foldingMarkersOn) { return; } m_foldingMarkersOn = enable; updateGeometry(); QTimer::singleShot(0, this, SLOT(update())); } QSize KateIconBorder::sizeHint() const { int w = 0; if (m_iconBorderOn) { w += iconPaneWidth + 2; } if (m_annotationBorderOn) { w += m_annotationBorderWidth + 2; } if (m_lineNumbersOn || (m_view->dynWordWrap() && m_dynWrapIndicatorsOn)) { w += lineNumberWidth() + 2; } if (m_foldingMarkersOn) { w += iconPaneWidth; } // space for the line modification system border if (m_view->config()->lineModification()) { w += 3; } // two pixel space w += 2; return QSize(w, 0); } // This function (re)calculates the maximum width of any of the digit characters (0 -> 9) // for graceful handling of variable-width fonts as the linenumber font. void KateIconBorder::updateFont() { const QFontMetricsF &fm = m_view->renderer()->config()->fontMetrics(); m_maxCharWidth = 0.0; // Loop to determine the widest numeric character in the current font. // 48 is ascii '0' for (int i = 48; i < 58; i++) { const qreal charWidth = ceil(fm.width(QChar(i))); m_maxCharWidth = qMax(m_maxCharWidth, charWidth); } // the icon pane scales with the font... iconPaneWidth = fm.height(); updateGeometry(); QTimer::singleShot(0, this, SLOT(update())); } int KateIconBorder::lineNumberWidth() const { // width = (number of digits + 1) * char width const int digits = (int) ceil(log10((double)(m_view->doc()->lines() + 1))); int width = m_lineNumbersOn ? (int)ceil((digits + 1) * m_maxCharWidth) : 0; if (m_view->dynWordWrap() && m_dynWrapIndicatorsOn) { // HACK: 16 == style().scrollBarExtent().width() width = qMax(16 + 4, width); if (m_cachedLNWidth != width || m_oldBackgroundColor != m_view->renderer()->config()->iconBarColor()) { int w = 16;// HACK: 16 == style().scrollBarExtent().width() style().scrollBarExtent().width(); int h = m_view->renderer()->lineHeight(); QSize newSize(w * devicePixelRatio(), h * devicePixelRatio()); if ((m_arrow.size() != newSize || m_oldBackgroundColor != m_view->renderer()->config()->iconBarColor()) && !newSize.isEmpty()) { m_arrow = QPixmap(newSize); m_arrow.setDevicePixelRatio(devicePixelRatio()); QPainter p(&m_arrow); p.fillRect(0, 0, w, h, m_view->renderer()->config()->iconBarColor()); h = m_view->renderer()->config()->fontMetrics().ascent(); p.setPen(m_view->renderer()->config()->lineNumberColor()); QPainterPath path; path.moveTo(w / 2, h / 2); path.lineTo(w / 2, 0); path.lineTo(w / 4, h / 4); path.lineTo(0, 0); path.lineTo(0, h / 2); path.lineTo(w / 2, h - 1); path.lineTo(w * 3 / 4, h - 1); path.lineTo(w - 1, h * 3 / 4); path.lineTo(w * 3 / 4, h / 2); path.lineTo(0, h / 2); p.drawPath(path); } } } return width; } void KateIconBorder::paintEvent(QPaintEvent *e) { paintBorder(e->rect().x(), e->rect().y(), e->rect().width(), e->rect().height()); } static void paintTriangle(QPainter &painter, QColor c, int xOffset, int yOffset, int width, int height, bool open) { painter.setRenderHint(QPainter::Antialiasing); qreal size = qMin(width, height); if (KColorUtils::luma(c) > 0.25) { c = KColorUtils::darken(c); } else { c = KColorUtils::shade(c, 0.1); } QPen pen; pen.setJoinStyle(Qt::RoundJoin); pen.setColor(c); pen.setWidthF(1.5); painter.setPen(pen); painter.setBrush(c); // let some border, if possible size *= 0.6; qreal halfSize = size / 2; qreal halfSizeP = halfSize * 0.6; QPointF middle(xOffset + (qreal)width / 2, yOffset + (qreal)height / 2); if (open) { QPointF points[3] = { middle + QPointF(-halfSize, -halfSizeP), middle + QPointF(halfSize, -halfSizeP), middle + QPointF(0, halfSizeP) }; painter.drawConvexPolygon(points, 3); } else { QPointF points[3] = { middle + QPointF(-halfSizeP, -halfSize), middle + QPointF(-halfSizeP, halfSize), middle + QPointF(halfSizeP, 0) }; painter.drawConvexPolygon(points, 3); } painter.setRenderHint(QPainter::Antialiasing, false); } void KateIconBorder::paintBorder(int /*x*/, int y, int /*width*/, int height) { uint h = m_view->renderer()->lineHeight(); uint startz = (y / h); uint endz = startz + 1 + (height / h); uint lineRangesSize = m_viewInternal->cache()->viewCacheLineCount(); uint currentLine = m_view->cursorPosition().line(); // center the folding boxes int m_px = (h - 11) / 2; if (m_px < 0) { m_px = 0; } int lnWidth(0); if (m_lineNumbersOn || (m_view->dynWordWrap() && m_dynWrapIndicatorsOn)) { // avoid calculating unless needed ;-) lnWidth = lineNumberWidth(); if (lnWidth != m_cachedLNWidth || m_oldBackgroundColor != m_view->renderer()->config()->iconBarColor()) { // we went from n0 ->n9 lines or vice verca // this causes an extra updateGeometry() first time the line numbers // are displayed, but sizeHint() is supposed to be const so we can't set // the cached value there. m_cachedLNWidth = lnWidth; m_oldBackgroundColor = m_view->renderer()->config()->iconBarColor(); updateGeometry(); update(); return; } } int w(this->width()); // sane value/calc only once QPainter p(this); p.setRenderHints(QPainter::TextAntialiasing); p.setFont(m_view->renderer()->config()->font()); // for line numbers KTextEditor::AnnotationModel *model = m_view->annotationModel() ? m_view->annotationModel() : m_doc->annotationModel(); for (uint z = startz; z <= endz; z++) { int y = h * z; int realLine = -1; if (z < lineRangesSize) { realLine = m_viewInternal->cache()->viewLine(z).line(); } int lnX = 0; p.fillRect(0, y, w - 5, h, m_view->renderer()->config()->iconBarColor()); p.fillRect(w - 5, y, 5, h, m_view->renderer()->config()->backgroundColor()); // icon pane if (m_iconBorderOn) { p.setPen(m_view->renderer()->config()->separatorColor()); p.setBrush(m_view->renderer()->config()->separatorColor()); p.drawLine(lnX + iconPaneWidth + 1, y, lnX + iconPaneWidth + 1, y + h); if ((realLine > -1) && (m_viewInternal->cache()->viewLine(z).startCol() == 0)) { uint mrk(m_doc->mark(realLine)); // call only once if (mrk) { for (uint bit = 0; bit < 32; bit++) { MarkInterface::MarkTypes markType = (MarkInterface::MarkTypes)(1 << bit); if (mrk & markType) { QPixmap px_mark(m_doc->markPixmap(markType)); if (!px_mark.isNull() && h > 0 && iconPaneWidth > 0) { if (iconPaneWidth < px_mark.width() || h < (uint)px_mark.height()) { px_mark = px_mark.scaled(iconPaneWidth, h, Qt::KeepAspectRatio); } // center the mark pixmap int x_px = (iconPaneWidth - px_mark.width()) / 2; if (x_px < 0) { x_px = 0; } int y_px = (h - px_mark.height()) / 2; if (y_px < 0) { y_px = 0; } p.drawPixmap(lnX + x_px, y + y_px, px_mark); } } } } } lnX += iconPaneWidth + 2; } // annotation information if (m_annotationBorderOn) { // Draw a border line between annotations and the line numbers p.setPen(m_view->renderer()->config()->lineNumberColor()); p.setBrush(m_view->renderer()->config()->lineNumberColor()); int borderWidth = m_annotationBorderWidth; p.drawLine(lnX + borderWidth + 1, y, lnX + borderWidth + 1, y + h); if ((realLine > -1) && model) { // Fetch data from the model QVariant text = model->data(realLine, Qt::DisplayRole); QVariant foreground = model->data(realLine, Qt::ForegroundRole); QVariant background = model->data(realLine, Qt::BackgroundRole); // Fill the background if (background.isValid()) { p.fillRect(lnX, y, borderWidth + 1, h, background.value()); } // Set the pen for drawing the foreground if (foreground.isValid()) { p.setPen(foreground.value()); } // Draw a border around all adjacent entries that have the same text as the currently hovered one const QVariant identifier = model->data( realLine, (Qt::ItemDataRole) KTextEditor::AnnotationModel::GroupIdentifierRole ); if( m_hoveredAnnotationGroupIdentifier == identifier.toString() ) { p.drawLine(lnX, y, lnX, y + h); p.drawLine(lnX + borderWidth, y, lnX + borderWidth, y + h); QVariant beforeText = model->data(realLine - 1, Qt::DisplayRole); QVariant afterText = model->data(realLine + 1, Qt::DisplayRole); if (((beforeText.isValid() && beforeText.canConvert() && text.isValid() && text.canConvert() && beforeText.toString() != text.toString()) || realLine == 0) && m_viewInternal->cache()->viewLine(z).viewLine() == 0) { p.drawLine(lnX + 1, y, lnX + borderWidth, y); } if (((afterText.isValid() && afterText.canConvert() && text.isValid() && text.canConvert() && afterText.toString() != text.toString()) || realLine == m_view->doc()->lines() - 1) && m_viewInternal->cache()->viewLine(z).viewLine() == m_viewInternal->cache()->viewLineCount(realLine) - 1) { p.drawLine(lnX + 1, y + h - 1, lnX + borderWidth, y + h - 1); } } if (foreground.isValid()) { QPen pen = p.pen(); pen.setWidth(1); p.setPen(pen); } // Now draw the normal text if (text.isValid() && text.canConvert() && (m_viewInternal->cache()->viewLine(z).startCol() == 0)) { p.drawText(lnX + 3, y, borderWidth - 3, h, Qt::AlignLeft | Qt::AlignVCenter, text.toString()); } } // adjust current X position and reset the pen and brush lnX += borderWidth + 2; } // line number if (m_lineNumbersOn || (m_view->dynWordWrap() && m_dynWrapIndicatorsOn)) { if (realLine > -1) { int distanceToCurrent = abs(realLine - static_cast(currentLine)); QColor color; if (distanceToCurrent == 0) { color = m_view->renderer()->config()->currentLineNumberColor(); } else { color = m_view->renderer()->config()->lineNumberColor(); } p.setPen(color); p.setBrush(color); if (m_viewInternal->cache()->viewLine(z).startCol() == 0) { if (m_relLineNumbersOn) { if (distanceToCurrent == 0) { p.drawText(lnX + m_maxCharWidth / 2, y, lnWidth - m_maxCharWidth, h, Qt::TextDontClip|Qt::AlignLeft|Qt::AlignVCenter, QString::number(realLine + 1)); } else { p.drawText(lnX + m_maxCharWidth / 2, y, lnWidth - m_maxCharWidth, h, Qt::TextDontClip|Qt::AlignRight|Qt::AlignVCenter, QString::number(distanceToCurrent)); } if (m_updateRelLineNumbers) { m_updateRelLineNumbers = false; update(); } } else if (m_lineNumbersOn) { p.drawText(lnX + m_maxCharWidth / 2, y, lnWidth - m_maxCharWidth, h, Qt::TextDontClip | Qt::AlignRight | Qt::AlignVCenter, QString::number(realLine + 1)); } } else if (m_view->dynWordWrap() && m_dynWrapIndicatorsOn) { p.drawPixmap(lnX + lnWidth - (m_arrow.width() / m_arrow.devicePixelRatio()) - 2, y, m_arrow); } } lnX += lnWidth + 2; } // folding markers if (m_foldingMarkersOn) { // first icon border background p.fillRect(lnX, y, iconPaneWidth, h, m_view->renderer()->config()->iconBarColor()); // possible additional folding highlighting if ((realLine >= 0) && m_foldingRange && m_foldingRange->overlapsLine(realLine)) { p.save(); // use linear gradient as brush QLinearGradient g(lnX, y, lnX + iconPaneWidth, y); const QColor foldingColor(m_view->renderer()->config()->foldingColor()); g.setColorAt(0, foldingColor); g.setColorAt(0.3, foldingColor.lighter(110)); g.setColorAt(1, foldingColor); p.setBrush(g); p.setPen(foldingColor); p.setClipRect(lnX, y, iconPaneWidth, h); p.setRenderHint(QPainter::Antialiasing); const qreal r = 4.0; if (m_foldingRange->start().line() == realLine && m_viewInternal->cache()->viewLine(z).viewLine() == 0) { p.drawRect(lnX, y, iconPaneWidth, h + r); } else if (m_foldingRange->end().line() == realLine && m_viewInternal->cache()->viewLine(z).viewLine() == m_viewInternal->cache()->viewLineCount(realLine) - 1) { p.drawRect(lnX, y - r, iconPaneWidth, h + r); } else { p.drawRect(lnX, y - r, iconPaneWidth, h + 2 * r); } p.restore(); } if ((realLine >= 0) && (m_viewInternal->cache()->viewLine(z).startCol() == 0)) { QVector > startingRanges = m_view->textFolding().foldingRangesStartingOnLine(realLine); bool anyFolded = false; for (int i = 0; i < startingRanges.size(); ++i) if (startingRanges[i].second & Kate::TextFolding::Folded) { anyFolded = true; } Kate::TextLine tl = m_doc->kateTextLine(realLine); if (!startingRanges.isEmpty() || tl->markedAsFoldingStart()) { if (anyFolded) { paintTriangle(p, m_view->renderer()->config()->foldingColor(), lnX, y, iconPaneWidth, h, false); } else { paintTriangle(p, m_view->renderer()->config()->foldingColor(), lnX, y, iconPaneWidth, h, true); } } } lnX += iconPaneWidth; } // modified line system if (m_view->config()->lineModification() && realLine > -1 && !m_doc->url().isEmpty()) { // one pixel space ++lnX; Kate::TextLine tl = m_doc->plainKateTextLine(realLine); if (tl->markedAsModified()) { p.fillRect(lnX, y, 3, h, m_view->renderer()->config()->modifiedLineColor()); } if (tl->markedAsSavedOnDisk()) { p.fillRect(lnX, y, 3, h, m_view->renderer()->config()->savedLineColor()); } } } } KateIconBorder::BorderArea KateIconBorder::positionToArea(const QPoint &p) const { // see KateIconBorder::sizeHint() for pixel spacings int x = 0; if (m_iconBorderOn) { x += iconPaneWidth; if (p.x() <= x) { return IconBorder; } x += 2; } if (this->m_annotationBorderOn) { x += m_annotationBorderWidth; if (p.x() <= x) { return AnnotationBorder; } x += 2; } if (m_lineNumbersOn || m_dynWrapIndicators) { x += lineNumberWidth(); if (p.x() <= x) { return LineNumbers; } x += 2; } if (m_foldingMarkersOn) { x += iconPaneWidth; if (p.x() <= x) { return FoldingMarkers; } } if (m_view->config()->lineModification()) { x += 3 + 2; if (p.x() <= x) { return ModificationBorder; } } return None; } void KateIconBorder::mousePressEvent(QMouseEvent *e) { const KateTextLayout &t = m_viewInternal->yToKateTextLayout(e->y()); if (t.isValid()) { m_lastClickedLine = t.line(); const auto area = positionToArea(e->pos()); // IconBorder and AnnotationBorder have their own behavior; don't forward to view if (area != IconBorder && area != AnnotationBorder) { const auto pos = QPoint(0, e->y()); if (area == LineNumbers && e->button() == Qt::LeftButton && !(e->modifiers() & Qt::ShiftModifier)) { // setup view so the following mousePressEvent will select the line m_viewInternal->beginSelectLine(pos); } QMouseEvent forward(QEvent::MouseButtonPress, pos, e->button(), e->buttons(), e->modifiers()); m_viewInternal->mousePressEvent(&forward); } return e->accept(); } QWidget::mousePressEvent(e); } void KateIconBorder::showDelayedBlock(int line) { // save the line over which the mouse hovers // either we start the timer for delay, or we show the block immediately // if the moving range already exists m_nextHighlightBlock = line; if (!m_foldingRange) { if (!m_delayFoldingHlTimer.isActive()) { m_delayFoldingHlTimer.start(); } } else { showBlock(); } } void KateIconBorder::showBlock() { if (m_nextHighlightBlock == m_currentBlockLine) { return; } m_currentBlockLine = m_nextHighlightBlock; if (m_currentBlockLine >= m_doc->buffer().lines()) { return; } /** * compute to which folding range we belong * FIXME: optimize + perhaps have some better threshold or use timers! */ KTextEditor::Range newRange = KTextEditor::Range::invalid(); for (int line = m_currentBlockLine; line >= qMax(0, m_currentBlockLine - 1024); --line) { /** * try if we have folding range from that line, should be fast per call */ KTextEditor::Range foldingRange = m_doc->buffer().computeFoldingRangeForStartLine(line); if (!foldingRange.isValid()) { continue; } /** * does the range reach us? */ if (foldingRange.overlapsLine(m_currentBlockLine)) { newRange = foldingRange; break; } } if (newRange.isValid() && m_foldingRange && *m_foldingRange == newRange) { // new range equals the old one, nothing to do. return; } else { // the ranges differ, delete the old, if it exists delete m_foldingRange; m_foldingRange = nullptr; } if (newRange.isValid()) { //qCDebug(LOG_KTE) << "new folding hl-range:" << newRange; m_foldingRange = m_doc->newMovingRange(newRange, KTextEditor::MovingRange::ExpandRight); KTextEditor::Attribute::Ptr attr(new KTextEditor::Attribute()); /** * create highlighting color with alpha for the range! */ QColor result = m_view->renderer()->config()->foldingColor(); result.setAlphaF(0.5); attr->setBackground(QBrush(result)); m_foldingRange->setView(m_view); // use z depth defined in moving ranges interface m_foldingRange->setZDepth(-100.0); m_foldingRange->setAttribute(attr); } // show text preview, if a folded region starts here bool foldUnderMouse = false; if (m_foldingRange && m_view->config()->foldingPreview()) { const QPoint globalPos = QCursor::pos(); const QPoint pos = mapFromGlobal(globalPos); const KateTextLayout &t = m_view->m_viewInternal->yToKateTextLayout(pos.y()); if (t.isValid() && positionToArea(pos) == FoldingMarkers) { const int realLine = t.line(); foldUnderMouse = !m_view->textFolding().isLineVisible(realLine + 1); if (foldUnderMouse) { if (!m_foldingPreview) { m_foldingPreview = new KateTextPreview(m_view); m_foldingPreview->setAttribute(Qt::WA_ShowWithoutActivating); m_foldingPreview->setFrameStyle(QFrame::StyledPanel); // event filter to catch application WindowDeactivate event, to hide the preview window // qApp->installEventFilter(this); } // TODO: use KateViewInternal::maxLen() somehow to compute proper width for amount of lines to display // try using the end line of the range for proper popup height const int lineCount = qMin(m_foldingRange->numberOfLines() + 1, (height() - pos.y()) / m_view->renderer()->lineHeight()); m_foldingPreview->resize(m_view->width() / 2, lineCount * m_view->renderer()->lineHeight() + 2 * m_foldingPreview->frameWidth()); const int xGlobal = mapToGlobal(QPoint(width(), 0)).x(); const int yGlobal = m_view->mapToGlobal(m_view->cursorToCoordinate(KTextEditor::Cursor(realLine, 0))).y(); m_foldingPreview->move(QPoint(xGlobal, yGlobal) - m_foldingPreview->contentsRect().topLeft()); m_foldingPreview->setLine(realLine); m_foldingPreview->setCenterView(false); m_foldingPreview->setShowFoldedLines(true); m_foldingPreview->raise(); m_foldingPreview->show(); } } } if (!foldUnderMouse) { delete m_foldingPreview; } /** * repaint */ repaint(); } void KateIconBorder::hideBlock() { if (m_delayFoldingHlTimer.isActive()) { m_delayFoldingHlTimer.stop(); } m_nextHighlightBlock = -2; m_currentBlockLine = -1; delete m_foldingRange; m_foldingRange = nullptr; delete m_foldingPreview; } void KateIconBorder::leaveEvent(QEvent *event) { hideBlock(); removeAnnotationHovering(); QWidget::leaveEvent(event); } void KateIconBorder::mouseMoveEvent(QMouseEvent *e) { const KateTextLayout &t = m_viewInternal->yToKateTextLayout(e->y()); if (t.isValid()) { if (positionToArea(e->pos()) == FoldingMarkers) { showDelayedBlock(t.line()); } else { hideBlock(); } if (positionToArea(e->pos()) == AnnotationBorder) { KTextEditor::AnnotationModel *model = m_view->annotationModel() ? m_view->annotationModel() : m_doc->annotationModel(); if (model) { m_hoveredAnnotationGroupIdentifier = model->data( t.line(), (Qt::ItemDataRole) KTextEditor::AnnotationModel::GroupIdentifierRole ).toString(); showAnnotationTooltip(t.line(), e->globalPos()); QTimer::singleShot(0, this, SLOT(update())); } } else { if (positionToArea(e->pos()) == IconBorder) { m_doc->requestMarkTooltip(t.line(), e->globalPos()); } m_hoveredAnnotationGroupIdentifier.clear(); hideAnnotationTooltip(); QTimer::singleShot(0, this, SLOT(update())); } if (positionToArea(e->pos()) != IconBorder) { QPoint p = m_viewInternal->mapFromGlobal(e->globalPos()); QMouseEvent forward(QEvent::MouseMove, p, e->button(), e->buttons(), e->modifiers()); m_viewInternal->mouseMoveEvent(&forward); } } else { // remove hovering if it's still there removeAnnotationHovering(); } QWidget::mouseMoveEvent(e); } void KateIconBorder::mouseReleaseEvent(QMouseEvent *e) { const int cursorOnLine = m_viewInternal->yToKateTextLayout(e->y()).line(); if (cursorOnLine == m_lastClickedLine && cursorOnLine >= 0 && cursorOnLine <= m_doc->lastLine()) { BorderArea area = positionToArea(e->pos()); if (area == IconBorder) { if (e->button() == Qt::LeftButton) { if (!m_doc->handleMarkClick(cursorOnLine)) { KateViewConfig *config = m_view->config(); const uint editBits = m_doc->editableMarks(); // is the default or the only editable mark const uint singleMark = qPopulationCount(editBits) > 1 ? editBits & config->defaultMarkType() : editBits; if (singleMark) { if (m_doc->mark(cursorOnLine) & singleMark) { m_doc->removeMark(cursorOnLine, singleMark); } else { m_doc->addMark(cursorOnLine, singleMark); } } else if (config->allowMarkMenu()) { showMarkMenu(cursorOnLine, QCursor::pos()); } } } else if (e->button() == Qt::RightButton) { showMarkMenu(cursorOnLine, QCursor::pos()); } } if (area == FoldingMarkers) { // ask the folding info for this line, if any folds are around! QVector > startingRanges = m_view->textFolding().foldingRangesStartingOnLine(cursorOnLine); bool anyFolded = false; for (int i = 0; i < startingRanges.size(); ++i) if (startingRanges[i].second & Kate::TextFolding::Folded) { anyFolded = true; } // fold or unfold all ranges, remember if any action happened! bool actionDone = false; for (int i = 0; i < startingRanges.size(); ++i) { actionDone = (anyFolded ? m_view->textFolding().unfoldRange(startingRanges[i].first) : m_view->textFolding().foldRange(startingRanges[i].first)) || actionDone; } // if no action done, try to fold it, create non-persistent folded range, if possible! if (!actionDone) { // either use the fold for this line or the range that is highlighted ATM if any! KTextEditor::Range foldingRange = m_view->doc()->buffer().computeFoldingRangeForStartLine(cursorOnLine); if (!foldingRange.isValid() && m_foldingRange) { foldingRange = m_foldingRange->toRange(); } m_view->textFolding().newFoldingRange(foldingRange, Kate::TextFolding::Folded); } delete m_foldingPreview; } if (area == AnnotationBorder) { const bool singleClick = style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, nullptr, this); if (e->button() == Qt::LeftButton && singleClick) { emit m_view->annotationActivated(m_view, cursorOnLine); } else if (e->button() == Qt::RightButton) { showAnnotationMenu(cursorOnLine, e->globalPos()); } } } QMouseEvent forward(QEvent::MouseButtonRelease, QPoint(0, e->y()), e->button(), e->buttons(), e->modifiers()); m_viewInternal->mouseReleaseEvent(&forward); } void KateIconBorder::mouseDoubleClickEvent(QMouseEvent *e) { int cursorOnLine = m_viewInternal->yToKateTextLayout(e->y()).line(); if (cursorOnLine == m_lastClickedLine && cursorOnLine <= m_doc->lastLine()) { BorderArea area = positionToArea(e->pos()); const bool singleClick = style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, nullptr, this); if (area == AnnotationBorder && !singleClick) { emit m_view->annotationActivated(m_view, cursorOnLine); } } QMouseEvent forward(QEvent::MouseButtonDblClick, QPoint(0, e->y()), e->button(), e->buttons(), e->modifiers()); m_viewInternal->mouseDoubleClickEvent(&forward); } void KateIconBorder::wheelEvent(QWheelEvent *e) { QCoreApplication::sendEvent(m_viewInternal, e); } void KateIconBorder::showMarkMenu(uint line, const QPoint &pos) { if (m_doc->handleMarkContextMenu(line, pos)) { return; } if (!m_view->config()->allowMarkMenu()) { return; } QMenu markMenu; QMenu selectDefaultMark; auto selectDefaultMarkActionGroup = new QActionGroup(&selectDefaultMark); QVector vec(33); int i = 1; for (uint bit = 0; bit < 32; bit++) { MarkInterface::MarkTypes markType = (MarkInterface::MarkTypes)(1 << bit); if (!(m_doc->editableMarks() & markType)) { continue; } QAction *mA; QAction *dMA; const QPixmap icon = m_doc->markPixmap(markType); if (!m_doc->markDescription(markType).isEmpty()) { mA = markMenu.addAction(icon, m_doc->markDescription(markType)); dMA = selectDefaultMark.addAction(icon, m_doc->markDescription(markType)); } else { mA = markMenu.addAction(icon, i18n("Mark Type %1", bit + 1)); dMA = selectDefaultMark.addAction(icon, i18n("Mark Type %1", bit + 1)); } selectDefaultMarkActionGroup->addAction(dMA); mA->setData(i); mA->setCheckable(true); dMA->setData(i + 100); dMA->setCheckable(true); if (m_doc->mark(line) & markType) { mA->setChecked(true); } if (markType & KateViewConfig::global()->defaultMarkType()) { dMA->setChecked(true); } vec[i++] = markType; } if (markMenu.actions().count() == 0) { return; } if (markMenu.actions().count() > 1) { markMenu.addAction(i18n("Set Default Mark Type"))->setMenu(&selectDefaultMark); } QAction *rA = markMenu.exec(pos); if (!rA) { return; } int result = rA->data().toInt(); if (result > 100) { KateViewConfig::global()->setDefaultMarkType(vec[result - 100]); } else { MarkInterface::MarkTypes markType = (MarkInterface::MarkTypes) vec[result]; if (m_doc->mark(line) & markType) { m_doc->removeMark(line, markType); } else { m_doc->addMark(line, markType); } } } void KateIconBorder::showAnnotationTooltip(int line, const QPoint &pos) { KTextEditor::AnnotationModel *model = m_view->annotationModel() ? m_view->annotationModel() : m_doc->annotationModel(); if (model) { QVariant data = model->data(line, Qt::ToolTipRole); QString tip = data.toString(); if (!tip.isEmpty()) { QToolTip::showText(pos, data.toString(), this); } } } int KateIconBorder::annotationLineWidth(int line) { KTextEditor::AnnotationModel *model = m_view->annotationModel() ? m_view->annotationModel() : m_doc->annotationModel(); if (model) { QVariant data = model->data(line, Qt::DisplayRole); return data.toString().length() * m_maxCharWidth + 8; } return 8; } void KateIconBorder::updateAnnotationLine(int line) { if (annotationLineWidth(line) > m_annotationBorderWidth) { m_annotationBorderWidth = annotationLineWidth(line); updateGeometry(); QTimer::singleShot(0, this, SLOT(update())); } } void KateIconBorder::showAnnotationMenu(int line, const QPoint &pos) { QMenu menu; QAction a(i18n("Disable Annotation Bar"), &menu); a.setIcon(QIcon::fromTheme(QStringLiteral("dialog-close"))); menu.addAction(&a); emit m_view->annotationContextMenuAboutToShow(m_view, &menu, line); if (menu.exec(pos) == &a) { m_view->setAnnotationBorderVisible(false); } } void KateIconBorder::hideAnnotationTooltip() { QToolTip::hideText(); } void KateIconBorder::updateAnnotationBorderWidth() { m_annotationBorderWidth = 6; KTextEditor::AnnotationModel *model = m_view->annotationModel() ? m_view->annotationModel() : m_doc->annotationModel(); if (model) { for (int i = 0; i < m_view->doc()->lines(); i++) { int curwidth = annotationLineWidth(i); if (curwidth > m_annotationBorderWidth) { m_annotationBorderWidth = curwidth; } } } updateGeometry(); QTimer::singleShot(0, this, SLOT(update())); } void KateIconBorder::annotationModelChanged(KTextEditor::AnnotationModel *oldmodel, KTextEditor::AnnotationModel *newmodel) { if (oldmodel) { oldmodel->disconnect(this); } if (newmodel) { connect(newmodel, SIGNAL(reset()), this, SLOT(updateAnnotationBorderWidth())); connect(newmodel, SIGNAL(lineChanged(int)), this, SLOT(updateAnnotationLine(int))); } updateAnnotationBorderWidth(); } void KateIconBorder::displayRangeChanged() { hideBlock(); removeAnnotationHovering(); } //END KateIconBorder //BEGIN KateViewEncodingAction // Acording to http://www.iana.org/assignments/ianacharset-mib // the default/unknown mib value is 2. #define MIB_DEFAULT 2 bool lessThanAction(KSelectAction *a, KSelectAction *b) { return a->text() < b->text(); } void KateViewEncodingAction::Private::init() { QList actions; q->setToolBarMode(MenuMode); int i; foreach (const QStringList &encodingsForScript, KCharsets::charsets()->encodingsByScript()) { KSelectAction *tmp = new KSelectAction(encodingsForScript.at(0), q); for (i = 1; i < encodingsForScript.size(); ++i) { tmp->addAction(encodingsForScript.at(i)); } q->connect(tmp, SIGNAL(triggered(QAction*)), q, SLOT(_k_subActionTriggered(QAction*))); //tmp->setCheckable(true); actions << tmp; } qSort(actions.begin(), actions.end(), lessThanAction); foreach (KSelectAction *action, actions) { q->addAction(action); } } void KateViewEncodingAction::Private::_k_subActionTriggered(QAction *action) { if (currentSubAction == action) { return; } currentSubAction = action; bool ok = false; int mib = q->mibForName(action->text(), &ok); if (ok) { emit q->KSelectAction::triggered(action->text()); emit q->triggered(q->codecForMib(mib)); } } KateViewEncodingAction::KateViewEncodingAction(KTextEditor::DocumentPrivate *_doc, KTextEditor::ViewPrivate *_view, const QString &text, QObject *parent, bool saveAsMode) : KSelectAction(text, parent), doc(_doc), view(_view), d(new Private(this)) , m_saveAsMode(saveAsMode) { d->init(); connect(menu(), SIGNAL(aboutToShow()), this, SLOT(slotAboutToShow())); connect(this, SIGNAL(triggered(QString)), this, SLOT(setEncoding(QString))); } KateViewEncodingAction::~KateViewEncodingAction() { delete d; } void KateViewEncodingAction::slotAboutToShow() { setCurrentCodec(doc->config()->encoding()); } void KateViewEncodingAction::setEncoding(const QString &e) { /** * in save as mode => trigger saveAs */ if (m_saveAsMode) { doc->documentSaveAsWithEncoding(e); return; } /** * else switch encoding */ doc->userSetEncodingForNextReload(); doc->setEncoding(e); view->reloadFile(); } int KateViewEncodingAction::mibForName(const QString &codecName, bool *ok) const { // FIXME logic is good but code is ugly bool success = false; int mib = MIB_DEFAULT; KCharsets *charsets = KCharsets::charsets(); QTextCodec *codec = charsets->codecForName(codecName, success); if (!success) { // Maybe we got a description name instead codec = charsets->codecForName(charsets->encodingForName(codecName), success); } if (codec) { mib = codec->mibEnum(); } if (ok) { *ok = success; } if (success) { return mib; } qCWarning(LOG_KTE) << "Invalid codec name: " << codecName; return MIB_DEFAULT; } QTextCodec *KateViewEncodingAction::codecForMib(int mib) const { if (mib == MIB_DEFAULT) { // FIXME offer to change the default codec return QTextCodec::codecForLocale(); } else { return QTextCodec::codecForMib(mib); } } QTextCodec *KateViewEncodingAction::currentCodec() const { return codecForMib(currentCodecMib()); } bool KateViewEncodingAction::setCurrentCodec(QTextCodec *codec) { disconnect(this, SIGNAL(triggered(QString)), this, SLOT(setEncoding(QString))); int i, j; for (i = 0; i < actions().size(); ++i) { if (actions().at(i)->menu()) { for (j = 0; j < actions().at(i)->menu()->actions().size(); ++j) { if (!j && !actions().at(i)->menu()->actions().at(j)->data().isNull()) { continue; } if (actions().at(i)->menu()->actions().at(j)->isSeparator()) { continue; } if (codec == KCharsets::charsets()->codecForName(actions().at(i)->menu()->actions().at(j)->text())) { d->currentSubAction = actions().at(i)->menu()->actions().at(j); d->currentSubAction->setChecked(true); } else { actions().at(i)->menu()->actions().at(j)->setChecked(false); } } } } connect(this, SIGNAL(triggered(QString)), this, SLOT(setEncoding(QString))); return true; } QString KateViewEncodingAction::currentCodecName() const { return d->currentSubAction->text(); } bool KateViewEncodingAction::setCurrentCodec(const QString &codecName) { return setCurrentCodec(KCharsets::charsets()->codecForName(codecName)); } int KateViewEncodingAction::currentCodecMib() const { return mibForName(currentCodecName()); } bool KateViewEncodingAction::setCurrentCodec(int mib) { return setCurrentCodec(codecForMib(mib)); } //END KateViewEncodingAction //BEGIN KateViewBar related classes KateViewBarWidget::KateViewBarWidget(bool addCloseButton, QWidget *parent) : QWidget(parent) , m_viewBar(nullptr) { QHBoxLayout *layout = new QHBoxLayout(this); // NOTE: Here be cosmetics. layout->setMargin(0); // hide button if (addCloseButton) { QToolButton *hideButton = new QToolButton(this); hideButton->setAutoRaise(true); hideButton->setIcon(QIcon::fromTheme(QStringLiteral("dialog-close"))); connect(hideButton, SIGNAL(clicked()), SIGNAL(hideMe())); layout->addWidget(hideButton); layout->setAlignment(hideButton, Qt::AlignLeft | Qt::AlignTop); } // widget to be used as parent for the real content m_centralWidget = new QWidget(this); layout->addWidget(m_centralWidget); setLayout(layout); setFocusProxy(m_centralWidget); } KateViewBar::KateViewBar(bool external, QWidget *parent, KTextEditor::ViewPrivate *view) : QWidget(parent), m_external(external), m_view(view), m_permanentBarWidget(nullptr) { m_layout = new QVBoxLayout(this); m_stack = new QStackedWidget(this); m_layout->addWidget(m_stack); m_layout->setMargin(0); m_stack->hide(); hide(); } void KateViewBar::addBarWidget(KateViewBarWidget *newBarWidget) { // just ignore additional adds for already existing widgets if (hasBarWidget(newBarWidget)) { return; } // add new widget, invisible... newBarWidget->hide(); m_stack->addWidget(newBarWidget); newBarWidget->setAssociatedViewBar(this); connect(newBarWidget, SIGNAL(hideMe()), SLOT(hideCurrentBarWidget())); } void KateViewBar::removeBarWidget(KateViewBarWidget *barWidget) { // remove only if there if (!hasBarWidget(barWidget)) { return; } m_stack->removeWidget(barWidget); barWidget->setAssociatedViewBar(nullptr); barWidget->hide(); disconnect(barWidget, nullptr, this, nullptr); } void KateViewBar::addPermanentBarWidget(KateViewBarWidget *barWidget) { Q_ASSERT(barWidget); Q_ASSERT(!m_permanentBarWidget); m_stack->addWidget(barWidget); m_stack->setCurrentWidget(barWidget); m_stack->show(); m_permanentBarWidget = barWidget; m_permanentBarWidget->show(); setViewBarVisible(true); } void KateViewBar::removePermanentBarWidget(KateViewBarWidget *barWidget) { Q_ASSERT(m_permanentBarWidget == barWidget); Q_UNUSED(barWidget); const bool hideBar = m_stack->currentWidget() == m_permanentBarWidget; m_permanentBarWidget->hide(); m_stack->removeWidget(m_permanentBarWidget); m_permanentBarWidget = nullptr; if (hideBar) { m_stack->hide(); setViewBarVisible(false); } } bool KateViewBar::hasPermanentWidget(KateViewBarWidget *barWidget) const { return (m_permanentBarWidget == barWidget); } void KateViewBar::showBarWidget(KateViewBarWidget *barWidget) { Q_ASSERT(barWidget != nullptr); if (barWidget != qobject_cast(m_stack->currentWidget())) { hideCurrentBarWidget(); } // raise correct widget m_stack->setCurrentWidget(barWidget); barWidget->show(); barWidget->setFocus(Qt::ShortcutFocusReason); m_stack->show(); setViewBarVisible(true); } bool KateViewBar::hasBarWidget(KateViewBarWidget *barWidget) const { return m_stack->indexOf(barWidget) != -1; } void KateViewBar::hideCurrentBarWidget() { KateViewBarWidget *current = qobject_cast(m_stack->currentWidget()); if (current) { current->closed(); } // if we have any permanent widget, make it visible again if (m_permanentBarWidget) { m_stack->setCurrentWidget (m_permanentBarWidget); } else { // else: hide the bar m_stack->hide(); setViewBarVisible(false); } m_view->setFocus(); } void KateViewBar::setViewBarVisible(bool visible) { if (m_external) { if (visible) { m_view->mainWindow()->showViewBar(m_view); } else { m_view->mainWindow()->hideViewBar(m_view); } } else { setVisible(visible); } } bool KateViewBar::hiddenOrPermanent() const { KateViewBarWidget *current = qobject_cast(m_stack->currentWidget()); if (!isVisible() || (m_permanentBarWidget && m_permanentBarWidget == current)) { return true; } return false; } void KateViewBar::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Escape) { hideCurrentBarWidget(); return; } QWidget::keyPressEvent(event); } void KateViewBar::hideEvent(QHideEvent *event) { Q_UNUSED(event); // if (!event->spontaneous()) // m_view->setFocus(); } //END KateViewBar related classes KatePasteMenu::KatePasteMenu(const QString &text, KTextEditor::ViewPrivate *view) : KActionMenu(text, view) , m_view(view) { connect(menu(), SIGNAL(aboutToShow()), this, SLOT(slotAboutToShow())); } void KatePasteMenu::slotAboutToShow() { menu()->clear(); /** * insert complete paste history */ int i = 0; Q_FOREACH (const QString &text, KTextEditor::EditorPrivate::self()->clipboardHistory()) { /** * get text for the menu ;) */ QString leftPart = (text.size() > 48) ? (text.left(48) + QLatin1String("...")) : text; QAction *a = menu()->addAction(leftPart.replace(QLatin1String("\n"), QLatin1String(" ")), this, SLOT(paste())); a->setData(i++); } } void KatePasteMenu::paste() { if (!sender()) { return; } QAction *action = qobject_cast(sender()); if (!action) { return; } // get index int i = action->data().toInt(); if (i >= KTextEditor::EditorPrivate::self()->clipboardHistory().size()) { return; } // paste m_view->paste(&KTextEditor::EditorPrivate::self()->clipboardHistory()[i]); } diff --git a/src/view/kateviewhelpers.h b/src/view/kateviewhelpers.h index 6d1e6786..66fba0fc 100644 --- a/src/view/kateviewhelpers.h +++ b/src/view/kateviewhelpers.h @@ -1,634 +1,634 @@ /* This file is part of the KDE libraries Copyright (C) 2002 John Firebaugh Copyright (C) 2001 Anders Lund Copyright (C) 2001 Christoph Cullmann This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. 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. 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. */ #ifndef __KATE_VIEW_HELPERS_H__ #define __KATE_VIEW_HELPERS_H__ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "katetextline.h" namespace KTextEditor { class DocumentPrivate; } namespace KTextEditor { class ViewPrivate; } class KateViewInternal; #define MAXFOLDINGCOLORS 16 class KateLineInfo; class KateTextPreview; namespace KTextEditor { class Command; class AnnotationModel; class MovingRange; } class QTimer; class QVBoxLayout; /** * Class to layout KTextEditor::Message%s in KateView. Only the floating * positions TopInView, CenterInView, and BottomInView are supported. * AboveView and BelowView are not supported and ASSERT. */ class KateMessageLayout : public QLayout { public: explicit KateMessageLayout (QWidget *parent); - ~KateMessageLayout() Q_DECL_OVERRIDE; + ~KateMessageLayout() override; void addWidget(QWidget *widget, KTextEditor::Message::MessagePosition pos); - int count() const Q_DECL_OVERRIDE; - QLayoutItem *itemAt(int index) const Q_DECL_OVERRIDE; - void setGeometry(const QRect &rect) Q_DECL_OVERRIDE; - QSize sizeHint() const Q_DECL_OVERRIDE; - QLayoutItem *takeAt(int index) Q_DECL_OVERRIDE; + int count() const override; + QLayoutItem *itemAt(int index) const override; + void setGeometry(const QRect &rect) override; + QSize sizeHint() const override; + QLayoutItem *takeAt(int index) override; void add(QLayoutItem *item, KTextEditor::Message::MessagePosition pos); private: - void addItem(QLayoutItem *item) Q_DECL_OVERRIDE; // never called publically + void addItem(QLayoutItem *item) override; // never called publically struct ItemWrapper { ItemWrapper(QLayoutItem *i, KTextEditor::Message::MessagePosition pos) : item(i) , position(pos) {} QLayoutItem * item = nullptr; KTextEditor::Message::MessagePosition position; }; QVector m_items; }; /** * This class is required because QScrollBar's sliderMoved() signal is * really supposed to be a sliderDragged() signal... so this way we can capture * MMB slider moves as well * * Also, it adds some useful indicators on the scrollbar. */ class KateScrollBar : public QScrollBar { Q_OBJECT public: KateScrollBar(Qt::Orientation orientation, class KateViewInternal *parent); - ~KateScrollBar() Q_DECL_OVERRIDE; - QSize sizeHint() const Q_DECL_OVERRIDE; + ~KateScrollBar() override; + QSize sizeHint() const override; inline bool showMarks() const { return m_showMarks; } inline void setShowMarks(bool b) { m_showMarks = b; update(); } inline bool showMiniMap() const { return m_showMiniMap; } void setShowMiniMap(bool b); inline bool miniMapAll() const { return m_miniMapAll; } inline void setMiniMapAll(bool b) { m_miniMapAll = b; updateGeometry(); update(); } inline bool miniMapWidth() const { return m_miniMapWidth; } inline void setMiniMapWidth(int width) { m_miniMapWidth = width; updateGeometry(); update(); } inline void queuePixmapUpdate() { m_updateTimer.start(); } Q_SIGNALS: void sliderMMBMoved(int value); protected: - void mousePressEvent(QMouseEvent *e) Q_DECL_OVERRIDE; - void mouseReleaseEvent(QMouseEvent *e) Q_DECL_OVERRIDE; - void mouseMoveEvent(QMouseEvent *e) Q_DECL_OVERRIDE; - void leaveEvent(QEvent *event) Q_DECL_OVERRIDE; - bool eventFilter(QObject *object, QEvent *event) Q_DECL_OVERRIDE; - void paintEvent(QPaintEvent *e) Q_DECL_OVERRIDE; - void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE; - void sliderChange(SliderChange change) Q_DECL_OVERRIDE; + void mousePressEvent(QMouseEvent *e) override; + void mouseReleaseEvent(QMouseEvent *e) override; + void mouseMoveEvent(QMouseEvent *e) override; + void leaveEvent(QEvent *event) override; + bool eventFilter(QObject *object, QEvent *event) override; + void paintEvent(QPaintEvent *e) override; + void resizeEvent(QResizeEvent *) override; + void sliderChange(SliderChange change) override; protected Q_SLOTS: void sliderMaybeMoved(int value); void marksChanged(); public Q_SLOTS: void updatePixmap(); private Q_SLOTS: void showTextPreview(); private: void showTextPreviewDelayed(); void hideTextPreview(); void redrawMarks(); void recomputeMarksPositions(); void miniMapPaintEvent(QPaintEvent *e); void normalPaintEvent(QPaintEvent *e); int minimapYToStdY(int y); const QColor charColor(const QVector &attributes, int &attributeIndex, const QList &decorations, const QColor &defaultColor, int x, QChar ch); bool m_middleMouseDown; bool m_leftMouseDown; KTextEditor::ViewPrivate *m_view; KTextEditor::DocumentPrivate *m_doc; class KateViewInternal *m_viewInternal; QPointer m_textPreview; QTimer m_delayTextPreviewTimer; QHash m_lines; bool m_showMarks; bool m_showMiniMap; bool m_miniMapAll; int m_miniMapWidth; QPixmap m_pixmap; int m_grooveHeight; QRect m_stdGroveRect; QRect m_mapGroveRect; QTimer m_updateTimer; QPoint m_toolTipPos; // lists of lines added/removed recently to avoid scrollbar flickering QHash m_linesAdded; int m_linesModified; static const unsigned char characterOpacity[256]; }; class KateIconBorder : public QWidget { Q_OBJECT public: KateIconBorder(KateViewInternal *internalView, QWidget *parent); - ~KateIconBorder() Q_DECL_OVERRIDE; + ~KateIconBorder() override; // VERY IMPORTANT ;) - QSize sizeHint() const Q_DECL_OVERRIDE; + QSize sizeHint() const override; void updateFont(); int lineNumberWidth() const; void setIconBorderOn(bool enable); void setLineNumbersOn(bool enable); void setRelLineNumbersOn(bool enable); void setAnnotationBorderOn(bool enable); void setDynWrapIndicators(int state); int dynWrapIndicators() const { return m_dynWrapIndicators; } bool dynWrapIndicatorsOn() const { return m_dynWrapIndicatorsOn; } void setFoldingMarkersOn(bool enable); void toggleIconBorder() { setIconBorderOn(!iconBorderOn()); } void toggleLineNumbers() { setLineNumbersOn(!lineNumbersOn()); } void toggleFoldingMarkers() { setFoldingMarkersOn(!foldingMarkersOn()); } inline bool iconBorderOn() const { return m_iconBorderOn; } inline bool lineNumbersOn() const { return m_lineNumbersOn; } inline bool viRelNumbersOn() const { return m_relLineNumbersOn; } inline bool foldingMarkersOn() const { return m_foldingMarkersOn; } inline bool annotationBorderOn() const { return m_annotationBorderOn; } void updateForCursorLineChange(); enum BorderArea { None, LineNumbers, IconBorder, FoldingMarkers, AnnotationBorder, ModificationBorder }; BorderArea positionToArea(const QPoint &) const; public Q_SLOTS: void updateAnnotationBorderWidth(); void updateAnnotationLine(int line); void annotationModelChanged(KTextEditor::AnnotationModel *oldmodel, KTextEditor::AnnotationModel *newmodel); void displayRangeChanged(); private: - void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE; + void paintEvent(QPaintEvent *) override; void paintBorder(int x, int y, int width, int height); - void mousePressEvent(QMouseEvent *) Q_DECL_OVERRIDE; - void mouseMoveEvent(QMouseEvent *) Q_DECL_OVERRIDE; - void mouseReleaseEvent(QMouseEvent *) Q_DECL_OVERRIDE; - void mouseDoubleClickEvent(QMouseEvent *) Q_DECL_OVERRIDE; - void leaveEvent(QEvent *event) Q_DECL_OVERRIDE; - void wheelEvent(QWheelEvent *e) Q_DECL_OVERRIDE; + void mousePressEvent(QMouseEvent *) override; + void mouseMoveEvent(QMouseEvent *) override; + void mouseReleaseEvent(QMouseEvent *) override; + void mouseDoubleClickEvent(QMouseEvent *) override; + void leaveEvent(QEvent *event) override; + void wheelEvent(QWheelEvent *e) override; void showMarkMenu(uint line, const QPoint &pos); void showAnnotationTooltip(int line, const QPoint &pos); void hideAnnotationTooltip(); void removeAnnotationHovering(); void showAnnotationMenu(int line, const QPoint &pos); int annotationLineWidth(int line); KTextEditor::ViewPrivate *m_view; KTextEditor::DocumentPrivate *m_doc; KateViewInternal *m_viewInternal; bool m_iconBorderOn: 1; bool m_lineNumbersOn: 1; bool m_relLineNumbersOn:1; bool m_updateRelLineNumbers:1; bool m_foldingMarkersOn: 1; bool m_dynWrapIndicatorsOn: 1; bool m_annotationBorderOn: 1; int m_dynWrapIndicators; int m_lastClickedLine; int m_cachedLNWidth; qreal m_maxCharWidth; int iconPaneWidth; int m_annotationBorderWidth; mutable QPixmap m_arrow; mutable QColor m_oldBackgroundColor; QPointer m_foldingPreview; KTextEditor::MovingRange *m_foldingRange; int m_nextHighlightBlock; int m_currentBlockLine; QTimer m_delayFoldingHlTimer; void showDelayedBlock(int line); void hideBlock(); private Q_SLOTS: void showBlock(); private: QString m_hoveredAnnotationGroupIdentifier; void initializeFoldingColors(); }; class KateViewEncodingAction: public KSelectAction { Q_OBJECT Q_PROPERTY(QString codecName READ currentCodecName WRITE setCurrentCodec) Q_PROPERTY(int codecMib READ currentCodecMib) public: KateViewEncodingAction(KTextEditor::DocumentPrivate *_doc, KTextEditor::ViewPrivate *_view, const QString &text, QObject *parent, bool saveAsMode = false); ~KateViewEncodingAction(); int mibForName(const QString &codecName, bool *ok = nullptr) const; QTextCodec *codecForMib(int mib) const; QTextCodec *currentCodec() const; bool setCurrentCodec(QTextCodec *codec); QString currentCodecName() const; bool setCurrentCodec(const QString &codecName); int currentCodecMib() const; bool setCurrentCodec(int mib); Q_SIGNALS: /** * Specific (proper) codec was selected */ void triggered(QTextCodec *codec); private: KTextEditor::DocumentPrivate *doc; KTextEditor::ViewPrivate *view; class Private { public: Private(KateViewEncodingAction *parent) : q(parent), currentSubAction(nullptr) { } void init(); void _k_subActionTriggered(QAction *); KateViewEncodingAction *q; QAction *currentSubAction; }; Private *const d; Q_PRIVATE_SLOT(d, void _k_subActionTriggered(QAction *)) const bool m_saveAsMode; private Q_SLOTS: void setEncoding(const QString &e); void slotAboutToShow(); }; class KateViewBar; class KateViewBarWidget : public QWidget { Q_OBJECT friend class KateViewBar; public: explicit KateViewBarWidget(bool addCloseButton, QWidget *parent = nullptr); virtual void closed() {} /// returns the currently associated KateViewBar and 0, if it is not associated KateViewBar *viewBar() { return m_viewBar; } protected: /** * @return widget that should be used to add controls to bar widget */ QWidget *centralWidget() { return m_centralWidget; } Q_SIGNALS: void hideMe(); // for friend class KateViewBar private: void setAssociatedViewBar(KateViewBar *bar) { m_viewBar = bar; } private: QWidget *m_centralWidget; KateViewBar *m_viewBar; // 0-pointer, if not added to a view bar }; class KateViewBar : public QWidget { Q_OBJECT public: KateViewBar(bool external, QWidget *parent, KTextEditor::ViewPrivate *view); /** * Adds a widget to this viewbar. * Widget is initially invisible, you should call showBarWidget, to show it. * Several widgets can be added to the bar, but only one can be visible */ void addBarWidget(KateViewBarWidget *newBarWidget); /** * Removes a widget from this viewbar. * Removing a widget makes sense if it takes a lot of space vertically, * because we use a QStackedWidget to maintain the same height for all * widgets in the viewbar. */ void removeBarWidget(KateViewBarWidget *barWidget); /** * @return if viewbar has widget @p barWidget */ bool hasBarWidget(KateViewBarWidget *barWidget) const; /** * Shows barWidget that was previously added with addBarWidget. * @see hideCurrentBarWidget */ void showBarWidget(KateViewBarWidget *barWidget); /** * Adds widget that will be always shown in the viewbar. * After adding permanent widget viewbar is immediately shown. * ViewBar with permanent widget won't hide itself * until permanent widget is removed. * OTOH showing/hiding regular barWidgets will work as usual * (they will be shown above permanent widget) * * If permanent widget already exists, asserts! */ void addPermanentBarWidget(KateViewBarWidget *barWidget); /** * Removes permanent bar widget from viewbar. * If no other viewbar widgets are shown, viewbar gets hidden. * * barWidget is not deleted, caller must do it if it wishes */ void removePermanentBarWidget(KateViewBarWidget *barWidget); /** * @return if viewbar has permanent widget @p barWidget */ bool hasPermanentWidget(KateViewBarWidget *barWidget) const; /** * @return true if the KateViewBar is hidden or displays a permanentBarWidget */ bool hiddenOrPermanent() const; public Q_SLOTS: /** * Hides currently shown bar widget */ void hideCurrentBarWidget(); protected: - void keyPressEvent(QKeyEvent *event) Q_DECL_OVERRIDE; - void hideEvent(QHideEvent *event) Q_DECL_OVERRIDE; + void keyPressEvent(QKeyEvent *event) override; + void hideEvent(QHideEvent *event) override; private: /** * Shows or hides whole viewbar */ void setViewBarVisible(bool visible); bool m_external; private: KTextEditor::ViewPrivate *m_view; QStackedWidget *m_stack; KateViewBarWidget *m_permanentBarWidget; QVBoxLayout *m_layout; }; class KTEXTEDITOR_EXPORT KateCommandLineBar : public KateViewBarWidget { Q_OBJECT public: explicit KateCommandLineBar(KTextEditor::ViewPrivate *view, QWidget *parent = nullptr); ~KateCommandLineBar(); void setText(const QString &text, bool selected = true); void execute(const QString &text); public Q_SLOTS: void showHelpPage(); private: class KateCmdLineEdit *m_lineEdit; }; class KateCmdLineEdit : public KLineEdit { Q_OBJECT public: KateCmdLineEdit(KateCommandLineBar *bar, KTextEditor::ViewPrivate *view); - bool event(QEvent *e) Q_DECL_OVERRIDE; + bool event(QEvent *e) override; - void hideEvent(QHideEvent *e) Q_DECL_OVERRIDE; + void hideEvent(QHideEvent *e) override; Q_SIGNALS: void hideRequested(); public Q_SLOTS: void slotReturnPressed(const QString &cmd); private Q_SLOTS: void hideLineEdit(); protected: - void focusInEvent(QFocusEvent *ev) Q_DECL_OVERRIDE; - void keyPressEvent(QKeyEvent *ev) Q_DECL_OVERRIDE; + void focusInEvent(QFocusEvent *ev) override; + void keyPressEvent(QKeyEvent *ev) override; private: /** * Parse an expression denoting a position in the document. * Return the position as an integer. * Examples of expressions are "10" (the 10th line), * "$" (the last line), "." (the current line), * "'a" (the mark 'a), "/foo/" (a forwards search for "foo"), * and "?bar?" (a backwards search for "bar"). * @param string the expression to parse * @return the position, an integer */ int calculatePosition(QString string); void fromHistory(bool up); QString helptext(const QPoint &) const; KTextEditor::ViewPrivate *m_view; KateCommandLineBar *m_bar; bool m_msgMode; QString m_oldText; uint m_histpos; ///< position in the history uint m_cmdend; ///< the point where a command ends in the text, if we have a valid one. KTextEditor::Command *m_command; ///< For completing flags/args and interactiveness class KateCmdLnWhatsThis *m_help; QTimer *m_hideTimer; }; class KatePasteMenu : public KActionMenu { Q_OBJECT public: KatePasteMenu(const QString &text, KTextEditor::ViewPrivate *view); private: KTextEditor::ViewPrivate *m_view; private Q_SLOTS: void slotAboutToShow(); void paste(); }; #endif diff --git a/src/view/kateviewinternal.cpp b/src/view/kateviewinternal.cpp index 607ca374..5d8a6a18 100644 --- a/src/view/kateviewinternal.cpp +++ b/src/view/kateviewinternal.cpp @@ -1,3845 +1,3845 @@ /* This file is part of the KDE libraries Copyright (C) 2002 John Firebaugh Copyright (C) 2002 Joseph Wenninger Copyright (C) 2002,2003 Christoph Cullmann Copyright (C) 2002-2007 Hamish Rodda Copyright (C) 2003 Anakim Border Copyright (C) 2007 Mirko Stocker Copyright (C) 2007 Matthew Woehlke Copyright (C) 2008 Erlend Hamberg Based on: KWriteView : Copyright (C) 1999 Jochen Wilhelmy This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. 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. 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. */ #include "kateviewinternal.h" #include "kateview.h" #include "kateviewhelpers.h" #include "katehighlight.h" #include "katebuffer.h" #include "katerenderer.h" #include "kateconfig.h" #include "katelayoutcache.h" #include "katecompletionwidget.h" #include "spellcheck/spellingmenu.h" #include "kateviewaccessible.h" #include "katetextanimation.h" #include "katemessagewidget.h" #include "kateglobal.h" #include "kateabstractinputmodefactory.h" #include "kateabstractinputmode.h" #include "katepartdebug.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include static const bool debugPainting = false; class ZoomEventFilter { public: ZoomEventFilter() = default; bool detectZoomingEvent(QWheelEvent *e, Qt::KeyboardModifiers modifier = Qt::ControlModifier) { Qt::KeyboardModifiers modState = e->modifiers(); if (modState == modifier) { if (m_lastWheelEvent.isValid()) { const qint64 deltaT = m_lastWheelEvent.elapsed(); // Pressing the specified modifier key within 200ms of the previous "unmodified" // wheelevent is not allowed to toggle on text zooming if (m_lastWheelEventUnmodified && deltaT < 200) { m_ignoreZoom = true; } else if (deltaT > 1000) { // the protection is kept active for 1s after the last wheel event // TODO: this value should be tuned, preferrably by someone using // Ctrl+Wheel zooming frequently. m_ignoreZoom = false; } } else { // we can't say anything and have to assume there's nothing // accidental to the modifier being pressed. m_ignoreZoom = false; } m_lastWheelEventUnmodified = false; if (m_ignoreZoom) { // unset the modifier so the view scrollbars can handle the scroll // event and produce normal, not accelerated scrolling modState &= ~modifier; e->setModifiers(modState); } } else { // state is reset after any wheel event without the zoom modifier m_lastWheelEventUnmodified = true; m_ignoreZoom = false; } m_lastWheelEvent.start(); // inform the caller whether this event is allowed to trigger text zooming. return !m_ignoreZoom && modState == modifier; } protected: QElapsedTimer m_lastWheelEvent; bool m_ignoreZoom = false; bool m_lastWheelEventUnmodified = false; }; KateViewInternal::KateViewInternal(KTextEditor::ViewPrivate *view) : QWidget(view) , editSessionNumber(0) , editIsRunning(false) , m_view(view) , m_cursor(doc()->buffer(), KTextEditor::Cursor(0, 0), Kate::TextCursor::MoveOnInsert) , m_mouse() , m_possibleTripleClick(false) , m_completionItemExpanded(false) , m_bm(doc()->newMovingRange(KTextEditor::Range::invalid(), KTextEditor::MovingRange::DoNotExpand)) , m_bmStart(doc()->newMovingRange(KTextEditor::Range::invalid(), KTextEditor::MovingRange::DoNotExpand)) , m_bmEnd(doc()->newMovingRange(KTextEditor::Range::invalid(), KTextEditor::MovingRange::DoNotExpand)) , m_bmLastFlashPos(doc()->newMovingCursor(KTextEditor::Cursor::invalid())) , m_dummy(nullptr) // stay on cursor will avoid that the view scroll around on press return at beginning , m_startPos(doc()->buffer(), KTextEditor::Cursor(0, 0), Kate::TextCursor::StayOnInsert) , m_visibleLineCount(0) , m_madeVisible(false) , m_shiftKeyPressed(false) , m_autoCenterLines(0) , m_minLinesVisible(0) , m_selChangedByUser(false) , m_selectAnchor(-1, -1) , m_selectionMode(Default) , m_layoutCache(new KateLayoutCache(renderer(), this)) , m_preserveX(false) , m_preservedX(0) , m_cachedMaxStartPos(-1, -1) , m_dragScrollTimer(this) , m_scrollTimer(this) , m_cursorTimer(this) , m_textHintTimer(this) , m_textHintDelay(500) , m_textHintPos(-1, -1) , m_imPreeditRange(nullptr) { QList factories = KTextEditor::EditorPrivate::self()->inputModeFactories(); Q_FOREACH(KateAbstractInputModeFactory *factory, factories) { KateAbstractInputMode *m = factory->createInputMode(this); m_inputModes.insert(m->viewInputMode(), m); } m_currentInputMode = m_inputModes[KTextEditor::View::NormalInputMode]; // TODO: twisted, but needed setMinimumSize(0, 0); setAttribute(Qt::WA_OpaquePaintEvent); setAttribute(Qt::WA_InputMethodEnabled); // invalidate m_selectionCached.start(), or keyb selection is screwed initially m_selectionCached = KTextEditor::Range::invalid(); // bracket markers are only for this view and should not be printed m_bm->setView(m_view); m_bmStart->setView(m_view); m_bmEnd->setView(m_view); m_bm->setAttributeOnlyForViews(true); m_bmStart->setAttributeOnlyForViews(true); m_bmEnd->setAttributeOnlyForViews(true); // use z depth defined in moving ranges interface m_bm->setZDepth(-1000.0); m_bmStart->setZDepth(-1000.0); m_bmEnd->setZDepth(-1000.0); // update mark attributes updateBracketMarkAttributes(); // // scrollbar for lines // m_lineScroll = new KateScrollBar(Qt::Vertical, this); m_lineScroll->show(); m_lineScroll->setTracking(true); m_lineScroll->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); // Hijack the line scroller's controls, so we can scroll nicely for word-wrap connect(m_lineScroll, SIGNAL(actionTriggered(int)), SLOT(scrollAction(int))); connect(m_lineScroll, SIGNAL(sliderMoved(int)), SLOT(scrollLines(int))); connect(m_lineScroll, SIGNAL(sliderMMBMoved(int)), SLOT(scrollLines(int))); connect(m_lineScroll, SIGNAL(valueChanged(int)), SLOT(scrollLines(int))); // // scrollbar for columns // m_columnScroll = new QScrollBar(Qt::Horizontal, m_view); if (m_view->dynWordWrap()) { m_columnScroll->hide(); } else { m_columnScroll->show(); } m_columnScroll->setTracking(true); m_startX = 0; connect(m_columnScroll, SIGNAL(valueChanged(int)), SLOT(scrollColumns(int))); // bottom corner box m_dummy = new QWidget(m_view); m_dummy->setFixedSize(m_lineScroll->width(), m_columnScroll->sizeHint().height()); m_dummy->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); if (m_view->dynWordWrap()) { m_dummy->hide(); } else { m_dummy->show(); } cache()->setWrap(m_view->dynWordWrap()); // // iconborder ;) // m_leftBorder = new KateIconBorder(this, m_view); m_leftBorder->show(); // update view if folding ranges change connect(&m_view->textFolding(), SIGNAL(foldingRangesChanged()), SLOT(slotRegionVisibilityChanged())); m_displayCursor.setPosition(0, 0); setAcceptDrops(true); m_zoomEventFilter = new ZoomEventFilter(); // event filter installEventFilter(this); // set initial cursor m_mouseCursor = Qt::IBeamCursor; setCursor(m_mouseCursor); // call mouseMoveEvent also if no mouse button is pressed setMouseTracking(true); m_dragInfo.state = diNone; // timers connect(&m_dragScrollTimer, SIGNAL(timeout()), this, SLOT(doDragScroll())); connect(&m_scrollTimer, SIGNAL(timeout()), this, SLOT(scrollTimeout())); connect(&m_cursorTimer, SIGNAL(timeout()), this, SLOT(cursorTimeout())); connect(&m_textHintTimer, SIGNAL(timeout()), this, SLOT(textHintTimeout())); // selection changed to set anchor connect(m_view, SIGNAL(selectionChanged(KTextEditor::View*)), this, SLOT(viewSelectionChanged())); #ifndef QT_NO_ACCESSIBILITY QAccessible::installFactory(accessibleInterfaceFactory); #endif connect(doc(), &KTextEditor::DocumentPrivate::textInserted, this, &KateViewInternal::documentTextInserted); connect(doc(), &KTextEditor::DocumentPrivate::textRemoved, this, &KateViewInternal::documentTextRemoved); // update is called in KTextEditor::ViewPrivate, after construction and layout is over // but before any other kateviewinternal call } KateViewInternal::~KateViewInternal() { // delete text animation object here, otherwise it updates the view in its destructor delete m_textAnimation; #ifndef QT_NO_ACCESSIBILITY QAccessible::removeFactory(accessibleInterfaceFactory); #endif // kill preedit ranges delete m_imPreeditRange; qDeleteAll(m_imPreeditRangeChildren); qDeleteAll(m_inputModes); // delete bracket markers delete m_bm; delete m_bmStart; delete m_bmEnd; delete m_zoomEventFilter; } void KateViewInternal::prepareForDynWrapChange() { // Which is the current view line? m_wrapChangeViewLine = cache()->displayViewLine(m_displayCursor, true); } void KateViewInternal::dynWrapChanged() { m_dummy->setFixedSize(m_lineScroll->width(), m_columnScroll->sizeHint().height()); if (m_view->dynWordWrap()) { m_columnScroll->hide(); m_dummy->hide(); } else { // column scrollbar + bottom corner box m_columnScroll->show(); m_dummy->show(); } cache()->setWrap(m_view->dynWordWrap()); updateView(); if (m_view->dynWordWrap()) { scrollColumns(0); } // Determine where the cursor should be to get the cursor on the same view line if (m_wrapChangeViewLine != -1) { KTextEditor::Cursor newStart = viewLineOffset(m_displayCursor, -m_wrapChangeViewLine); makeVisible(newStart, newStart.column(), true); } else { update(); } } KTextEditor::Cursor KateViewInternal::endPos() const { // Hrm, no lines laid out at all?? if (!cache()->viewCacheLineCount()) { return KTextEditor::Cursor(); } for (int i = qMin(linesDisplayed() - 1, cache()->viewCacheLineCount() - 1); i >= 0; i--) { const KateTextLayout &thisLine = cache()->viewLine(i); if (thisLine.line() == -1) { continue; } if (thisLine.virtualLine() >= m_view->textFolding().visibleLines()) { // Cache is too out of date return KTextEditor::Cursor(m_view->textFolding().visibleLines() - 1, doc()->lineLength(m_view->textFolding().visibleLineToLine(m_view->textFolding().visibleLines() - 1))); } return KTextEditor::Cursor(thisLine.virtualLine(), thisLine.wrap() ? thisLine.endCol() - 1 : thisLine.endCol()); } // can happen, if view is still invisible return KTextEditor::Cursor(); } int KateViewInternal::endLine() const { return endPos().line(); } KateTextLayout KateViewInternal::yToKateTextLayout(int y) const { if (y < 0 || y > size().height()) { return KateTextLayout::invalid(); } int range = y / renderer()->lineHeight(); // lineRanges is always bigger than 0, after the initial updateView call if (range >= 0 && range < cache()->viewCacheLineCount()) { return cache()->viewLine(range); } return KateTextLayout::invalid(); } int KateViewInternal::lineToY(int viewLine) const { return (viewLine - startLine()) * renderer()->lineHeight(); } void KateViewInternal::slotIncFontSizes(qreal step) { renderer()->increaseFontSizes(step); } void KateViewInternal::slotDecFontSizes(qreal step) { renderer()->decreaseFontSizes(step); } /** * Line is the real line number to scroll to. */ void KateViewInternal::scrollLines(int line) { KTextEditor::Cursor newPos(line, 0); scrollPos(newPos); } // This can scroll less than one true line void KateViewInternal::scrollViewLines(int offset) { KTextEditor::Cursor c = viewLineOffset(startPos(), offset); scrollPos(c); bool blocked = m_lineScroll->blockSignals(true); m_lineScroll->setValue(startLine()); m_lineScroll->blockSignals(blocked); } void KateViewInternal::scrollAction(int action) { switch (action) { case QAbstractSlider::SliderSingleStepAdd: scrollNextLine(); break; case QAbstractSlider::SliderSingleStepSub: scrollPrevLine(); break; case QAbstractSlider::SliderPageStepAdd: scrollNextPage(); break; case QAbstractSlider::SliderPageStepSub: scrollPrevPage(); break; case QAbstractSlider::SliderToMinimum: top_home(); break; case QAbstractSlider::SliderToMaximum: bottom_end(); break; } } void KateViewInternal::scrollNextPage() { scrollViewLines(qMax(linesDisplayed() - 1, 0)); } void KateViewInternal::scrollPrevPage() { scrollViewLines(-qMax(linesDisplayed() - 1, 0)); } void KateViewInternal::scrollPrevLine() { scrollViewLines(-1); } void KateViewInternal::scrollNextLine() { scrollViewLines(1); } KTextEditor::Cursor KateViewInternal::maxStartPos(bool changed) { cache()->setAcceptDirtyLayouts(true); if (m_cachedMaxStartPos.line() == -1 || changed) { KTextEditor::Cursor end(m_view->textFolding().visibleLines() - 1, doc()->lineLength(m_view->textFolding().visibleLineToLine(m_view->textFolding().visibleLines() - 1))); if (m_view->config()->scrollPastEnd()) { m_cachedMaxStartPos = viewLineOffset(end, -m_minLinesVisible); } else { m_cachedMaxStartPos = viewLineOffset(end, -(linesDisplayed() - 1)); } } cache()->setAcceptDirtyLayouts(false); return m_cachedMaxStartPos; } // c is a virtual cursor void KateViewInternal::scrollPos(KTextEditor::Cursor &c, bool force, bool calledExternally, bool emitSignals) { if (!force && ((!m_view->dynWordWrap() && c.line() == startLine()) || c == startPos())) { return; } if (c.line() < 0) { c.setLine(0); } KTextEditor::Cursor limit = maxStartPos(); if (c > limit) { c = limit; // Re-check we're not just scrolling to the same place if (!force && ((!m_view->dynWordWrap() && c.line() == startLine()) || c == startPos())) { return; } } int viewLinesScrolled = 0; // only calculate if this is really used and useful, could be wrong here, please recheck // for larger scrolls this makes 2-4 seconds difference on my xeon with dyn. word wrap on // try to get it really working ;) bool viewLinesScrolledUsable = !force && (c.line() >= startLine() - linesDisplayed() - 1) && (c.line() <= endLine() + linesDisplayed() + 1); if (viewLinesScrolledUsable) { viewLinesScrolled = cache()->displayViewLine(c); } m_startPos.setPosition(c); // set false here but reversed if we return to makeVisible m_madeVisible = false; if (viewLinesScrolledUsable) { int lines = linesDisplayed(); if (m_view->textFolding().visibleLines() < lines) { KTextEditor::Cursor end(m_view->textFolding().visibleLines() - 1, doc()->lineLength(m_view->textFolding().visibleLineToLine(m_view->textFolding().visibleLines() - 1))); lines = qMin(linesDisplayed(), cache()->displayViewLine(end) + 1); } Q_ASSERT(lines >= 0); if (!calledExternally && qAbs(viewLinesScrolled) < lines && // NOTE: on some machines we must update if the floating widget is visible // otherwise strange painting bugs may occur during scrolling... !((m_view->m_messageWidgets[KTextEditor::Message::TopInView] && m_view->m_messageWidgets[KTextEditor::Message::TopInView]->isVisible()) ||(m_view->m_messageWidgets[KTextEditor::Message::CenterInView] && m_view->m_messageWidgets[KTextEditor::Message::CenterInView]->isVisible()) ||(m_view->m_messageWidgets[KTextEditor::Message::BottomInView] && m_view->m_messageWidgets[KTextEditor::Message::BottomInView]->isVisible()) ) ) { updateView(false, viewLinesScrolled); int scrollHeight = -(viewLinesScrolled * (int)renderer()->lineHeight()); // scroll excluding child widgets (floating notifications) scroll(0, scrollHeight, rect()); m_leftBorder->scroll(0, scrollHeight); if (emitSignals) { emit m_view->verticalScrollPositionChanged(m_view, c); emit m_view->displayRangeChanged(m_view); } return; } } updateView(); update(); m_leftBorder->update(); if (emitSignals) { emit m_view->verticalScrollPositionChanged(m_view, c); emit m_view->displayRangeChanged(m_view); } } void KateViewInternal::scrollColumns(int x) { if (x < 0) { x = 0; } if (x > m_columnScroll->maximum()) { x = m_columnScroll->maximum(); } if (x == m_startX) { return; } int dx = m_startX - x; m_startX = x; if (qAbs(dx) < width()) { // scroll excluding child widgets (floating notifications) scroll(dx, 0, rect()); } else { update(); } emit m_view->horizontalScrollPositionChanged(m_view); emit m_view->displayRangeChanged(m_view); bool blocked = m_columnScroll->blockSignals(true); m_columnScroll->setValue(m_startX); m_columnScroll->blockSignals(blocked); } // If changed is true, the lines that have been set dirty have been updated. void KateViewInternal::updateView(bool changed, int viewLinesScrolled) { doUpdateView(changed, viewLinesScrolled); if (changed) { updateDirty(); } } void KateViewInternal::doUpdateView(bool changed, int viewLinesScrolled) { if (!isVisible() && !viewLinesScrolled && !changed) { return; //When this view is not visible, don't do anything } bool blocked = m_lineScroll->blockSignals(true); if (width() != cache()->viewWidth()) { cache()->setViewWidth(width()); changed = true; } /* It was observed that height() could be negative here -- when the main Kate view has 0 as size (during creation), and there frame arount KateViewInternal. In which case we'd set the view cache to 0 (or less!) lines, and start allocating huge chunks of data, later. */ int newSize = (qMax(0, height()) / renderer()->lineHeight()) + 1; cache()->updateViewCache(startPos(), newSize, viewLinesScrolled); m_visibleLineCount = newSize; KTextEditor::Cursor maxStart = maxStartPos(changed); int maxLineScrollRange = maxStart.line(); if (m_view->dynWordWrap() && maxStart.column() != 0) { maxLineScrollRange++; } m_lineScroll->setRange(0, maxLineScrollRange); m_lineScroll->setValue(startPos().line()); m_lineScroll->setSingleStep(1); m_lineScroll->setPageStep(qMax(0, height()) / renderer()->lineHeight()); m_lineScroll->blockSignals(blocked); KateViewConfig::ScrollbarMode show_scrollbars = static_cast(view()->config()->showScrollbars()); bool visible = ((show_scrollbars == KateViewConfig::AlwaysOn) || ((show_scrollbars == KateViewConfig::ShowWhenNeeded) && (maxLineScrollRange != 0))); bool visible_dummy = visible; m_lineScroll->setVisible(visible); if (!m_view->dynWordWrap()) { int max = maxLen(startLine()) - width(); if (max < 0) { max = 0; } // if we lose the ability to scroll horizontally, move view to the far-left if (max == 0) { scrollColumns(0); } blocked = m_columnScroll->blockSignals(true); // disable scrollbar m_columnScroll->setDisabled(max == 0); visible = ((show_scrollbars == KateViewConfig::AlwaysOn) || ((show_scrollbars == KateViewConfig::ShowWhenNeeded) && (max != 0))); visible_dummy &= visible; m_columnScroll->setVisible(visible); m_columnScroll->setRange(0, max + (renderer()->spaceWidth() / 2)); // Add some space for the caret at EOL m_columnScroll->setValue(m_startX); // Approximate linescroll m_columnScroll->setSingleStep(renderer()->config()->fontMetrics().width(QLatin1Char('a'))); m_columnScroll->setPageStep(width()); m_columnScroll->blockSignals(blocked); } else { visible_dummy = false; } m_dummy->setVisible(visible_dummy); } /** * this function ensures a certain location is visible on the screen. * if endCol is -1, ignore making the columns visible. */ void KateViewInternal::makeVisible(const KTextEditor::Cursor &c, int endCol, bool force, bool center, bool calledExternally) { //qCDebug(LOG_KTE) << "MakeVisible start " << startPos() << " end " << endPos() << " -> request: " << c;// , new start [" << scroll.line << "," << scroll.col << "] lines " << (linesDisplayed() - 1) << " height " << height(); // if the line is in a folded region, unfold all the way up //if ( doc()->foldingTree()->findNodeForLine( c.line )->visible ) // qCDebug(LOG_KTE)<<"line ("< endPos())) { KTextEditor::Cursor scroll = viewLineOffset(c, -int(linesDisplayed()) / 2); scrollPos(scroll, false, calledExternally); } else if (c > viewLineOffset(startPos(), linesDisplayed() - m_minLinesVisible - 1)) { KTextEditor::Cursor scroll = viewLineOffset(c, -(linesDisplayed() - m_minLinesVisible - 1)); scrollPos(scroll, false, calledExternally); } else if (c < viewLineOffset(startPos(), m_minLinesVisible)) { KTextEditor::Cursor scroll = viewLineOffset(c, -m_minLinesVisible); scrollPos(scroll, false, calledExternally); } else { // Check to see that we're not showing blank lines KTextEditor::Cursor max = maxStartPos(); if (startPos() > max) { scrollPos(max, max.column(), calledExternally); } } if (!m_view->dynWordWrap() && (endCol != -1 || m_view->wrapCursor())) { KTextEditor::Cursor rc = toRealCursor(c); int sX = renderer()->cursorToX(cache()->textLayout(rc), rc, !m_view->wrapCursor()); int sXborder = sX - 8; if (sXborder < 0) { sXborder = 0; } if (sX < m_startX) { scrollColumns(sXborder); } else if (sX > m_startX + width()) { scrollColumns(sX - width() + 8); } } m_madeVisible = !force; #ifndef QT_NO_ACCESSIBILITY // FIXME -- is this needed? // QAccessible::updateAccessibility(this, KateCursorAccessible::ChildId, QAccessible::Focus); #endif } void KateViewInternal::slotRegionVisibilityChanged() { qCDebug(LOG_KTE); cache()->clear(); m_cachedMaxStartPos.setLine(-1); KTextEditor::Cursor max = maxStartPos(); if (startPos() > max) { scrollPos(max, false, false, false /* don't emit signals! */); } // if text was folded: make sure the cursor is on a visible line qint64 foldedRangeId = -1; if (!m_view->textFolding().isLineVisible(m_cursor.line(), &foldedRangeId)) { KTextEditor::Range foldingRange = m_view->textFolding().foldingRange(foldedRangeId); Q_ASSERT(foldingRange.start().isValid()); // set cursor to start of folding region updateCursor(foldingRange.start(), true); } else { // force an update of the cursor, since otherwise the m_displayCursor // line may be below the total amount of visible lines. updateCursor(m_cursor, true); } updateView(); update(); m_leftBorder->update(); // emit signals here, scrollPos has this disabled, to ensure we do this after all stuff is updated! emit m_view->verticalScrollPositionChanged(m_view, max); emit m_view->displayRangeChanged(m_view); } void KateViewInternal::slotRegionBeginEndAddedRemoved(unsigned int) { qCDebug(LOG_KTE); // FIXME: performance problem m_leftBorder->update(); } void KateViewInternal::showEvent(QShowEvent *e) { updateView(); QWidget::showEvent(e); } int KateViewInternal::linesDisplayed() const { int h = height(); // catch zero heights, even if should not happen int fh = qMax(1, renderer()->lineHeight()); // default to 1, there is always one line around.... // too many places calc with linesDisplayed() - 1 return qMax(1, (h - (h % fh)) / fh); } QPoint KateViewInternal::cursorToCoordinate(const KTextEditor::Cursor &cursor, bool realCursor, bool includeBorder) const { if (cursor.line() >= doc()->lines()) { return QPoint(-1, -1); } int viewLine = cache()->displayViewLine(realCursor ? toVirtualCursor(cursor) : cursor, true); if (viewLine < 0 || viewLine >= cache()->viewCacheLineCount()) { return QPoint(-1, -1); } const int y = (int)viewLine * renderer()->lineHeight(); KateTextLayout layout = cache()->viewLine(viewLine); if (cursor.column() > doc()->lineLength(cursor.line())) { return QPoint(-1, -1); } int x = 0; // only set x value if we have a valid layout (bug #171027) if (layout.isValid()) { x = (int)layout.lineLayout().cursorToX(cursor.column()); } // else // qCDebug(LOG_KTE) << "Invalid Layout"; if (includeBorder) { x += m_leftBorder->width(); } x -= startX(); return QPoint(x, y); } QPoint KateViewInternal::cursorCoordinates(bool includeBorder) const { return cursorToCoordinate(m_displayCursor, false, includeBorder); } KTextEditor::Cursor KateViewInternal::findMatchingBracket() { KTextEditor::Cursor c; if (!m_bm->toRange().isValid()) { return KTextEditor::Cursor::invalid(); } Q_ASSERT(m_bmEnd->toRange().isValid()); Q_ASSERT(m_bmStart->toRange().isValid()); if (m_bmStart->toRange().contains(m_cursor) || m_bmStart->end() == m_cursor.toCursor()) { c = m_bmEnd->end(); } else if (m_bmEnd->toRange().contains(m_cursor) || m_bmEnd->end() == m_cursor.toCursor()) { c = m_bmStart->start(); } else { // should never happen: a range exists, but the cursor position is // neither at the start nor at the end... return KTextEditor::Cursor::invalid(); } return c; } void KateViewInternal::doReturn() { doc()->newLine(m_view); m_leftBorder->updateForCursorLineChange(); updateView(); } void KateViewInternal::doSmartNewline() { int ln = m_cursor.line(); Kate::TextLine line = doc()->kateTextLine(ln); int col = qMin(m_cursor.column(), line->firstChar()); if (col != -1) { while (line->length() > col && !(line->at(col).isLetterOrNumber() || line->at(col) == QLatin1Char('_')) && col < m_cursor.column()) { ++col; } } else { col = line->length(); // stay indented } doc()->editStart(); doc()->editWrapLine(ln, m_cursor.column()); doc()->insertText(KTextEditor::Cursor(ln + 1, 0), line->string(0, col)); doc()->editEnd(); updateView(); } void KateViewInternal::doDelete() { doc()->del(m_view, m_cursor); } void KateViewInternal::doBackspace() { doc()->backspace(m_view, m_cursor); } void KateViewInternal::doTabulator() { doc()->insertTab(m_view, m_cursor); } void KateViewInternal::doTranspose() { doc()->transpose(m_cursor); } void KateViewInternal::doDeletePrevWord() { doc()->editStart(); wordPrev(true); KTextEditor::Range selection = m_view->selectionRange(); m_view->removeSelectedText(); doc()->editEnd(); tagRange(selection, true); updateDirty(); } void KateViewInternal::doDeleteNextWord() { doc()->editStart(); wordNext(true); KTextEditor::Range selection = m_view->selectionRange(); m_view->removeSelectedText(); doc()->editEnd(); tagRange(selection, true); updateDirty(); } class CalculatingCursor { public: // These constructors constrain their arguments to valid positions // before only the third one did, but that leads to crashs // see bug 227449 CalculatingCursor(KateViewInternal *vi) : m_vi(vi) { makeValid(); } CalculatingCursor(KateViewInternal *vi, const KTextEditor::Cursor &c) : m_cursor(c) , m_vi(vi) { makeValid(); } CalculatingCursor(KateViewInternal *vi, int line, int col) : m_cursor(line, col) , m_vi(vi) { makeValid(); } virtual ~CalculatingCursor() { } int line() const { return m_cursor.line(); } int column() const { return m_cursor.column(); } operator KTextEditor::Cursor() const { return m_cursor; } virtual CalculatingCursor &operator+=(int n) = 0; virtual CalculatingCursor &operator-=(int n) = 0; CalculatingCursor &operator++() { return operator+=(1); } CalculatingCursor &operator--() { return operator-=(1); } void makeValid() { m_cursor.setLine(qBound(0, line(), int(doc()->lines() - 1))); if (view()->wrapCursor()) { m_cursor.setColumn(qBound(0, column(), doc()->lineLength(line()))); } else { m_cursor.setColumn(qMax(0, column())); } Q_ASSERT(valid()); } void toEdge(KateViewInternal::Bias bias) { if (bias == KateViewInternal::left) { m_cursor.setColumn(0); } else if (bias == KateViewInternal::right) { m_cursor.setColumn(doc()->lineLength(line())); } } bool atEdge() const { return atEdge(KateViewInternal::left) || atEdge(KateViewInternal::right); } bool atEdge(KateViewInternal::Bias bias) const { switch (bias) { case KateViewInternal::left: return column() == 0; case KateViewInternal::none: return atEdge(); case KateViewInternal::right: return column() >= doc()->lineLength(line()); default: Q_ASSERT(false); return false; } } protected: bool valid() const { return line() >= 0 && line() < doc()->lines() && column() >= 0 && (!view()->wrapCursor() || column() <= doc()->lineLength(line())); } KTextEditor::ViewPrivate *view() { return m_vi->m_view; } const KTextEditor::ViewPrivate *view() const { return m_vi->m_view; } KTextEditor::DocumentPrivate *doc() { return view()->doc(); } const KTextEditor::DocumentPrivate *doc() const { return view()->doc(); } KTextEditor::Cursor m_cursor; KateViewInternal *m_vi; }; class BoundedCursor : public CalculatingCursor { public: BoundedCursor(KateViewInternal *vi) : CalculatingCursor(vi) {} BoundedCursor(KateViewInternal *vi, const KTextEditor::Cursor &c) : CalculatingCursor(vi, c) {} BoundedCursor(KateViewInternal *vi, int line, int col) : CalculatingCursor(vi, line, col) {} - CalculatingCursor &operator+=(int n) Q_DECL_OVERRIDE + CalculatingCursor &operator+=(int n) override { KateLineLayoutPtr thisLine = m_vi->cache()->line(line()); if (!thisLine->isValid()) { qCWarning(LOG_KTE) << "Did not retrieve valid layout for line " << line(); return *this; } const bool wrapCursor = view()->wrapCursor(); int maxColumn = -1; if (n >= 0) { for (int i = 0; i < n; i++) { if (column() >= thisLine->length()) { if (wrapCursor) { break; } else if (view()->dynWordWrap()) { // Don't go past the edge of the screen in dynamic wrapping mode if (maxColumn == -1) { maxColumn = thisLine->length() + ((m_vi->width() - thisLine->widthOfLastLine()) / m_vi->renderer()->spaceWidth()) - 1; } if (column() >= maxColumn) { m_cursor.setColumn(maxColumn); break; } m_cursor.setColumn(column() + 1); } else { m_cursor.setColumn(column() + 1); } } else { m_cursor.setColumn(thisLine->layout()->nextCursorPosition(column())); } } } else { for (int i = 0; i > n; i--) { if (column() >= thisLine->length()) { m_cursor.setColumn(column() - 1); } else if (column() == 0) { break; } else { m_cursor.setColumn(thisLine->layout()->previousCursorPosition(column())); } } } Q_ASSERT(valid()); return *this; } - CalculatingCursor &operator-=(int n) Q_DECL_OVERRIDE + CalculatingCursor &operator-=(int n) override { return operator+=(-n); } }; class WrappingCursor : public CalculatingCursor { public: WrappingCursor(KateViewInternal *vi) : CalculatingCursor(vi) {} WrappingCursor(KateViewInternal *vi, const KTextEditor::Cursor &c) : CalculatingCursor(vi, c) {} WrappingCursor(KateViewInternal *vi, int line, int col) : CalculatingCursor(vi, line, col) {} - CalculatingCursor &operator+=(int n) Q_DECL_OVERRIDE + CalculatingCursor &operator+=(int n) override { KateLineLayoutPtr thisLine = m_vi->cache()->line(line()); if (!thisLine->isValid()) { qCWarning(LOG_KTE) << "Did not retrieve a valid layout for line " << line(); return *this; } if (n >= 0) { for (int i = 0; i < n; i++) { if (column() >= thisLine->length()) { // Have come to the end of a line if (line() >= doc()->lines() - 1) // Have come to the end of the document { break; } // Advance to the beginning of the next line m_cursor.setColumn(0); m_cursor.setLine(line() + 1); // Retrieve the next text range thisLine = m_vi->cache()->line(line()); if (!thisLine->isValid()) { qCWarning(LOG_KTE) << "Did not retrieve a valid layout for line " << line(); return *this; } continue; } m_cursor.setColumn(thisLine->layout()->nextCursorPosition(column())); } } else { for (int i = 0; i > n; i--) { if (column() == 0) { // Have come to the start of the document if (line() == 0) { break; } // Start going back to the end of the last line m_cursor.setLine(line() - 1); // Retrieve the next text range thisLine = m_vi->cache()->line(line()); if (!thisLine->isValid()) { qCWarning(LOG_KTE) << "Did not retrieve a valid layout for line " << line(); return *this; } // Finish going back to the end of the last line m_cursor.setColumn(thisLine->length()); continue; } if (column() > thisLine->length()) { m_cursor.setColumn(column() - 1); } else { m_cursor.setColumn(thisLine->layout()->previousCursorPosition(column())); } } } Q_ASSERT(valid()); return *this; } - CalculatingCursor &operator-=(int n) Q_DECL_OVERRIDE + CalculatingCursor &operator-=(int n) override { return operator+=(-n); } }; void KateViewInternal::moveChar(KateViewInternal::Bias bias, bool sel) { KTextEditor::Cursor c; if (m_view->wrapCursor()) { c = WrappingCursor(this, m_cursor) += bias; } else { c = BoundedCursor(this, m_cursor) += bias; } updateSelection(c, sel); updateCursor(c); } void KateViewInternal::cursorPrevChar(bool sel) { if (! m_view->wrapCursor() && m_cursor.column() == 0) { return; } moveChar(KateViewInternal::left, sel); } void KateViewInternal::cursorNextChar(bool sel) { moveChar(KateViewInternal::right, sel); } void KateViewInternal::wordPrev(bool sel) { WrappingCursor c(this, m_cursor); // First we skip backwards all space. // Then we look up into which category the current position falls: // 1. a "word" character // 2. a "non-word" character (except space) // 3. the beginning of the line // and skip all preceding characters that fall into this class. // The code assumes that space is never part of the word character class. KateHighlighting *h = doc()->highlight(); if (!c.atEdge(left)) { while (!c.atEdge(left) && doc()->line(c.line())[ c.column() - 1 ].isSpace()) { --c; } } if (c.atEdge(left)) { --c; } else if (h->isInWord(doc()->line(c.line())[ c.column() - 1 ])) { while (!c.atEdge(left) && h->isInWord(doc()->line(c.line())[ c.column() - 1 ])) { --c; } } else { while (!c.atEdge(left) && !h->isInWord(doc()->line(c.line())[ c.column() - 1 ]) // in order to stay symmetric to wordLeft() // we must not skip space preceding a non-word sequence && !doc()->line(c.line())[ c.column() - 1 ].isSpace()) { --c; } } updateSelection(c, sel); updateCursor(c); } void KateViewInternal::wordNext(bool sel) { WrappingCursor c(this, m_cursor); // We look up into which category the current position falls: // 1. a "word" character // 2. a "non-word" character (except space) // 3. the end of the line // and skip all following characters that fall into this class. // If the skipped characters are followed by space, we skip that too. // The code assumes that space is never part of the word character class. KateHighlighting *h = doc()->highlight(); if (c.atEdge(right)) { ++c; } else if (h->isInWord(doc()->line(c.line())[ c.column() ])) { while (!c.atEdge(right) && h->isInWord(doc()->line(c.line())[ c.column() ])) { ++c; } } else { while (!c.atEdge(right) && !h->isInWord(doc()->line(c.line())[ c.column() ]) // we must not skip space, because if that space is followed // by more non-word characters, we would skip them, too && !doc()->line(c.line())[ c.column() ].isSpace()) { ++c; } } while (!c.atEdge(right) && doc()->line(c.line())[ c.column() ].isSpace()) { ++c; } updateSelection(c, sel); updateCursor(c); } void KateViewInternal::moveEdge(KateViewInternal::Bias bias, bool sel) { BoundedCursor c(this, m_cursor); c.toEdge(bias); updateSelection(c, sel); updateCursor(c); } void KateViewInternal::home(bool sel) { if (m_view->dynWordWrap() && currentLayout().startCol()) { // Allow us to go to the real start if we're already at the start of the view line if (m_cursor.column() != currentLayout().startCol()) { KTextEditor::Cursor c = currentLayout().start(); updateSelection(c, sel); updateCursor(c); return; } } if (!doc()->config()->smartHome()) { moveEdge(left, sel); return; } Kate::TextLine l = doc()->kateTextLine(m_cursor.line()); if (!l) { return; } KTextEditor::Cursor c = m_cursor; int lc = l->firstChar(); if (lc < 0 || c.column() == lc) { c.setColumn(0); } else { c.setColumn(lc); } updateSelection(c, sel); updateCursor(c, true); } void KateViewInternal::end(bool sel) { KateTextLayout layout = currentLayout(); if (m_view->dynWordWrap() && layout.wrap()) { // Allow us to go to the real end if we're already at the end of the view line if (m_cursor.column() < layout.endCol() - 1) { KTextEditor::Cursor c(m_cursor.line(), layout.endCol() - 1); updateSelection(c, sel); updateCursor(c); return; } } if (!doc()->config()->smartHome()) { moveEdge(right, sel); return; } Kate::TextLine l = doc()->kateTextLine(m_cursor.line()); if (!l) { return; } // "Smart End", as requested in bugs #78258 and #106970 if (m_cursor.column() == doc()->lineLength(m_cursor.line())) { KTextEditor::Cursor c = m_cursor; c.setColumn(l->lastChar() + 1); updateSelection(c, sel); updateCursor(c, true); } else { moveEdge(right, sel); } } KateTextLayout KateViewInternal::currentLayout() const { return cache()->textLayout(m_cursor); } KateTextLayout KateViewInternal::previousLayout() const { int currentViewLine = cache()->viewLine(m_cursor); if (currentViewLine) { return cache()->textLayout(m_cursor.line(), currentViewLine - 1); } else { return cache()->textLayout(m_view->textFolding().visibleLineToLine(m_displayCursor.line() - 1), -1); } } KateTextLayout KateViewInternal::nextLayout() const { int currentViewLine = cache()->viewLine(m_cursor) + 1; if (currentViewLine >= cache()->line(m_cursor.line())->viewLineCount()) { currentViewLine = 0; return cache()->textLayout(m_view->textFolding().visibleLineToLine(m_displayCursor.line() + 1), currentViewLine); } else { return cache()->textLayout(m_cursor.line(), currentViewLine); } } /* * This returns the cursor which is offset by (offset) view lines. * This is the main function which is called by code not specifically dealing with word-wrap. * The opposite conversion (cursor to offset) can be done with cache()->displayViewLine(). * * The cursors involved are virtual cursors (ie. equivalent to m_displayCursor) */ KTextEditor::Cursor KateViewInternal::viewLineOffset(const KTextEditor::Cursor &virtualCursor, int offset, bool keepX) { if (!m_view->dynWordWrap()) { KTextEditor::Cursor ret(qMin((int)m_view->textFolding().visibleLines() - 1, virtualCursor.line() + offset), 0); if (ret.line() < 0) { ret.setLine(0); } if (keepX) { int realLine = m_view->textFolding().visibleLineToLine(ret.line()); KateTextLayout t = cache()->textLayout(realLine, 0); Q_ASSERT(t.isValid()); ret.setColumn(renderer()->xToCursor(t, m_preservedX, !m_view->wrapCursor()).column()); } return ret; } KTextEditor::Cursor realCursor = virtualCursor; realCursor.setLine(m_view->textFolding().visibleLineToLine(m_view->textFolding().lineToVisibleLine(virtualCursor.line()))); int cursorViewLine = cache()->viewLine(realCursor); int currentOffset = 0; int virtualLine = 0; bool forwards = (offset > 0) ? true : false; if (forwards) { currentOffset = cache()->lastViewLine(realCursor.line()) - cursorViewLine; if (offset <= currentOffset) { // the answer is on the same line KateTextLayout thisLine = cache()->textLayout(realCursor.line(), cursorViewLine + offset); Q_ASSERT(thisLine.virtualLine() == (int) m_view->textFolding().lineToVisibleLine(virtualCursor.line())); return KTextEditor::Cursor(virtualCursor.line(), thisLine.startCol()); } virtualLine = virtualCursor.line() + 1; } else { offset = -offset; currentOffset = cursorViewLine; if (offset <= currentOffset) { // the answer is on the same line KateTextLayout thisLine = cache()->textLayout(realCursor.line(), cursorViewLine - offset); Q_ASSERT(thisLine.virtualLine() == (int) m_view->textFolding().lineToVisibleLine(virtualCursor.line())); return KTextEditor::Cursor(virtualCursor.line(), thisLine.startCol()); } virtualLine = virtualCursor.line() - 1; } currentOffset++; while (virtualLine >= 0 && virtualLine < (int)m_view->textFolding().visibleLines()) { int realLine = m_view->textFolding().visibleLineToLine(virtualLine); KateLineLayoutPtr thisLine = cache()->line(realLine, virtualLine); if (!thisLine) { break; } for (int i = 0; i < thisLine->viewLineCount(); ++i) { if (offset == currentOffset) { KateTextLayout thisViewLine = thisLine->viewLine(i); if (!forwards) { // We actually want it the other way around int requiredViewLine = cache()->lastViewLine(realLine) - thisViewLine.viewLine(); if (requiredViewLine != thisViewLine.viewLine()) { thisViewLine = thisLine->viewLine(requiredViewLine); } } KTextEditor::Cursor ret(virtualLine, thisViewLine.startCol()); // keep column position if (keepX) { KTextEditor::Cursor realCursor = toRealCursor(virtualCursor); KateTextLayout t = cache()->textLayout(realCursor); // renderer()->cursorToX(t, realCursor, !m_view->wrapCursor()); realCursor = renderer()->xToCursor(thisViewLine, m_preservedX, !m_view->wrapCursor()); ret.setColumn(realCursor.column()); } return ret; } currentOffset++; } if (forwards) { virtualLine++; } else { virtualLine--; } } // Looks like we were asked for something a bit exotic. // Return the max/min valid position. if (forwards) { return KTextEditor::Cursor(m_view->textFolding().visibleLines() - 1, doc()->lineLength(m_view->textFolding().visibleLineToLine(m_view->textFolding().visibleLines() - 1))); } else { return KTextEditor::Cursor(0, 0); } } int KateViewInternal::lineMaxCursorX(const KateTextLayout &range) { if (!m_view->wrapCursor() && !range.wrap()) { return INT_MAX; } int maxX = range.endX(); if (maxX && range.wrap()) { QChar lastCharInLine = doc()->kateTextLine(range.line())->at(range.endCol() - 1); maxX -= renderer()->config()->fontMetrics().width(lastCharInLine); } return maxX; } int KateViewInternal::lineMaxCol(const KateTextLayout &range) { int maxCol = range.endCol(); if (maxCol && range.wrap()) { maxCol--; } return maxCol; } void KateViewInternal::cursorUp(bool sel) { if (!sel && m_view->completionWidget()->isCompletionActive()) { m_view->completionWidget()->cursorUp(); return; } // assert that the display cursor is in visible lines Q_ASSERT(m_displayCursor.line() < m_view->textFolding().visibleLines()); /** * move cursor to start of line, if we are at first line! */ if (m_displayCursor.line() == 0 && (!m_view->dynWordWrap() || cache()->viewLine(m_cursor) == 0)) { home(sel); return; } m_preserveX = true; KateTextLayout thisLine = currentLayout(); // This is not the first line because that is already simplified out above KateTextLayout pRange = previousLayout(); // Ensure we're in the right spot Q_ASSERT(m_cursor.line() == thisLine.line()); Q_ASSERT(m_cursor.column() >= thisLine.startCol()); Q_ASSERT(!thisLine.wrap() || m_cursor.column() < thisLine.endCol()); KTextEditor::Cursor c = renderer()->xToCursor(pRange, m_preservedX, !m_view->wrapCursor()); updateSelection(c, sel); updateCursor(c); } void KateViewInternal::cursorDown(bool sel) { if (!sel && m_view->completionWidget()->isCompletionActive()) { m_view->completionWidget()->cursorDown(); return; } /** * move cursor to end of line, if we are at last line! */ if ((m_displayCursor.line() >= m_view->textFolding().visibleLines() - 1) && (!m_view->dynWordWrap() || cache()->viewLine(m_cursor) == cache()->lastViewLine(m_cursor.line()))) { end(sel); return; } m_preserveX = true; KateTextLayout thisLine = currentLayout(); // This is not the last line because that is already simplified out above KateTextLayout nRange = nextLayout(); // Ensure we're in the right spot Q_ASSERT((m_cursor.line() == thisLine.line()) && (m_cursor.column() >= thisLine.startCol()) && (!thisLine.wrap() || m_cursor.column() < thisLine.endCol())); KTextEditor::Cursor c = renderer()->xToCursor(nRange, m_preservedX, !m_view->wrapCursor()); updateSelection(c, sel); updateCursor(c); } void KateViewInternal::cursorToMatchingBracket(bool sel) { KTextEditor::Cursor c = findMatchingBracket(); if (c.isValid()) { updateSelection(c, sel); updateCursor(c); } } void KateViewInternal::topOfView(bool sel) { KTextEditor::Cursor c = viewLineOffset(startPos(), m_minLinesVisible); updateSelection(toRealCursor(c), sel); updateCursor(toRealCursor(c)); } void KateViewInternal::bottomOfView(bool sel) { KTextEditor::Cursor c = viewLineOffset(endPos(), -m_minLinesVisible); updateSelection(toRealCursor(c), sel); updateCursor(toRealCursor(c)); } // lines is the offset to scroll by void KateViewInternal::scrollLines(int lines, bool sel) { KTextEditor::Cursor c = viewLineOffset(m_displayCursor, lines, true); // Fix the virtual cursor -> real cursor c.setLine(m_view->textFolding().visibleLineToLine(c.line())); updateSelection(c, sel); updateCursor(c); } // This is a bit misleading... it's asking for the view to be scrolled, not the cursor void KateViewInternal::scrollUp() { KTextEditor::Cursor newPos = viewLineOffset(startPos(), -1); scrollPos(newPos); } void KateViewInternal::scrollDown() { KTextEditor::Cursor newPos = viewLineOffset(startPos(), 1); scrollPos(newPos); } void KateViewInternal::setAutoCenterLines(int viewLines, bool updateView) { m_autoCenterLines = viewLines; m_minLinesVisible = qMin(int((linesDisplayed() - 1) / 2), m_autoCenterLines); if (updateView) { KateViewInternal::updateView(); } } void KateViewInternal::pageUp(bool sel, bool half) { if (m_view->isCompletionActive()) { m_view->completionWidget()->pageUp(); return; } // remember the view line and x pos int viewLine = cache()->displayViewLine(m_displayCursor); bool atTop = startPos().atStartOfDocument(); // Adjust for an auto-centering cursor int lineadj = m_minLinesVisible; int linesToScroll; if (! half) { linesToScroll = -qMax((linesDisplayed() - 1) - lineadj, 0); } else { linesToScroll = -qMax((linesDisplayed() / 2 - 1) - lineadj, 0); } m_preserveX = true; if (!doc()->pageUpDownMovesCursor() && !atTop) { KTextEditor::Cursor newStartPos = viewLineOffset(startPos(), linesToScroll - 1); scrollPos(newStartPos); // put the cursor back approximately where it was KTextEditor::Cursor newPos = toRealCursor(viewLineOffset(newStartPos, viewLine, true)); KateTextLayout newLine = cache()->textLayout(newPos); newPos = renderer()->xToCursor(newLine, m_preservedX, !m_view->wrapCursor()); m_preserveX = true; updateSelection(newPos, sel); updateCursor(newPos); } else { scrollLines(linesToScroll, sel); } } void KateViewInternal::pageDown(bool sel, bool half) { if (m_view->isCompletionActive()) { m_view->completionWidget()->pageDown(); return; } // remember the view line int viewLine = cache()->displayViewLine(m_displayCursor); bool atEnd = startPos() >= m_cachedMaxStartPos; // Adjust for an auto-centering cursor int lineadj = m_minLinesVisible; int linesToScroll; if (! half) { linesToScroll = qMax((linesDisplayed() - 1) - lineadj, 0); } else { linesToScroll = qMax((linesDisplayed() / 2 - 1) - lineadj, 0); } m_preserveX = true; if (!doc()->pageUpDownMovesCursor() && !atEnd) { KTextEditor::Cursor newStartPos = viewLineOffset(startPos(), linesToScroll + 1); scrollPos(newStartPos); // put the cursor back approximately where it was KTextEditor::Cursor newPos = toRealCursor(viewLineOffset(newStartPos, viewLine, true)); KateTextLayout newLine = cache()->textLayout(newPos); newPos = renderer()->xToCursor(newLine, m_preservedX, !m_view->wrapCursor()); m_preserveX = true; updateSelection(newPos, sel); updateCursor(newPos); } else { scrollLines(linesToScroll, sel); } } int KateViewInternal::maxLen(int startLine) { Q_ASSERT(!m_view->dynWordWrap()); int displayLines = (m_view->height() / renderer()->lineHeight()) + 1; int maxLen = 0; for (int z = 0; z < displayLines; z++) { int virtualLine = startLine + z; if (virtualLine < 0 || virtualLine >= (int)m_view->textFolding().visibleLines()) { break; } maxLen = qMax(maxLen, cache()->line(m_view->textFolding().visibleLineToLine(virtualLine))->width()); } return maxLen; } bool KateViewInternal::columnScrollingPossible() { return !m_view->dynWordWrap() && m_columnScroll->isEnabled() && (m_columnScroll->maximum() > 0); } bool KateViewInternal::lineScrollingPossible() { return m_lineScroll->minimum() != m_lineScroll->maximum(); } void KateViewInternal::top(bool sel) { KTextEditor::Cursor newCursor(0, 0); newCursor = renderer()->xToCursor(cache()->textLayout(newCursor), m_preservedX, !m_view->wrapCursor()); updateSelection(newCursor, sel); updateCursor(newCursor); } void KateViewInternal::bottom(bool sel) { KTextEditor::Cursor newCursor(doc()->lastLine(), 0); newCursor = renderer()->xToCursor(cache()->textLayout(newCursor), m_preservedX, !m_view->wrapCursor()); updateSelection(newCursor, sel); updateCursor(newCursor); } void KateViewInternal::top_home(bool sel) { if (m_view->isCompletionActive()) { m_view->completionWidget()->top(); return; } KTextEditor::Cursor c(0, 0); updateSelection(c, sel); updateCursor(c); } void KateViewInternal::bottom_end(bool sel) { if (m_view->isCompletionActive()) { m_view->completionWidget()->bottom(); return; } KTextEditor::Cursor c(doc()->lastLine(), doc()->lineLength(doc()->lastLine())); updateSelection(c, sel); updateCursor(c); } void KateViewInternal::updateSelection(const KTextEditor::Cursor &_newCursor, bool keepSel) { KTextEditor::Cursor newCursor = _newCursor; if (keepSel) { if (!m_view->selection() || (m_selectAnchor.line() == -1) //don't kill the selection if we have a persistent selection and //the cursor is inside or at the boundaries of the selected area || (m_view->config()->persistentSelection() && !(m_view->selectionRange().contains(m_cursor) || m_view->selectionRange().boundaryAtCursor(m_cursor)))) { m_selectAnchor = m_cursor; setSelection(KTextEditor::Range(m_cursor, newCursor)); } else { bool doSelect = true; switch (m_selectionMode) { case Word: { // Restore selStartCached if needed. It gets nuked by // viewSelectionChanged if we drag the selection into non-existence, // which can legitimately happen if a shift+DC selection is unable to // set a "proper" (i.e. non-empty) cached selection, e.g. because the // start was on something that isn't a word. Word select mode relies // on the cached selection being set properly, even if it is empty // (i.e. selStartCached == selEndCached). if (!m_selectionCached.isValid()) { m_selectionCached.setStart(m_selectionCached.end()); } int c; if (newCursor > m_selectionCached.start()) { m_selectAnchor = m_selectionCached.start(); Kate::TextLine l = doc()->kateTextLine(newCursor.line()); c = newCursor.column(); if (c > 0 && doc()->highlight()->isInWord(l->at(c - 1))) { for (; c < l->length(); c++) if (!doc()->highlight()->isInWord(l->at(c))) { break; } } newCursor.setColumn(c); } else if (newCursor < m_selectionCached.start()) { m_selectAnchor = m_selectionCached.end(); Kate::TextLine l = doc()->kateTextLine(newCursor.line()); c = newCursor.column(); if (c > 0 && c < doc()->lineLength(newCursor.line()) && doc()->highlight()->isInWord(l->at(c)) && doc()->highlight()->isInWord(l->at(c - 1))) { for (c -= 2; c >= 0; c--) if (!doc()->highlight()->isInWord(l->at(c))) { break; } newCursor.setColumn(c + 1); } } else { doSelect = false; } } break; case Line: if (!m_selectionCached.isValid()) { m_selectionCached = KTextEditor::Range(endLine(), 0, endLine(), 0); } if (newCursor.line() > m_selectionCached.start().line()) { if (newCursor.line() + 1 >= doc()->lines()) { newCursor.setColumn(doc()->line(newCursor.line()).length()); } else { newCursor.setPosition(newCursor.line() + 1, 0); } // Grow to include the entire line m_selectAnchor = m_selectionCached.start(); m_selectAnchor.setColumn(0); } else if (newCursor.line() < m_selectionCached.start().line()) { newCursor.setColumn(0); // Grow to include entire line m_selectAnchor = m_selectionCached.end(); if (m_selectAnchor.column() > 0) { if (m_selectAnchor.line() + 1 >= doc()->lines()) { m_selectAnchor.setColumn(doc()->line(newCursor.line()).length()); } else { m_selectAnchor.setPosition(m_selectAnchor.line() + 1, 0); } } } else { // same line, ignore doSelect = false; } break; case Mouse: { if (!m_selectionCached.isValid()) { break; } if (newCursor > m_selectionCached.end()) { m_selectAnchor = m_selectionCached.start(); } else if (newCursor < m_selectionCached.start()) { m_selectAnchor = m_selectionCached.end(); } else { doSelect = false; } } break; default: /* nothing special to do */; } if (doSelect) { setSelection(KTextEditor::Range(m_selectAnchor, newCursor)); } else if (m_selectionCached.isValid()) { // we have a cached selection, so we restore that setSelection(m_selectionCached); } } m_selChangedByUser = true; } else if (!m_view->config()->persistentSelection()) { m_view->clearSelection(); m_selectionCached = KTextEditor::Range::invalid(); m_selectAnchor = KTextEditor::Cursor::invalid(); } #ifndef QT_NO_ACCESSIBILITY // FIXME KF5 // QAccessibleTextSelectionEvent ev(this, /* selection start, selection end*/); // QAccessible::updateAccessibility(&ev); #endif } void KateViewInternal::setSelection(const KTextEditor::Range &range) { disconnect(m_view, SIGNAL(selectionChanged(KTextEditor::View*)), this, SLOT(viewSelectionChanged())); m_view->setSelection(range); connect(m_view, SIGNAL(selectionChanged(KTextEditor::View*)), this, SLOT(viewSelectionChanged())); } void KateViewInternal::moveCursorToSelectionEdge() { if (!m_view->selection()) { return; } int tmp = m_minLinesVisible; m_minLinesVisible = 0; if (m_view->selectionRange().start() < m_selectAnchor) { updateCursor(m_view->selectionRange().start()); } else { updateCursor(m_view->selectionRange().end()); } m_minLinesVisible = tmp; } void KateViewInternal::updateCursor(const KTextEditor::Cursor &newCursor, bool force, bool center, bool calledExternally) { if (!force && (m_cursor.toCursor() == newCursor)) { m_displayCursor = toVirtualCursor(newCursor); if (!m_madeVisible && m_view == doc()->activeView()) { // unfold if required m_view->textFolding().ensureLineIsVisible(newCursor.line()); makeVisible(m_displayCursor, m_displayCursor.column(), false, center, calledExternally); } return; } if (m_cursor.line() != newCursor.line()) { m_leftBorder->updateForCursorLineChange(); } // unfold if required m_view->textFolding().ensureLineIsVisible(newCursor.line()); KTextEditor::Cursor oldDisplayCursor = m_displayCursor; m_displayCursor = toVirtualCursor(newCursor); m_cursor.setPosition(newCursor); if (m_view == doc()->activeView()) { makeVisible(m_displayCursor, m_displayCursor.column(), false, center, calledExternally); } updateBracketMarks(); // It's efficient enough to just tag them both without checking to see if they're on the same view line /* kdDebug()<<"oldDisplayCursor:"< 0) { m_cursorTimer.start(QApplication::cursorFlashTime() / 2); } renderer()->setDrawCaret(true); } // Remember the maximum X position if requested if (m_preserveX) { m_preserveX = false; } else { m_preservedX = renderer()->cursorToX(cache()->textLayout(m_cursor), m_cursor, !m_view->wrapCursor()); } //qCDebug(LOG_KTE) << "m_preservedX: " << m_preservedX << " (was "<< oldmaxx << "), m_cursorX: " << m_cursorX; //qCDebug(LOG_KTE) << "Cursor now located at real " << cursor.line << "," << cursor.col << ", virtual " << m_displayCursor.line << ", " << m_displayCursor.col << "; Top is " << startLine() << ", " << startPos().col; cursorMoved(); updateDirty(); //paintText(0, 0, width(), height(), true); emit m_view->cursorPositionChanged(m_view, m_cursor); } void KateViewInternal::updateBracketMarkAttributes() { KTextEditor::Attribute::Ptr bracketFill = KTextEditor::Attribute::Ptr(new KTextEditor::Attribute()); bracketFill->setBackground(m_view->m_renderer->config()->highlightedBracketColor()); bracketFill->setBackgroundFillWhitespace(false); if (QFontInfo(renderer()->currentFont()).fixedPitch()) { // make font bold only for fixed fonts, otherwise text jumps around bracketFill->setFontBold(); } m_bmStart->setAttribute(bracketFill); m_bmEnd->setAttribute(bracketFill); if (m_view->m_renderer->config()->showWholeBracketExpression()) { KTextEditor::Attribute::Ptr expressionFill = KTextEditor::Attribute::Ptr(new KTextEditor::Attribute()); expressionFill->setBackground(m_view->m_renderer->config()->highlightedBracketColor()); expressionFill->setBackgroundFillWhitespace(false); m_bm->setAttribute(expressionFill); } else { m_bm->setAttribute(KTextEditor::Attribute::Ptr(new KTextEditor::Attribute())); } } void KateViewInternal::updateBracketMarks() { // add some limit to this, this is really endless on big files without limit const int maxLines = 5000; const KTextEditor::Range newRange = doc()->findMatchingBracket(m_cursor, maxLines); // new range valid, then set ranges to it if (newRange.isValid()) { if (m_bm->toRange() == newRange) { return; } // modify full range m_bm->setRange(newRange); // modify start and end ranges m_bmStart->setRange(KTextEditor::Range(m_bm->start(), KTextEditor::Cursor(m_bm->start().line(), m_bm->start().column() + 1))); m_bmEnd->setRange(KTextEditor::Range(m_bm->end(), KTextEditor::Cursor(m_bm->end().line(), m_bm->end().column() + 1))); // flash matching bracket if (!renderer()->config()->animateBracketMatching()) { return; } const KTextEditor::Cursor flashPos = (m_cursor == m_bmStart->start() || m_cursor == m_bmStart->end()) ? m_bmEnd->start() : m_bm->start(); if (flashPos != m_bmLastFlashPos->toCursor()) { m_bmLastFlashPos->setPosition(flashPos); KTextEditor::Attribute::Ptr attribute = doc()->attributeAt(flashPos); attribute->setBackground(m_view->m_renderer->config()->highlightedBracketColor()); attribute->setFontBold(m_bmStart->attribute()->fontBold()); flashChar(flashPos, attribute); } return; } // new range was invalid m_bm->setRange(KTextEditor::Range::invalid()); m_bmStart->setRange(KTextEditor::Range::invalid()); m_bmEnd->setRange(KTextEditor::Range::invalid()); m_bmLastFlashPos->setPosition(KTextEditor::Cursor::invalid()); } bool KateViewInternal::tagLine(const KTextEditor::Cursor &virtualCursor) { // FIXME may be a more efficient way for this if ((int)m_view->textFolding().visibleLineToLine(virtualCursor.line()) > doc()->lastLine()) { return false; } // End FIXME int viewLine = cache()->displayViewLine(virtualCursor, true); if (viewLine >= 0 && viewLine < cache()->viewCacheLineCount()) { cache()->viewLine(viewLine).setDirty(); // tag one line more because of overlapping things like _, bug 335079 if (viewLine+1 < cache()->viewCacheLineCount()) { cache()->viewLine(viewLine+1).setDirty(); } m_leftBorder->update(0, lineToY(viewLine), m_leftBorder->width(), renderer()->lineHeight()); return true; } return false; } bool KateViewInternal::tagLines(int start, int end, bool realLines) { return tagLines(KTextEditor::Cursor(start, 0), KTextEditor::Cursor(end, -1), realLines); } bool KateViewInternal::tagLines(KTextEditor::Cursor start, KTextEditor::Cursor end, bool realCursors) { if (realCursors) { cache()->relayoutLines(start.line(), end.line()); //qCDebug(LOG_KTE)<<"realLines is true"; start = toVirtualCursor(start); end = toVirtualCursor(end); } else { cache()->relayoutLines(toRealCursor(start).line(), toRealCursor(end).line()); } if (end.line() < startLine()) { //qCDebug(LOG_KTE)<<"end endLine(), but cache may not be valid when checking, so use a // less optimal but still adequate approximation (potential overestimation but minimal performance difference) if (start.line() > startLine() + cache()->viewCacheLineCount()) { //qCDebug(LOG_KTE)<<"start> endLine"<updateViewCache(startPos()); //qCDebug(LOG_KTE) << "tagLines( [" << start << "], [" << end << "] )"; bool ret = false; for (int z = 0; z < cache()->viewCacheLineCount(); z++) { KateTextLayout &line = cache()->viewLine(z); if ((line.virtualLine() > start.line() || (line.virtualLine() == start.line() && line.endCol() >= start.column() && start.column() != -1)) && (line.virtualLine() < end.line() || (line.virtualLine() == end.line() && (line.startCol() <= end.column() || end.column() == -1)))) { ret = true; break; //qCDebug(LOG_KTE) << "Tagged line " << line.line(); } } if (!m_view->dynWordWrap()) { int y = lineToY(start.line()); // FIXME is this enough for when multiple lines are deleted int h = (end.line() - start.line() + 2) * renderer()->lineHeight(); if (end.line() >= m_view->textFolding().visibleLines() - 1) { h = height(); } m_leftBorder->update(0, y, m_leftBorder->width(), h); } else { // FIXME Do we get enough good info in editRemoveText to optimize this more? //bool justTagged = false; for (int z = 0; z < cache()->viewCacheLineCount(); z++) { KateTextLayout &line = cache()->viewLine(z); if (!line.isValid() || ((line.virtualLine() > start.line() || (line.virtualLine() == start.line() && line.endCol() >= start.column() && start.column() != -1)) && (line.virtualLine() < end.line() || (line.virtualLine() == end.line() && (line.startCol() <= end.column() || end.column() == -1))))) { //justTagged = true; m_leftBorder->update(0, z * renderer()->lineHeight(), m_leftBorder->width(), m_leftBorder->height()); break; } /*else if (justTagged) { justTagged = false; leftBorder->update (0, z * doc()->viewFont.fontHeight, leftBorder->width(), doc()->viewFont.fontHeight); break; }*/ } } return ret; } bool KateViewInternal::tagRange(const KTextEditor::Range &range, bool realCursors) { return tagLines(range.start(), range.end(), realCursors); } void KateViewInternal::tagAll() { // clear the cache... cache()->clear(); m_leftBorder->updateFont(); m_leftBorder->update(); } void KateViewInternal::paintCursor() { if (tagLine(m_displayCursor)) { updateDirty(); //paintText (0,0,width(), height(), true); } } // Point in content coordinates void KateViewInternal::placeCursor(const QPoint &p, bool keepSelection, bool updateSelection) { KateTextLayout thisLine = yToKateTextLayout(p.y()); KTextEditor::Cursor c; if (!thisLine.isValid()) { // probably user clicked below the last line -> use the last line thisLine = cache()->textLayout(doc()->lines() - 1, -1); } c = renderer()->xToCursor(thisLine, startX() + p.x(), !m_view->wrapCursor()); if (c.line() < 0 || c.line() >= doc()->lines()) { return; } if (updateSelection) { KateViewInternal::updateSelection(c, keepSelection); } int tmp = m_minLinesVisible; m_minLinesVisible = 0; updateCursor(c); m_minLinesVisible = tmp; if (updateSelection && keepSelection) { moveCursorToSelectionEdge(); } } // Point in content coordinates bool KateViewInternal::isTargetSelected(const QPoint &p) { const KateTextLayout &thisLine = yToKateTextLayout(p.y()); if (!thisLine.isValid()) { return false; } return m_view->cursorSelected(renderer()->xToCursor(thisLine, startX() + p.x(), !m_view->wrapCursor())); } //BEGIN EVENT HANDLING STUFF bool KateViewInternal::eventFilter(QObject *obj, QEvent *e) { switch (e->type()) { case QEvent::ChildAdded: case QEvent::ChildRemoved: { QChildEvent *c = static_cast(e); if (c->added()) { c->child()->installEventFilter(this); /*foreach (QWidget* child, c->child()->findChildren()) child->installEventFilter(this);*/ } else if (c->removed()) { c->child()->removeEventFilter(this); /*foreach (QWidget* child, c->child()->findChildren()) child->removeEventFilter(this);*/ } } break; case QEvent::ShortcutOverride: { QKeyEvent *k = static_cast(e); if (k->key() == Qt::Key_Escape && k->modifiers() == Qt::NoModifier) { if (m_view->isCompletionActive()) { m_view->abortCompletion(); k->accept(); //qCDebug(LOG_KTE) << obj << "shortcut override" << k->key() << "aborting completion"; return true; } else if (!m_view->bottomViewBar()->hiddenOrPermanent()) { m_view->bottomViewBar()->hideCurrentBarWidget(); k->accept(); //qCDebug(LOG_KTE) << obj << "shortcut override" << k->key() << "closing view bar"; return true; } else if (!m_view->config()->persistentSelection() && m_view->selection()) { m_currentInputMode->clearSelection(); k->accept(); //qCDebug(LOG_KTE) << obj << "shortcut override" << k->key() << "clearing selection"; return true; } } if (m_currentInputMode->stealKey(k)) { k->accept(); return true; } } break; case QEvent::KeyPress: { QKeyEvent *k = static_cast(e); // Override all other single key shortcuts which do not use a modifier other than Shift if (obj == this && (!k->modifiers() || k->modifiers() == Qt::ShiftModifier)) { keyPressEvent(k); if (k->isAccepted()) { //qCDebug(LOG_KTE) << obj << "shortcut override" << k->key() << "using keystroke"; return true; } } //qCDebug(LOG_KTE) << obj << "shortcut override" << k->key() << "ignoring"; } break; case QEvent::DragMove: { QPoint currentPoint = ((QDragMoveEvent *) e)->pos(); QRect doNotScrollRegion(s_scrollMargin, s_scrollMargin, width() - s_scrollMargin * 2, height() - s_scrollMargin * 2); if (!doNotScrollRegion.contains(currentPoint)) { startDragScroll(); // Keep sending move events ((QDragMoveEvent *)e)->accept(QRect(0, 0, 0, 0)); } dragMoveEvent((QDragMoveEvent *)e); } break; case QEvent::DragLeave: // happens only when pressing ESC while dragging stopDragScroll(); break; default: break; } return QWidget::eventFilter(obj, e); } void KateViewInternal::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Left && e->modifiers() == Qt::AltModifier) { m_view->emitNavigateLeft(); e->setAccepted(true); return; } if (e->key() == Qt::Key_Right && e->modifiers() == Qt::AltModifier) { m_view->emitNavigateRight(); e->setAccepted(true); return; } if (e->key() == Qt::Key_Up && e->modifiers() == Qt::AltModifier) { m_view->emitNavigateUp(); e->setAccepted(true); return; } if (e->key() == Qt::Key_Down && e->modifiers() == Qt::AltModifier) { m_view->emitNavigateDown(); e->setAccepted(true); return; } if (e->key() == Qt::Key_Return && e->modifiers() == Qt::AltModifier) { m_view->emitNavigateAccept(); e->setAccepted(true); return; } if (e->key() == Qt::Key_Backspace && e->modifiers() == Qt::AltModifier) { m_view->emitNavigateBack(); e->setAccepted(true); return; } if (e->key() == Qt::Key_Alt && m_view->completionWidget()->isCompletionActive()) { m_completionItemExpanded = m_view->completionWidget()->toggleExpanded(true); m_view->completionWidget()->resetHadNavigation(); m_altDownTime.start(); } // Note: AND'ing with is a quick hack to fix Key_Enter const int key = e->key() | (e->modifiers() & Qt::ShiftModifier); if (m_currentInputMode->keyPress(e)) { return; } if (!doc()->isReadWrite()) { e->ignore(); return; } if ((key == Qt::Key_Return) || (key == Qt::Key_Enter) || (key == Qt::SHIFT + Qt::Key_Return) || (key == Qt::SHIFT + Qt::Key_Enter)) { doReturn(); e->accept(); return; } if (key == Qt::Key_Backspace || key == Qt::SHIFT + Qt::Key_Backspace) { //m_view->backspace(); e->accept(); return; } if (key == Qt::Key_Tab || key == Qt::SHIFT + Qt::Key_Backtab || key == Qt::Key_Backtab) { if (m_view->completionWidget()->isCompletionActive()) { e->accept(); m_view->completionWidget()->tab(key != Qt::Key_Tab); return; } if (key == Qt::Key_Tab) { uint tabHandling = doc()->config()->tabHandling(); // convert tabSmart into tabInsertsTab or tabIndents: if (tabHandling == KateDocumentConfig::tabSmart) { // multiple lines selected if (m_view->selection() && !m_view->selectionRange().onSingleLine()) { tabHandling = KateDocumentConfig::tabIndents; } // otherwise: take look at cursor position else { // if the cursor is at or before the first non-space character // or on an empty line, // Tab indents, otherwise it inserts a tab character. Kate::TextLine line = doc()->kateTextLine(m_cursor.line()); int first = line->firstChar(); if (first < 0 || m_cursor.column() <= first) { tabHandling = KateDocumentConfig::tabIndents; } else { tabHandling = KateDocumentConfig::tabInsertsTab; } } } if (tabHandling == KateDocumentConfig::tabInsertsTab) { doc()->typeChars(m_view, QStringLiteral("\t")); } else { doc()->indent(m_view->selection() ? m_view->selectionRange() : KTextEditor::Range(m_cursor.line(), 0, m_cursor.line(), 0), 1); } e->accept(); return; } else if (doc()->config()->tabHandling() != KateDocumentConfig::tabInsertsTab) { // key == Qt::SHIFT+Qt::Key_Backtab || key == Qt::Key_Backtab doc()->indent(m_view->selection() ? m_view->selectionRange() : KTextEditor::Range(m_cursor.line(), 0, m_cursor.line(), 0), -1); e->accept(); return; } } if (!(e->modifiers() & Qt::ControlModifier) && !e->text().isEmpty() && doc()->typeChars(m_view, e->text())) { e->accept(); return; } // allow composition of AltGr + (q|2|3) on windows static const int altGR = Qt::ControlModifier | Qt::AltModifier; if ((e->modifiers() & altGR) == altGR && !e->text().isEmpty() && doc()->typeChars(m_view, e->text())) { e->accept(); return; } e->ignore(); } void KateViewInternal::keyReleaseEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Alt && m_view->completionWidget()->isCompletionActive() && ((m_completionItemExpanded && (m_view->completionWidget()->hadNavigation() || m_altDownTime.elapsed() > 300)) || (!m_completionItemExpanded && !m_view->completionWidget()->hadNavigation()))) { m_view->completionWidget()->toggleExpanded(false, true); } if ((e->modifiers() & Qt::SHIFT) == Qt::SHIFT) { m_shiftKeyPressed = true; } else { if (m_shiftKeyPressed) { m_shiftKeyPressed = false; if (m_selChangedByUser) { if (m_view->selection()) { QApplication::clipboard()->setText(m_view->selectionText(), QClipboard::Selection); } m_selChangedByUser = false; } } } e->ignore(); return; } void KateViewInternal::contextMenuEvent(QContextMenuEvent *e) { // try to show popup menu QPoint p = e->pos(); if (e->reason() == QContextMenuEvent::Keyboard) { makeVisible(m_displayCursor, 0); p = cursorCoordinates(false); p.rx() -= startX(); } else if (! m_view->selection() || m_view->config()->persistentSelection()) { placeCursor(e->pos()); } // popup is a qguardedptr now if (m_view->contextMenu()) { m_view->spellingMenu()->setUseMouseForMisspelledRange((e->reason() == QContextMenuEvent::Mouse)); m_view->contextMenu()->popup(mapToGlobal(p)); e->accept(); } } void KateViewInternal::mousePressEvent(QMouseEvent *e) { switch (e->button()) { case Qt::LeftButton: m_selChangedByUser = false; if (m_possibleTripleClick) { m_possibleTripleClick = false; m_selectionMode = Line; if (e->modifiers() & Qt::ShiftModifier) { updateSelection(m_cursor, true); } else { m_view->selectLine(m_cursor); if (m_view->selection()) { m_selectAnchor = m_view->selectionRange().start(); } } if (m_view->selection()) { QApplication::clipboard()->setText(m_view->selectionText(), QClipboard::Selection); } // Keep the line at the select anchor selected during further // mouse selection if (m_selectAnchor.line() > m_view->selectionRange().start().line()) { // Preserve the last selected line if (m_selectAnchor == m_view->selectionRange().end() && m_selectAnchor.column() == 0) { m_selectionCached.setStart(KTextEditor::Cursor(m_selectAnchor.line() - 1, 0)); } else { m_selectionCached.setStart(KTextEditor::Cursor(m_selectAnchor.line(), 0)); } m_selectionCached.setEnd(m_view->selectionRange().end()); } else { // Preserve the first selected line m_selectionCached.setStart(m_view->selectionRange().start()); if (m_view->selectionRange().end().line() > m_view->selectionRange().start().line()) { m_selectionCached.setEnd(KTextEditor::Cursor(m_view->selectionRange().start().line() + 1, 0)); } else { m_selectionCached.setEnd(m_view->selectionRange().end()); } } moveCursorToSelectionEdge(); m_scrollX = 0; m_scrollY = 0; m_scrollTimer.start(50); e->accept(); return; } else if (m_selectionMode == Default) { m_selectionMode = Mouse; } // request the software keyboard, if any if (e->button() == Qt::LeftButton && qApp->autoSipEnabled()) { QStyle::RequestSoftwareInputPanel behavior = QStyle::RequestSoftwareInputPanel(style()->styleHint(QStyle::SH_RequestSoftwareInputPanel)); if (hasFocus() || behavior == QStyle::RSIP_OnMouseClick) { QEvent event(QEvent::RequestSoftwareInputPanel); QApplication::sendEvent(this, &event); } } if (e->modifiers() & Qt::ShiftModifier) { if (!m_selectAnchor.isValid()) { m_selectAnchor = m_cursor; } } else { m_selectionCached = KTextEditor::Range::invalid(); } if (!(e->modifiers() & Qt::ShiftModifier) && isTargetSelected(e->pos())) { m_dragInfo.state = diPending; m_dragInfo.start = e->pos(); } else { m_dragInfo.state = diNone; if (e->modifiers() & Qt::ShiftModifier) { placeCursor(e->pos(), true, false); if (m_selectionCached.start().isValid()) { if (m_cursor.toCursor() < m_selectionCached.start()) { m_selectAnchor = m_selectionCached.end(); } else { m_selectAnchor = m_selectionCached.start(); } } setSelection(KTextEditor::Range(m_selectAnchor, m_cursor)); } else { placeCursor(e->pos()); } m_scrollX = 0; m_scrollY = 0; m_scrollTimer.start(50); } e->accept(); break; default: e->ignore(); break; } } void KateViewInternal::mouseDoubleClickEvent(QMouseEvent *e) { switch (e->button()) { case Qt::LeftButton: m_selectionMode = Word; if (e->modifiers() & Qt::ShiftModifier) { // Now select the word under the select anchor int cs, ce; Kate::TextLine l = doc()->kateTextLine(m_selectAnchor.line()); ce = m_selectAnchor.column(); if (ce > 0 && doc()->highlight()->isInWord(l->at(ce))) { for (; ce < l->length(); ce++) if (!doc()->highlight()->isInWord(l->at(ce))) { break; } } cs = m_selectAnchor.column() - 1; if (cs < doc()->lineLength(m_selectAnchor.line()) && doc()->highlight()->isInWord(l->at(cs))) { for (cs--; cs >= 0; cs--) if (!doc()->highlight()->isInWord(l->at(cs))) { break; } } // ...and keep it selected if (cs + 1 < ce) { m_selectionCached.setStart(KTextEditor::Cursor(m_selectAnchor.line(), cs + 1)); m_selectionCached.setEnd(KTextEditor::Cursor(m_selectAnchor.line(), ce)); } else { m_selectionCached.setStart(m_selectAnchor); m_selectionCached.setEnd(m_selectAnchor); } // Now word select to the mouse cursor placeCursor(e->pos(), true); } else { // first clear the selection, otherwise we run into bug #106402 // ...and set the cursor position, for the same reason (otherwise there // are *other* idiosyncrasies we can't fix without reintroducing said // bug) // Parameters: don't redraw, and don't emit selectionChanged signal yet m_view->clearSelection(false, false); placeCursor(e->pos()); m_view->selectWord(m_cursor); cursorToMatchingBracket(true); if (m_view->selection()) { m_selectAnchor = m_view->selectionRange().start(); m_selectionCached = m_view->selectionRange(); } else { m_selectAnchor = m_cursor; m_selectionCached = KTextEditor::Range(m_cursor, m_cursor); } } // Move cursor to end (or beginning) of selected word if (m_view->selection()) { #if !defined(Q_OS_OSX) QApplication::clipboard()->setText(m_view->selectionText(), QClipboard::Selection); #endif } moveCursorToSelectionEdge(); m_possibleTripleClick = true; QTimer::singleShot(QApplication::doubleClickInterval(), this, SLOT(tripleClickTimeout())); m_scrollX = 0; m_scrollY = 0; m_scrollTimer.start(50); e->accept(); break; default: e->ignore(); break; } } void KateViewInternal::tripleClickTimeout() { m_possibleTripleClick = false; } void KateViewInternal::beginSelectLine(const QPoint &pos) { placeCursor(pos); m_possibleTripleClick = true; // set so subsequent mousePressEvent will select line } void KateViewInternal::mouseReleaseEvent(QMouseEvent *e) { switch (e->button()) { case Qt::LeftButton: m_selectionMode = Default; // m_selectionCached.start().setLine( -1 ); if (m_selChangedByUser) { if (m_view->selection()) { QApplication::clipboard()->setText(m_view->selectionText(), QClipboard::Selection); } moveCursorToSelectionEdge(); m_selChangedByUser = false; } if (m_dragInfo.state == diPending) { placeCursor(e->pos(), e->modifiers() & Qt::ShiftModifier); } else if (m_dragInfo.state == diNone) { m_scrollTimer.stop(); } m_dragInfo.state = diNone; e->accept(); break; case Qt::MidButton: placeCursor(e->pos()); if (doc()->isReadWrite()) { QString clipboard = QApplication::clipboard()->text(QClipboard::Selection); m_view->paste(&clipboard); } e->accept(); break; default: e->ignore(); break; } } void KateViewInternal::leaveEvent(QEvent *) { m_textHintTimer.stop(); // fix bug 194452, scrolling keeps going if you scroll via mouse drag and press and other mouse // button outside the view area if (m_dragInfo.state == diNone) { m_scrollTimer.stop(); } } KTextEditor::Cursor KateViewInternal::coordinatesToCursor(const QPoint &_coord, bool includeBorder) const { QPoint coord(_coord); KTextEditor::Cursor ret = KTextEditor::Cursor::invalid(); if (includeBorder) { coord.rx() -= m_leftBorder->width(); } coord.rx() += startX(); const KateTextLayout &thisLine = yToKateTextLayout(coord.y()); if (thisLine.isValid()) { ret = renderer()->xToCursor(thisLine, coord.x(), !m_view->wrapCursor()); } if (ret.column() > view()->document()->lineLength(ret.line())) { // The cursor is beyond the end of the line; in that case the renderer // gives the index of the character behind the last one. return KTextEditor::Cursor::invalid(); } return ret; } void KateViewInternal::mouseMoveEvent(QMouseEvent *e) { KTextEditor::Cursor newPosition = coordinatesToCursor(e->pos(), false); if (newPosition != m_mouse) { m_mouse = newPosition; mouseMoved(); } if (e->buttons() & Qt::LeftButton) { if (m_dragInfo.state == diPending) { // we had a mouse down, but haven't confirmed a drag yet // if the mouse has moved sufficiently, we will confirm QPoint p(e->pos() - m_dragInfo.start); // we've left the drag square, we can start a real drag operation now if (p.manhattanLength() > QApplication::startDragDistance()) { doDrag(); } return; } else if (m_dragInfo.state == diDragging) { // Don't do anything after a canceled drag until the user lets go of // the mouse button! return; } m_mouseX = e->x(); m_mouseY = e->y(); m_scrollX = 0; m_scrollY = 0; int d = renderer()->lineHeight(); if (m_mouseX < 0) { m_scrollX = -d; } if (m_mouseX > width()) { m_scrollX = d; } if (m_mouseY < 0) { m_mouseY = 0; m_scrollY = -d; } if (m_mouseY > height()) { m_mouseY = height(); m_scrollY = d; } placeCursor(QPoint(m_mouseX, m_mouseY), true); } else { if (isTargetSelected(e->pos())) { // mouse is over selected text. indicate that the text is draggable by setting // the arrow cursor as other Qt text editing widgets do if (m_mouseCursor != Qt::ArrowCursor) { m_mouseCursor = Qt::ArrowCursor; setCursor(m_mouseCursor); } } else { // normal text cursor if (m_mouseCursor != Qt::IBeamCursor) { m_mouseCursor = Qt::IBeamCursor; setCursor(m_mouseCursor); } } //We need to check whether the mouse position is actually within the widget, //because other widgets like the icon border forward their events to this, //and we will create invalid text hint requests if we don't check if (textHintsEnabled() && geometry().contains(parentWidget()->mapFromGlobal(e->globalPos()))) { if (QToolTip::isVisible()) { QToolTip::hideText(); } m_textHintTimer.start(m_textHintDelay); m_textHintPos = e->pos(); } } } void KateViewInternal::updateDirty() { const int h = renderer()->lineHeight(); int currentRectStart = -1; int currentRectEnd = -1; QRegion updateRegion; { for (int i = 0; i < cache()->viewCacheLineCount(); ++i) { if (cache()->viewLine(i).isDirty()) { if (currentRectStart == -1) { currentRectStart = h * i; currentRectEnd = h; } else { currentRectEnd += h; } } else if (currentRectStart != -1) { updateRegion += QRect(0, currentRectStart, width(), currentRectEnd); currentRectStart = -1; currentRectEnd = -1; } } } if (currentRectStart != -1) { updateRegion += QRect(0, currentRectStart, width(), currentRectEnd); } if (!updateRegion.isEmpty()) { if (debugPainting) { qCDebug(LOG_KTE) << "Update dirty region " << updateRegion; } update(updateRegion); } } void KateViewInternal::hideEvent(QHideEvent *e) { Q_UNUSED(e); if (m_view->isCompletionActive()) { m_view->completionWidget()->abortCompletion(); } } void KateViewInternal::paintEvent(QPaintEvent *e) { if (debugPainting) { qCDebug(LOG_KTE) << "GOT PAINT EVENT: Region" << e->region(); } const QRect &unionRect = e->rect(); int xStart = startX() + unionRect.x(); int xEnd = xStart + unionRect.width(); uint h = renderer()->lineHeight(); uint startz = (unionRect.y() / h); uint endz = startz + 1 + (unionRect.height() / h); uint lineRangesSize = cache()->viewCacheLineCount(); const KTextEditor::Cursor pos = m_cursor; QPainter paint(this); paint.setRenderHints(QPainter::Antialiasing); paint.save(); renderer()->setCaretStyle(m_currentInputMode->caretStyle()); renderer()->setShowTabs(doc()->config()->showTabs()); renderer()->setShowTrailingSpaces(doc()->config()->showSpaces()); renderer()->updateMarkerSize(); int sy = startz * h; paint.translate(unionRect.x(), startz * h); for (uint z = startz; z <= endz; z++) { paint.save(); if ((z >= lineRangesSize) || (cache()->viewLine(z).line() == -1)) { if (!(z >= lineRangesSize)) { cache()->viewLine(z).setDirty(false); } paint.fillRect(0, 0, unionRect.width(), h, renderer()->config()->backgroundColor()); } else { //qCDebug(LOG_KTE)<<"KateViewInternal::paintEvent(QPaintEvent *e):cache()->viewLine"<viewLine(z); /* If viewLine() returns non-zero, then a document line was split in several visual lines, and we're trying to paint visual line that is not the first. In that case, this line was already painted previously, since KateRenderer::paintTextLine paints all visual lines. Except if we're at the start of the region that needs to be painted -- when no previous calls to paintTextLine were made. */ if (!thisLine.viewLine() || z == startz) { //qDebug() << "paint text: line: " << thisLine.line() << " viewLine " << thisLine.viewLine() << " x: " << unionRect.x() << " y: " << unionRect.y() << " width: " << xEnd-xStart << " height: " << h << endl; // first: paint our line paint.translate(QPoint(0, h * - thisLine.viewLine())); paint.setClipRect(QRect(0, 0, unionRect.width(), h * thisLine.kateLineLayout()->viewLineCount())); renderer()->paintTextLine(paint, thisLine.kateLineLayout(), xStart, xEnd, &pos); paint.translate(0, h * thisLine.viewLine()); // second: paint previous line elements, that span into our line like _, bug 335079 if (z > 0) { KateTextLayout &previousLine = cache()->viewLine(z-1); paint.translate(QPoint(0, h * - (previousLine.viewLine() + 1))); renderer()->paintTextLine(paint, previousLine.kateLineLayout(), xStart, xEnd, &pos); paint.translate(0, h * (previousLine.viewLine() + 1)); } /** * line painted, reset and state + mark line as non-dirty */ thisLine.setDirty(false); } } paint.restore(); paint.translate(0, h); sy += h; } paint.restore(); if (m_textAnimation) { m_textAnimation->draw(paint); } } void KateViewInternal::resizeEvent(QResizeEvent *e) { bool expandedHorizontally = width() > e->oldSize().width(); bool expandedVertically = height() > e->oldSize().height(); bool heightChanged = height() != e->oldSize().height(); m_dummy->setFixedSize(m_lineScroll->width(), m_columnScroll->sizeHint().height()); m_madeVisible = false; if (heightChanged) { setAutoCenterLines(m_autoCenterLines, false); m_cachedMaxStartPos.setPosition(-1, -1); } if (m_view->dynWordWrap()) { bool dirtied = false; for (int i = 0; i < cache()->viewCacheLineCount(); i++) { // find the first dirty line // the word wrap updateView algorithm is forced to check all lines after a dirty one KateTextLayout viewLine = cache()->viewLine(i); if (viewLine.wrap() || viewLine.isRightToLeft() || viewLine.width() > width()) { dirtied = true; viewLine.setDirty(); break; } } if (dirtied || heightChanged) { updateView(true); m_leftBorder->update(); } } else { updateView(); if (expandedHorizontally && startX() > 0) { scrollColumns(startX() - (width() - e->oldSize().width())); } } if (width() < e->oldSize().width() && !m_view->wrapCursor()) { // May have to restrain cursor to new smaller width... if (m_cursor.column() > doc()->lineLength(m_cursor.line())) { KateTextLayout thisLine = currentLayout(); KTextEditor::Cursor newCursor(m_cursor.line(), thisLine.endCol() + ((width() - thisLine.xOffset() - (thisLine.width() - m_startX)) / renderer()->spaceWidth()) - 1); if (newCursor.column() < m_cursor.column()) { updateCursor(newCursor); } } } if (expandedVertically) { KTextEditor::Cursor max = maxStartPos(); if (startPos() > max) { scrollPos(max); return; // already fired displayRangeChanged } } emit m_view->displayRangeChanged(m_view); } void KateViewInternal::scrollTimeout() { if (m_scrollX || m_scrollY) { scrollLines(startPos().line() + (m_scrollY / (int) renderer()->lineHeight())); placeCursor(QPoint(m_mouseX, m_mouseY), true); } } void KateViewInternal::cursorTimeout() { if (!debugPainting && m_currentInputMode->blinkCaret()) { renderer()->setDrawCaret(!renderer()->drawCaret()); paintCursor(); } } void KateViewInternal::textHintTimeout() { m_textHintTimer.stop(); KTextEditor::Cursor c = coordinatesToCursor(m_textHintPos, false); if (!c.isValid()) { return; } QStringList textHints; foreach(KTextEditor::TextHintProvider * const p, m_textHintProviders) { const QString hint = p->textHint(m_view, c); if (!hint.isEmpty()) { textHints.append(hint); } } if (!textHints.isEmpty()) { qCDebug(LOG_KTE) << "Hint text: " << textHints; QString hint; foreach(const QString & str, textHints) { hint += QStringLiteral("

%1

").arg(str); } QPoint pos(startX() + m_textHintPos.x(), m_textHintPos.y()); QToolTip::showText(mapToGlobal(pos), hint); } } void KateViewInternal::focusInEvent(QFocusEvent *) { if (QApplication::cursorFlashTime() > 0) { m_cursorTimer.start(QApplication::cursorFlashTime() / 2); } paintCursor(); doc()->setActiveView(m_view); // this will handle focus stuff in kateview m_view->slotGotFocus(); } void KateViewInternal::focusOutEvent(QFocusEvent *) { //if (m_view->isCompletionActive()) //m_view->abortCompletion(); m_cursorTimer.stop(); m_view->renderer()->setDrawCaret(true); paintCursor(); m_textHintTimer.stop(); m_view->slotLostFocus(); } void KateViewInternal::doDrag() { m_dragInfo.state = diDragging; m_dragInfo.dragObject = new QDrag(this); QMimeData *mimeData = new QMimeData(); mimeData->setText(m_view->selectionText()); m_dragInfo.dragObject->setMimeData(mimeData); m_dragInfo.dragObject->start(Qt::MoveAction); } void KateViewInternal::dragEnterEvent(QDragEnterEvent *event) { if (event->source() == this) { event->setDropAction(Qt::MoveAction); } event->setAccepted((event->mimeData()->hasText() && doc()->isReadWrite()) || event->mimeData()->hasUrls()); } void KateViewInternal::fixDropEvent(QDropEvent *event) { if (event->source() != this) { event->setDropAction(Qt::CopyAction); } else { Qt::DropAction action = Qt::MoveAction; #ifdef Q_WS_MAC if (event->keyboardModifiers() & Qt::AltModifier) { action = Qt::CopyAction; } #else if (event->keyboardModifiers() & Qt::ControlModifier) { action = Qt::CopyAction; } #endif event->setDropAction(action); } } void KateViewInternal::dragMoveEvent(QDragMoveEvent *event) { // track the cursor to the current drop location placeCursor(event->pos(), true, false); // important: accept action to switch between copy and move mode // without this, the text will always be copied. fixDropEvent(event); } void KateViewInternal::dropEvent(QDropEvent *event) { /** * if we have urls, pass this event off to the hosting application */ if (event->mimeData()->hasUrls()) { emit dropEventPass(event); return; } if (event->mimeData()->hasText() && doc()->isReadWrite()) { const QString text = event->mimeData()->text(); // is the source our own document? bool priv = false; if (KateViewInternal *vi = qobject_cast(event->source())) { priv = doc()->ownedView(vi->m_view); } // dropped on a text selection area? bool selected = m_view->cursorSelected(m_cursor); fixDropEvent(event); if (priv && selected && event->dropAction() != Qt::CopyAction) { // this is a drag that we started and dropped on our selection // ignore this case return; } // fix the cursor position before editStart(), so that it is correctly // stored for the undo action KTextEditor::Cursor targetCursor(m_cursor); // backup current cursor int selectionWidth = m_view->selectionRange().columnWidth(); // for block selection int selectionHeight = m_view->selectionRange().numberOfLines(); // for block selection if (event->dropAction() != Qt::CopyAction) { editSetCursor(m_view->selectionRange().end()); } else { m_view->clearSelection(); } // use one transaction doc()->editStart(); // on move: remove selected text; on copy: duplicate text doc()->insertText(targetCursor, text, m_view->blockSelection()); KTextEditor::DocumentCursor startCursor(doc(), targetCursor); KTextEditor::DocumentCursor endCursor1(doc(), targetCursor); const int textLength = text.length(); if (event->dropAction() != Qt::CopyAction) { m_view->removeSelectedText(); if (m_cursor.toCursor() < startCursor.toCursor()) { startCursor.move(-textLength); endCursor1.move(-textLength); } } if (!m_view->blockSelection()) { endCursor1.move(textLength); } else { endCursor1.setColumn(startCursor.column() + selectionWidth); endCursor1.setLine(startCursor.line() + selectionHeight); } KTextEditor::Cursor endCursor(endCursor1); qCDebug(LOG_KTE) << startCursor << "---(" << textLength << ")---" << endCursor; setSelection(KTextEditor::Range(startCursor, endCursor)); editSetCursor(endCursor); doc()->editEnd(); event->acceptProposedAction(); updateView(); } // finally finish drag and drop mode m_dragInfo.state = diNone; // important, because the eventFilter`s DragLeave does not occur stopDragScroll(); } //END EVENT HANDLING STUFF void KateViewInternal::clear() { m_startPos.setPosition(0, 0); m_displayCursor = KTextEditor::Cursor(0, 0); m_cursor.setPosition(0, 0); cache()->clear(); updateView(true); } void KateViewInternal::wheelEvent(QWheelEvent *e) { // check if this event should change the font size (Ctrl pressed, angle reported and not accidentally so) // Note: if detectZoomingEvent() doesn't unset the ControlModifier we'll get accelerated scrolling. if (m_zoomEventFilter->detectZoomingEvent(e)) { if (e->angleDelta().y() > 0) { slotIncFontSizes(qreal(e->angleDelta().y()) / QWheelEvent::DefaultDeltasPerStep); } else if (e->angleDelta().y() < 0) { slotDecFontSizes(qreal(-e->angleDelta().y()) / QWheelEvent::DefaultDeltasPerStep); } // accept always and be done for zooming e->accept(); return; } // handle vertical scrolling via the scrollbar if (e->orientation() == Qt::Vertical) { QWheelEvent copy = *e; QApplication::sendEvent(m_lineScroll, ©); if (copy.isAccepted()) { e->accept(); } } // handle horizontal scrolling via the scrollbar if (e->orientation() == Qt::Horizontal) { // if we have dyn word wrap, we should ignore the scroll events if (m_view->dynWordWrap()) { e->accept(); return; } QWheelEvent copy = *e; QApplication::sendEvent(m_columnScroll, ©); if (copy.isAccepted()) { e->accept(); } } } void KateViewInternal::startDragScroll() { if (!m_dragScrollTimer.isActive()) { m_dragScrollTimer.start(s_scrollTime); } } void KateViewInternal::stopDragScroll() { m_dragScrollTimer.stop(); updateView(); } void KateViewInternal::doDragScroll() { QPoint p = this->mapFromGlobal(QCursor::pos()); int dx = 0, dy = 0; if (p.y() < s_scrollMargin) { dy = p.y() - s_scrollMargin; } else if (p.y() > height() - s_scrollMargin) { dy = s_scrollMargin - (height() - p.y()); } if (p.x() < s_scrollMargin) { dx = p.x() - s_scrollMargin; } else if (p.x() > width() - s_scrollMargin) { dx = s_scrollMargin - (width() - p.x()); } dy /= 4; if (dy) { scrollLines(startPos().line() + dy); } if (columnScrollingPossible() && dx) { scrollColumns(qMin(m_startX + dx, m_columnScroll->maximum())); } if (!dy && !dx) { stopDragScroll(); } } void KateViewInternal::registerTextHintProvider(KTextEditor::TextHintProvider *provider) { if (! m_textHintProviders.contains(provider)) { m_textHintProviders.append(provider); } // we have a client, so start timeout m_textHintTimer.start(m_textHintDelay); } void KateViewInternal::unregisterTextHintProvider(KTextEditor::TextHintProvider *provider) { const int index = m_textHintProviders.indexOf(provider); if (index >= 0) { m_textHintProviders.removeAt(index); } if (m_textHintProviders.isEmpty()) { m_textHintTimer.stop(); } } void KateViewInternal::setTextHintDelay(int delay) { if (delay <= 0) { m_textHintDelay = 200; // ms } else { m_textHintDelay = delay; // ms } } int KateViewInternal::textHintDelay() const { return m_textHintDelay; } bool KateViewInternal::textHintsEnabled() { return ! m_textHintProviders.isEmpty(); } //BEGIN EDIT STUFF void KateViewInternal::editStart() { editSessionNumber++; if (editSessionNumber > 1) { return; } editIsRunning = true; editOldCursor = m_cursor; editOldSelection = m_view->selectionRange(); } void KateViewInternal::editEnd(int editTagLineStart, int editTagLineEnd, bool tagFrom) { if (editSessionNumber == 0) { return; } editSessionNumber--; if (editSessionNumber > 0) { return; } // fix start position, might have moved from column 0 // try to clever calculate the right start column for the tricky dyn word wrap case int col = 0; if (m_view->dynWordWrap()) { if (KateLineLayoutPtr layout = cache()->line(m_startPos.line())) { int index = layout->viewLineForColumn(m_startPos.column()); if (index >= 0 && index < layout->viewLineCount()) { col = layout->viewLine(index).startCol(); } } } m_startPos.setPosition(m_startPos.line(), col); if (tagFrom && (editTagLineStart <= int(m_view->textFolding().visibleLineToLine(startLine())))) { tagAll(); } else { tagLines(editTagLineStart, tagFrom ? qMax(doc()->lastLine() + 1, editTagLineEnd) : editTagLineEnd, true); } if (editOldCursor == m_cursor.toCursor()) { updateBracketMarks(); } updateView(true); if (editOldCursor != m_cursor.toCursor() || m_view == doc()->activeView()) { // Only scroll the view to the cursor if the insertion happens at the cursor. // This might not be the case for e.g. collaborative editing, when a remote user // inserts text at a position not at the caret. if (m_cursor.line() >= editTagLineStart && m_cursor.line() <= editTagLineEnd) { m_madeVisible = false; updateCursor(m_cursor, true); } } /** * selection changed? * fixes bug 316226 */ if (editOldSelection != m_view->selectionRange() || (editOldSelection.isValid() && !editOldSelection.isEmpty() && !(editTagLineStart > editOldSelection.end().line() && editTagLineEnd < editOldSelection.start().line()))) { emit m_view->selectionChanged(m_view); } editIsRunning = false; } void KateViewInternal::editSetCursor(const KTextEditor::Cursor &_cursor) { if (m_cursor.toCursor() != _cursor) { m_cursor.setPosition(_cursor); } } //END void KateViewInternal::viewSelectionChanged() { if (!m_view->selection()) { m_selectAnchor = KTextEditor::Cursor::invalid(); } else { m_selectAnchor = m_view->selectionRange().start(); } // Do NOT nuke the entire range! The reason is that a shift+DC selection // might (correctly) set the range to be empty (i.e. start() == end()), and // subsequent dragging might shrink the selection into non-existence. When // this happens, we use the cached end to restore the cached start so that // updateSelection is not confused. See also comments in updateSelection. m_selectionCached.setStart(KTextEditor::Cursor::invalid()); } KateLayoutCache *KateViewInternal::cache() const { return m_layoutCache; } KTextEditor::Cursor KateViewInternal::toRealCursor(const KTextEditor::Cursor &virtualCursor) const { return KTextEditor::Cursor(m_view->textFolding().visibleLineToLine(virtualCursor.line()), virtualCursor.column()); } KTextEditor::Cursor KateViewInternal::toVirtualCursor(const KTextEditor::Cursor &realCursor) const { /** * only convert valid lines, folding doesn't like invalid input! * don't validate whole cursor, column might be -1 */ if (realCursor.line() < 0) { return KTextEditor::Cursor::invalid(); } return KTextEditor::Cursor(m_view->textFolding().lineToVisibleLine(realCursor.line()), realCursor.column()); } KateRenderer *KateViewInternal::renderer() const { return m_view->renderer(); } void KateViewInternal::mouseMoved() { m_view->notifyMousePositionChanged(m_mouse); m_view->updateRangesIn(KTextEditor::Attribute::ActivateMouseIn); } void KateViewInternal::cursorMoved() { m_view->updateRangesIn(KTextEditor::Attribute::ActivateCaretIn); #ifndef QT_NO_ACCESSIBILITY if (QAccessible::isActive()) { QAccessibleTextCursorEvent ev(this, static_cast(QAccessible::queryAccessibleInterface(this))->positionFromCursor(this, m_cursor)); QAccessible::updateAccessibility(&ev); } #endif } bool KateViewInternal::rangeAffectsView(const KTextEditor::Range &range, bool realCursors) const { int startLine = m_startPos.line(); int endLine = startLine + (int)m_visibleLineCount; if (realCursors) { startLine = (int)m_view->textFolding().visibleLineToLine(startLine); endLine = (int)m_view->textFolding().visibleLineToLine(endLine); } return (range.end().line() >= startLine) || (range.start().line() <= endLine); } //BEGIN IM INPUT STUFF QVariant KateViewInternal::inputMethodQuery(Qt::InputMethodQuery query) const { switch (query) { case Qt::ImCursorRectangle: { // Cursor placement code is changed for Asian input method that // shows candidate window. This behavior is same as Qt/E 2.3.7 // which supports Asian input methods. Asian input methods need // start point of IM selection text to place candidate window as // adjacent to the selection text. // // in Qt5, cursor rectangle is used as QRectF internally, and it // will be checked by QRectF::isValid(), which will mark rectangle // with width == 0 or height == 0 as invalid. auto lineHeight = renderer()->lineHeight(); return QRect(cursorToCoordinate(m_cursor, true, false), QSize(1, lineHeight ? lineHeight : 1)); } case Qt::ImFont: return renderer()->currentFont(); case Qt::ImCursorPosition: return m_cursor.column(); case Qt::ImAnchorPosition: // If selectAnchor is at the same line, return the real anchor position // Otherwise return the same position of cursor if (m_view->selection() && m_selectAnchor.line() == m_cursor.line()) { return m_selectAnchor.column(); } else { return m_cursor.column(); } case Qt::ImSurroundingText: if (Kate::TextLine l = doc()->kateTextLine(m_cursor.line())) { return l->string(); } else { return QString(); } case Qt::ImCurrentSelection: if (m_view->selection()) { return m_view->selectionText(); } else { return QString(); } default: /* values: ImMaximumTextLength */ break; } return QWidget::inputMethodQuery(query); } void KateViewInternal::inputMethodEvent(QInputMethodEvent *e) { if (doc()->readOnly()) { e->ignore(); return; } //qCDebug(LOG_KTE) << "Event: cursor" << m_cursor << "commit" << e->commitString() << "preedit" << e->preeditString() << "replacement start" << e->replacementStart() << "length" << e->replacementLength(); if (!m_imPreeditRange) { m_imPreeditRange = doc()->newMovingRange(KTextEditor::Range(m_cursor, m_cursor), KTextEditor::MovingRange::ExpandLeft | KTextEditor::MovingRange::ExpandRight); } if (!m_imPreeditRange->toRange().isEmpty()) { doc()->inputMethodStart(); doc()->removeText(*m_imPreeditRange); doc()->inputMethodEnd(); } if (!e->commitString().isEmpty() || e->replacementLength()) { m_view->removeSelectedText(); KTextEditor::Range preeditRange = *m_imPreeditRange; KTextEditor::Cursor start(m_imPreeditRange->start().line(), m_imPreeditRange->start().column() + e->replacementStart()); KTextEditor::Cursor removeEnd = start + KTextEditor::Cursor(0, e->replacementLength()); doc()->editStart(); if (start != removeEnd) { doc()->removeText(KTextEditor::Range(start, removeEnd)); } if (!e->commitString().isEmpty()) { // if the input method event is text that should be inserted, call KTextEditor::DocumentPrivate::typeChars() // with the text. that method will handle the input and take care of overwrite mode, etc. doc()->typeChars(m_view, e->commitString()); } doc()->editEnd(); // Revert to the same range as above m_imPreeditRange->setRange(preeditRange); } if (!e->preeditString().isEmpty()) { doc()->inputMethodStart(); doc()->insertText(m_imPreeditRange->start(), e->preeditString()); doc()->inputMethodEnd(); // The preedit range gets automatically repositioned } // Finished this input method context? if (m_imPreeditRange && e->preeditString().isEmpty()) { // delete the range and reset the pointer delete m_imPreeditRange; m_imPreeditRange = nullptr; qDeleteAll(m_imPreeditRangeChildren); m_imPreeditRangeChildren.clear(); if (QApplication::cursorFlashTime() > 0) { renderer()->setDrawCaret(false); } renderer()->setCaretOverrideColor(QColor()); e->accept(); return; } KTextEditor::Cursor newCursor = m_cursor; bool hideCursor = false; QColor caretColor; if (m_imPreeditRange) { qDeleteAll(m_imPreeditRangeChildren); m_imPreeditRangeChildren.clear(); int decorationColumn = 0; foreach (const QInputMethodEvent::Attribute &a, e->attributes()) { if (a.type == QInputMethodEvent::Cursor) { newCursor = m_imPreeditRange->start() + KTextEditor::Cursor(0, a.start); hideCursor = !a.length; QColor c = qvariant_cast(a.value); if (c.isValid()) { caretColor = c; } } else if (a.type == QInputMethodEvent::TextFormat) { QTextCharFormat f = qvariant_cast(a.value).toCharFormat(); if (f.isValid() && decorationColumn <= a.start) { KTextEditor::Range fr(m_imPreeditRange->start().line(), m_imPreeditRange->start().column() + a.start, m_imPreeditRange->start().line(), m_imPreeditRange->start().column() + a.start + a.length); KTextEditor::MovingRange *formatRange = doc()->newMovingRange(fr); KTextEditor::Attribute::Ptr attribute(new KTextEditor::Attribute()); attribute->merge(f); formatRange->setAttribute(attribute); decorationColumn = a.start + a.length; m_imPreeditRangeChildren.push_back(formatRange); } } } } renderer()->setDrawCaret(hideCursor); renderer()->setCaretOverrideColor(caretColor); if (newCursor != m_cursor.toCursor()) { updateCursor(newCursor); } e->accept(); } //END IM INPUT STUFF void KateViewInternal::flashChar(const KTextEditor::Cursor &pos, KTextEditor::Attribute::Ptr attribute) { Q_ASSERT(pos.isValid()); Q_ASSERT(attribute.constData()); // if line is folded away, do nothing if (!m_view->textFolding().isLineVisible(pos.line())) { return; } KTextEditor::Range range(pos, KTextEditor::Cursor(pos.line(), pos.column() + 1)); if (m_textAnimation) { m_textAnimation->deleteLater(); } m_textAnimation = new KateTextAnimation(range, attribute, this); } void KateViewInternal::documentTextInserted(KTextEditor::Document *document, const KTextEditor::Range &range) { #ifndef QT_NO_ACCESSIBILITY if (QAccessible::isActive()) { QAccessibleTextInsertEvent ev(this, static_cast(QAccessible::queryAccessibleInterface(this))->positionFromCursor(this, range.start()), document->text(range)); QAccessible::updateAccessibility(&ev); } #endif } void KateViewInternal::documentTextRemoved(KTextEditor::Document * /*document*/, const KTextEditor::Range &range, const QString &oldText) { #ifndef QT_NO_ACCESSIBILITY if (QAccessible::isActive()) { QAccessibleTextRemoveEvent ev(this, static_cast(QAccessible::queryAccessibleInterface(this))->positionFromCursor(this, range.start()), oldText); QAccessible::updateAccessibility(&ev); } #endif } diff --git a/src/view/kateviewinternal.h b/src/view/kateviewinternal.h index 45a32fa5..642cac47 100644 --- a/src/view/kateviewinternal.h +++ b/src/view/kateviewinternal.h @@ -1,471 +1,471 @@ /* This file is part of the KDE libraries Copyright (C) 2002-2007 Hamish Rodda Copyright (C) 2002 John Firebaugh Copyright (C) 2002 Joseph Wenninger Copyright (C) 2002 Christoph Cullmann Copyright (C) 2007 Mirko Stocker Based on: KWriteView : Copyright (C) 1999 Jochen Wilhelmy This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. 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. 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. */ #ifndef _KATE_VIEW_INTERNAL_ #define _KATE_VIEW_INTERNAL_ #include #include "katetextcursor.h" #include "katetextline.h" #include "katedocument.h" #include "kateview.h" #include "katerenderer.h" #include #include #include #include #include #include #include #include namespace KTextEditor { class MovingRange; class TextHintProvider; } class KateIconBorder; class KateScrollBar; class KateTextLayout; class KateTextAnimation; class KateAbstractInputMode; class ZoomEventFilter; class QScrollBar; class KateViewInternal : public QWidget { Q_OBJECT friend class KTextEditor::ViewPrivate; friend class KateIconBorder; friend class KateScrollBar; friend class CalculatingCursor; friend class BoundedCursor; friend class WrappingCursor; friend class KateAbstractInputMode; friend class ::KateTextPreview; public: enum Bias { left = -1, none = 0, right = 1 }; public: KateViewInternal(KTextEditor::ViewPrivate *view); - ~KateViewInternal() Q_DECL_OVERRIDE; + ~KateViewInternal() override; KTextEditor::ViewPrivate *view() const { return m_view; } //BEGIN EDIT STUFF public: void editStart(); void editEnd(int editTagLineStart, int editTagLineEnd, bool tagFrom); void editSetCursor(const KTextEditor::Cursor &cursor); private: uint editSessionNumber; bool editIsRunning; KTextEditor::Cursor editOldCursor; KTextEditor::Range editOldSelection; //END //BEGIN TAG & CLEAR & UPDATE STUFF public: bool tagLine(const KTextEditor::Cursor &virtualCursor); bool tagLines(int start, int end, bool realLines = false); // cursors not const references as they are manipulated within bool tagLines(KTextEditor::Cursor start, KTextEditor::Cursor end, bool realCursors = false); bool tagRange(const KTextEditor::Range &range, bool realCursors); void tagAll(); void updateDirty(); void clear(); //END private Q_SLOTS: // Updates the view and requests a redraw. void updateView(bool changed = false, int viewLinesScrolled = 0); private: // Actually performs the updating, but doesn't call update(). void doUpdateView(bool changed = false, int viewLinesScrolled = 0); void makeVisible(const KTextEditor::Cursor &c, int endCol, bool force = false, bool center = false, bool calledExternally = false); public: // Start Position is a virtual cursor KTextEditor::Cursor startPos() const { return m_startPos; } int startLine() const { return m_startPos.line(); } int startX() const { return m_startX; } KTextEditor::Cursor endPos() const; int endLine() const; KateTextLayout yToKateTextLayout(int y) const; void prepareForDynWrapChange(); void dynWrapChanged(); public Q_SLOTS: void slotIncFontSizes(qreal step = 1.0); void slotDecFontSizes(qreal step = 1.0); void paintCursor(); private Q_SLOTS: void scrollLines(int line); // connected to the sliderMoved of the m_lineScroll void scrollViewLines(int offset); void scrollAction(int action); void scrollNextPage(); void scrollPrevPage(); void scrollPrevLine(); void scrollNextLine(); void scrollColumns(int x); // connected to the valueChanged of the m_columnScroll void viewSelectionChanged(); public: void doReturn(); void doSmartNewline(); void doDelete(); void doBackspace(); void doTabulator(); void doTranspose(); void doDeletePrevWord(); void doDeleteNextWord(); void cursorPrevChar(bool sel = false); void cursorNextChar(bool sel = false); void wordPrev(bool sel = false); void wordNext(bool sel = false); void home(bool sel = false); void end(bool sel = false); void cursorUp(bool sel = false); void cursorDown(bool sel = false); void cursorToMatchingBracket(bool sel = false); void scrollUp(); void scrollDown(); void topOfView(bool sel = false); void bottomOfView(bool sel = false); void pageUp(bool sel = false, bool half = false); void pageDown(bool sel = false, bool half = false); void top(bool sel = false); void bottom(bool sel = false); void top_home(bool sel = false); void bottom_end(bool sel = false); KTextEditor::Cursor getCursor() const { return m_cursor; } KTextEditor::Cursor getMouse() const { return m_mouse; } QPoint cursorToCoordinate(const KTextEditor::Cursor &cursor, bool realCursor = true, bool includeBorder = true) const; // by default, works on coordinates of the whole widget, eg. offsetted by the border KTextEditor::Cursor coordinatesToCursor(const QPoint &coord, bool includeBorder = true) const; QPoint cursorCoordinates(bool includeBorder = true) const; KTextEditor::Cursor findMatchingBracket(); KateIconBorder *iconBorder() const { return m_leftBorder; } // EVENT HANDLING STUFF - IMPORTANT private: void fixDropEvent(QDropEvent *event); protected: - void hideEvent(QHideEvent *e) Q_DECL_OVERRIDE; - void paintEvent(QPaintEvent *e) Q_DECL_OVERRIDE; - bool eventFilter(QObject *obj, QEvent *e) Q_DECL_OVERRIDE; - void keyPressEvent(QKeyEvent *) Q_DECL_OVERRIDE; - void keyReleaseEvent(QKeyEvent *) Q_DECL_OVERRIDE; - void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE; - void mousePressEvent(QMouseEvent *) Q_DECL_OVERRIDE; - void mouseDoubleClickEvent(QMouseEvent *) Q_DECL_OVERRIDE; - void mouseReleaseEvent(QMouseEvent *) Q_DECL_OVERRIDE; - void mouseMoveEvent(QMouseEvent *) Q_DECL_OVERRIDE; - void leaveEvent(QEvent *) Q_DECL_OVERRIDE; - void dragEnterEvent(QDragEnterEvent *) Q_DECL_OVERRIDE; - void dragMoveEvent(QDragMoveEvent *) Q_DECL_OVERRIDE; - void dropEvent(QDropEvent *) Q_DECL_OVERRIDE; - void showEvent(QShowEvent *) Q_DECL_OVERRIDE; - void wheelEvent(QWheelEvent *e) Q_DECL_OVERRIDE; - void focusInEvent(QFocusEvent *) Q_DECL_OVERRIDE; - void focusOutEvent(QFocusEvent *) Q_DECL_OVERRIDE; - void inputMethodEvent(QInputMethodEvent *e) Q_DECL_OVERRIDE; - - void contextMenuEvent(QContextMenuEvent *e) Q_DECL_OVERRIDE; + void hideEvent(QHideEvent *e) override; + void paintEvent(QPaintEvent *e) override; + bool eventFilter(QObject *obj, QEvent *e) override; + void keyPressEvent(QKeyEvent *) override; + void keyReleaseEvent(QKeyEvent *) override; + void resizeEvent(QResizeEvent *) override; + void mousePressEvent(QMouseEvent *) override; + void mouseDoubleClickEvent(QMouseEvent *) override; + void mouseReleaseEvent(QMouseEvent *) override; + void mouseMoveEvent(QMouseEvent *) override; + void leaveEvent(QEvent *) override; + void dragEnterEvent(QDragEnterEvent *) override; + void dragMoveEvent(QDragMoveEvent *) override; + void dropEvent(QDropEvent *) override; + void showEvent(QShowEvent *) override; + void wheelEvent(QWheelEvent *e) override; + void focusInEvent(QFocusEvent *) override; + void focusOutEvent(QFocusEvent *) override; + void inputMethodEvent(QInputMethodEvent *e) override; + + void contextMenuEvent(QContextMenuEvent *e) override; private Q_SLOTS: void tripleClickTimeout(); Q_SIGNALS: // emitted when KateViewInternal is not handling its own URI drops void dropEventPass(QDropEvent *); private Q_SLOTS: void slotRegionVisibilityChanged(); void slotRegionBeginEndAddedRemoved(unsigned int); private: void moveChar(Bias bias, bool sel); void moveEdge(Bias bias, bool sel); KTextEditor::Cursor maxStartPos(bool changed = false); void scrollPos(KTextEditor::Cursor &c, bool force = false, bool calledExternally = false, bool emitSignals = true); void scrollLines(int lines, bool sel); int linesDisplayed() const; int lineToY(int viewLine) const; void updateSelection(const KTextEditor::Cursor &, bool keepSel); void setSelection(const KTextEditor::Range &); void moveCursorToSelectionEdge(); void updateCursor(const KTextEditor::Cursor &newCursor, bool force = false, bool center = false, bool calledExternally = false); void updateBracketMarks(); void beginSelectLine(const QPoint &pos); void placeCursor(const QPoint &p, bool keepSelection = false, bool updateSelection = true); bool isTargetSelected(const QPoint &p); //Returns whether the given range affects the area currently visible in the view bool rangeAffectsView(const KTextEditor::Range &range, bool realCursors) const; void doDrag(); KateRenderer *renderer() const; KTextEditor::ViewPrivate *m_view; class KateIconBorder *m_leftBorder; int m_mouseX; int m_mouseY; int m_scrollX; int m_scrollY; ZoomEventFilter *m_zoomEventFilter; Qt::CursorShape m_mouseCursor; Kate::TextCursor m_cursor; KTextEditor::Cursor m_mouse; KTextEditor::Cursor m_displayCursor; bool m_possibleTripleClick; //Whether the current completion-item was expanded while the last press of ALT bool m_completionItemExpanded; QElapsedTimer m_altDownTime; // Bracket mark and corresponding decorative ranges KTextEditor::MovingRange *m_bm, *m_bmStart, *m_bmEnd; KTextEditor::MovingCursor *m_bmLastFlashPos; void updateBracketMarkAttributes(); enum DragState { diNone, diPending, diDragging }; struct _dragInfo { DragState state; QPoint start; QDrag *dragObject; } m_dragInfo; // // line scrollbar + first visible (virtual) line in the current view // KateScrollBar *m_lineScroll; QWidget *m_dummy; // These are now cursors to account for word-wrap. // Start Position is a virtual cursor Kate::TextCursor m_startPos; //Count of lines that are visible behind m_startPos. //This does not respect dynamic word wrap, so take it as an approximation. uint m_visibleLineCount; // This is set to false on resize or scroll (other than that called by makeVisible), // so that makeVisible is again called when a key is pressed and the cursor is in the same spot bool m_madeVisible; bool m_shiftKeyPressed; // How many lines to should be kept visible above/below the cursor when possible void setAutoCenterLines(int viewLines, bool updateView = true); int m_autoCenterLines; int m_minLinesVisible; // // column scrollbar + x position // QScrollBar *m_columnScroll; int m_startX; // has selection changed while your mouse or shift key is pressed bool m_selChangedByUser; KTextEditor::Cursor m_selectAnchor; enum SelectionMode { Default = 0, Mouse, Word, Line }; ///< for drag selection. uint m_selectionMode; // when drag selecting after double/triple click, keep the initial selected // word/line independent of direction. // They get set in the event of a double click, and is used with mouse move + leftbutton KTextEditor::Range m_selectionCached; // maximal length of textlines visible from given startLine int maxLen(int startLine); // are we allowed to scroll columns? bool columnScrollingPossible(); // the same for lines bool lineScrollingPossible(); // returns the maximum X value / col value a cursor can take for a specific line range int lineMaxCursorX(const KateTextLayout &line); int lineMaxCol(const KateTextLayout &line); class KateLayoutCache *cache() const; KateLayoutCache *m_layoutCache; // convenience methods KateTextLayout currentLayout() const; KateTextLayout previousLayout() const; KateTextLayout nextLayout() const; // find the cursor offset by (offset) view lines from a cursor. // when keepX is true, the column position will be calculated based on the x // position of the specified cursor. KTextEditor::Cursor viewLineOffset(const KTextEditor::Cursor &virtualCursor, int offset, bool keepX = false); KTextEditor::Cursor toRealCursor(const KTextEditor::Cursor &virtualCursor) const; KTextEditor::Cursor toVirtualCursor(const KTextEditor::Cursor &realCursor) const; // These variable holds the most recent maximum real & visible column number bool m_preserveX; int m_preservedX; int m_wrapChangeViewLine; KTextEditor::Cursor m_cachedMaxStartPos; // // implementation details for KTextEditor::FlashTextInterface // public: void flashChar(const KTextEditor::Cursor &pos, KTextEditor::Attribute::Ptr attribute); private: QPointer m_textAnimation; private Q_SLOTS: void doDragScroll(); void startDragScroll(); void stopDragScroll(); private: // Timers QTimer m_dragScrollTimer; QTimer m_scrollTimer; QTimer m_cursorTimer; QTimer m_textHintTimer; static const int s_scrollTime = 30; static const int s_scrollMargin = 16; private Q_SLOTS: void scrollTimeout(); void cursorTimeout(); void textHintTimeout(); void documentTextInserted(KTextEditor::Document *document, const KTextEditor::Range &range); void documentTextRemoved(KTextEditor::Document *document, const KTextEditor::Range &range, const QString &oldText); // // KTE::TextHintInterface // public: void registerTextHintProvider(KTextEditor::TextHintProvider *provider); void unregisterTextHintProvider(KTextEditor::TextHintProvider *provider); void setTextHintDelay(int delay); int textHintDelay() const; bool textHintsEnabled(); // not part of the interface private: QVector m_textHintProviders; int m_textHintDelay; QPoint m_textHintPos; // // IM input stuff // public: - QVariant inputMethodQuery(Qt::InputMethodQuery query) const Q_DECL_OVERRIDE; + QVariant inputMethodQuery(Qt::InputMethodQuery query) const override; private: KTextEditor::MovingRange *m_imPreeditRange; QList m_imPreeditRangeChildren; private: void mouseMoved(); void cursorMoved(); private: inline KTextEditor::DocumentPrivate *doc() { return m_view->doc(); } inline KTextEditor::DocumentPrivate *doc() const { return m_view->doc(); } // input modes private: QMap m_inputModes; KateAbstractInputMode *m_currentInputMode; }; #endif diff --git a/src/vimode/appcommands.h b/src/vimode/appcommands.h index 459c8b6c..a24a6889 100644 --- a/src/vimode/appcommands.h +++ b/src/vimode/appcommands.h @@ -1,119 +1,119 @@ /* This file is part of the KDE libraries Copyright (C) 2009 Erlend Hamberg Copyright (C) 2011 Svyatoslav Kuzmich 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. 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. 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. */ #ifndef KATEVI_APP_COMMANDS_H #define KATEVI_APP_COMMANDS_H #include #include namespace KTextEditor { class MainWindow; } namespace KateVi { class AppCommands : public KTextEditor::Command { Q_OBJECT AppCommands(); static AppCommands* m_instance; public: - ~AppCommands() Q_DECL_OVERRIDE; - bool exec(KTextEditor::View *view, const QString &cmd, QString &msg, const KTextEditor::Range &range = KTextEditor::Range::invalid()) Q_DECL_OVERRIDE; - bool help(KTextEditor::View *view, const QString &cmd, QString &msg) Q_DECL_OVERRIDE; + ~AppCommands() override; + bool exec(KTextEditor::View *view, const QString &cmd, QString &msg, const KTextEditor::Range &range = KTextEditor::Range::invalid()) override; + bool help(KTextEditor::View *view, const QString &cmd, QString &msg) override; static AppCommands* self() { if (m_instance == nullptr) { m_instance = new AppCommands(); } return m_instance; } private: /** * @returns a view in the given \p window that does not share a split * view with the given \p view. If such view could not be found, then * nullptr is returned. */ KTextEditor::View * findViewInDifferentSplitView(KTextEditor::MainWindow *window, KTextEditor::View *view); private Q_SLOTS: void closeCurrentDocument(); void closeCurrentView(); void closeCurrentSplitView(); void closeOtherSplitViews(); void quit(); private: QRegExp re_write; QRegExp re_close; QRegExp re_quit; QRegExp re_exit; QRegExp re_edit; QRegExp re_tabedit; QRegExp re_new; QRegExp re_split; QRegExp re_vsplit; QRegExp re_vclose; QRegExp re_only; }; class BufferCommands : public KTextEditor::Command { Q_OBJECT BufferCommands(); static BufferCommands* m_instance; public: - ~BufferCommands() Q_DECL_OVERRIDE; - bool exec(KTextEditor::View *view, const QString &cmd, QString &msg, const KTextEditor::Range &range = KTextEditor::Range::invalid()) Q_DECL_OVERRIDE; - bool help(KTextEditor::View *view, const QString &cmd, QString &msg) Q_DECL_OVERRIDE; + ~BufferCommands() override; + bool exec(KTextEditor::View *view, const QString &cmd, QString &msg, const KTextEditor::Range &range = KTextEditor::Range::invalid()) override; + bool help(KTextEditor::View *view, const QString &cmd, QString &msg) override; static BufferCommands* self() { if (m_instance == nullptr) { m_instance = new BufferCommands(); } return m_instance; } private: void switchDocument(KTextEditor::View *, const QString &doc); void prevBuffer(KTextEditor::View *); void nextBuffer(KTextEditor::View *); void firstBuffer(KTextEditor::View *); void lastBuffer(KTextEditor::View *); void prevTab(KTextEditor::View *); void nextTab(KTextEditor::View *); void firstTab(KTextEditor::View *); void lastTab(KTextEditor::View *); void activateDocument(KTextEditor::View *, KTextEditor::Document *); QList documents(); }; } #endif /* KATEVI_APP_COMMANDS_H */ diff --git a/src/vimode/cmds.h b/src/vimode/cmds.h index 5d6c423b..41c006fb 100644 --- a/src/vimode/cmds.h +++ b/src/vimode/cmds.h @@ -1,125 +1,125 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2003-2005 Anders Lund * Copyright (C) 2001-2010 Christoph Cullmann * Copyright (C) 2001 Charles Samuels * * 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. * * 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. * * 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. */ #ifndef KATEVI_COMMANDS_H #define KATEVI_COMMANDS_H #include #include "kateregexpsearch.h" #include #include #include "mappings.h" #include namespace KTextEditor { class DocumentPrivate; } class KCompletion; namespace KateVi { /** * This KTextEditor::Command provides vi 'ex' commands */ class Commands : public KTextEditor::Command, public KateViCommandInterface { Commands() : KTextEditor::Command (QStringList() << mappingCommands() << QStringLiteral("d") << QStringLiteral("delete") << QStringLiteral("j") << QStringLiteral("c") << QStringLiteral("change") << QStringLiteral("<") << QStringLiteral(">") << QStringLiteral("y") << QStringLiteral("yank") << QStringLiteral("ma") << QStringLiteral("mark") << QStringLiteral("k")) { } static Commands *m_instance; public: - ~Commands() Q_DECL_OVERRIDE + ~Commands() override { m_instance = nullptr; } /** * execute command on given range * @param view view to use for execution * @param cmd cmd string * @param msg message returned from running the command * @param range range to execute command on * @return success */ bool exec(class KTextEditor::View *view, const QString &cmd, QString &msg, - const KTextEditor::Range &range = KTextEditor::Range(-1, -0, -1, 0)) Q_DECL_OVERRIDE; + const KTextEditor::Range &range = KTextEditor::Range(-1, -0, -1, 0)) override; - bool supportsRange(const QString &range) Q_DECL_OVERRIDE; + bool supportsRange(const QString &range) override; /** This command does not have help. @see KTextEditor::Command::help */ - bool help(class KTextEditor::View *, const QString &, QString &) Q_DECL_OVERRIDE + bool help(class KTextEditor::View *, const QString &, QString &) override { return false; } /** * Reimplement from KTextEditor::Command */ - KCompletion *completionObject(KTextEditor::View *, const QString &) Q_DECL_OVERRIDE; + KCompletion *completionObject(KTextEditor::View *, const QString &) override; static Commands *self() { if (m_instance == nullptr) { m_instance = new Commands(); } return m_instance; } private: const QStringList &mappingCommands(); Mappings::MappingMode modeForMapCommand(const QString &mapCommand); bool isMapCommandRecursive(const QString &mapCommand); }; /** * Support vim/sed style search and replace * @author Charles Samuels **/ class SedReplace : public KateCommands::SedReplace, public KateViCommandInterface { SedReplace() { } static SedReplace *m_instance; public: - ~SedReplace() Q_DECL_OVERRIDE + ~SedReplace() override { m_instance = nullptr; } static SedReplace *self() { if (m_instance == nullptr) { m_instance = new SedReplace(); } return m_instance; } protected: - bool interactiveSedReplace(KTextEditor::ViewPrivate *kateView, QSharedPointer interactiveSedReplace) Q_DECL_OVERRIDE; + bool interactiveSedReplace(KTextEditor::ViewPrivate *kateView, QSharedPointer interactiveSedReplace) override; }; } #endif /* KATEVI_COMMANDS_H */ diff --git a/src/vimode/config/configtab.h b/src/vimode/config/configtab.h index 6e914203..77ce3b2f 100644 --- a/src/vimode/config/configtab.h +++ b/src/vimode/config/configtab.h @@ -1,67 +1,67 @@ /* This file is part of the KDE libraries and the Kate part. * * 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. * * 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. * * 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. */ #ifndef KATEVI_CONFIG_TAB_H #define KATEVI_CONFIG_TAB_H #include #include class QTableWidget; namespace KateVi { namespace Ui { class ConfigWidget; } class ConfigTab : public KateConfigPage { Q_OBJECT public: explicit ConfigTab(QWidget *parent, Mappings *mappings); - ~ConfigTab() Q_DECL_OVERRIDE; + ~ConfigTab() override; - QString name() const Q_DECL_OVERRIDE; + QString name() const override; protected: Ui::ConfigWidget *ui; private: void applyTab(QTableWidget *mappingsTable, Mappings::MappingMode mode); void reloadTab(QTableWidget *mappingsTable, Mappings::MappingMode mode); public Q_SLOTS: - void apply() Q_DECL_OVERRIDE; - void reload() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE; - void defaults() Q_DECL_OVERRIDE; + void apply() override; + void reload() override; + void reset() override; + void defaults() override; private Q_SLOTS: void showWhatsThis(const QString &text); void addMappingRow(); void removeSelectedMappingRows(); void importNormalMappingRow(); private: Mappings *m_mappings; }; } #endif /* KATEVI_CONFIG_TAB_H */ diff --git a/src/vimode/emulatedcommandbar/commandmode.h b/src/vimode/emulatedcommandbar/commandmode.h index 4ab62e1e..b0ef1efd 100644 --- a/src/vimode/emulatedcommandbar/commandmode.h +++ b/src/vimode/emulatedcommandbar/commandmode.h @@ -1,97 +1,97 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2013-2016 Simon St James * * 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. * * 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. * * 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. */ #ifndef KATEVI_EMULATED_COMMAND_BAR_COMMANDMODE_H #define KATEVI_EMULATED_COMMAND_BAR_COMMANDMODE_H #include "activemode.h" #include #include namespace KTextEditor { class ViewPrivate; } namespace KateVi { class EmulatedCommandBar; class MatchHighlighter; class InteractiveSedReplaceMode; class Completer; class InputModeManager; class CommandMode : public ActiveMode { public: CommandMode(EmulatedCommandBar* emulatedCommandBar, MatchHighlighter* matchHighlighter, InputModeManager* viInputModeManager, KTextEditor::ViewPrivate* view, QLineEdit* edit, InteractiveSedReplaceMode *interactiveSedReplaceMode, Completer* completer); virtual ~CommandMode() { } - bool handleKeyPress ( const QKeyEvent* keyEvent ) Q_DECL_OVERRIDE; - void editTextChanged(const QString &newText) Q_DECL_OVERRIDE; - CompletionStartParams completionInvoked(Completer::CompletionInvocation invocationType) Q_DECL_OVERRIDE; - void completionChosen() Q_DECL_OVERRIDE; - void deactivate(bool wasAborted) Q_DECL_OVERRIDE; + bool handleKeyPress ( const QKeyEvent* keyEvent ) override; + void editTextChanged(const QString &newText) override; + CompletionStartParams completionInvoked(Completer::CompletionInvocation invocationType) override; + void completionChosen() override; + void deactivate(bool wasAborted) override; QString executeCommand(const QString &commandToExecute); private: CompletionStartParams activateCommandCompletion(); CompletionStartParams activateCommandHistoryCompletion(); CompletionStartParams activateSedFindHistoryCompletion(); CompletionStartParams activateSedReplaceHistoryCompletion(); QString withoutRangeExpression(); QString rangeExpression(); QString withSedFindTermReplacedWith(const QString &newFindTerm); QString withSedDelimiterEscaped(const QString &text); bool isCursorInFindTermOfSed(); bool isCursorInReplaceTermOfSed(); QString sedFindTerm(); QString sedReplaceTerm(); /** * Stuff to do with expressions of the form: * * s/find/replace/ */ struct ParsedSedExpression { bool parsedSuccessfully; int findBeginPos; int findEndPos; int replaceBeginPos; int replaceEndPos; QChar delimiter; }; /** * The "range expression" is the (optional) expression before the command that describes * the range over which the command should be run e.g. '<,'>. @see CommandRangeExpressionParser */ CommandMode::ParsedSedExpression parseAsSedExpression(); void replaceCommandBeforeCursorWith(const QString &newCommand); int commandBeforeCursorBegin(); QLineEdit *m_edit; InteractiveSedReplaceMode *m_interactiveSedReplaceMode; Completer *m_completer; KCompletion m_cmdCompletion; QHash m_cmdDict; KTextEditor::Command *queryCommand(const QString &cmd) const; }; } #endif diff --git a/src/vimode/emulatedcommandbar/emulatedcommandbar.h b/src/vimode/emulatedcommandbar/emulatedcommandbar.h index 72bb6cce..8bab15aa 100644 --- a/src/vimode/emulatedcommandbar/emulatedcommandbar.h +++ b/src/vimode/emulatedcommandbar/emulatedcommandbar.h @@ -1,131 +1,131 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2013-2016 Simon St James * * 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. * * 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. * * 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. */ #ifndef KATEVI_EMULATED_COMMAND_BAR_H #define KATEVI_EMULATED_COMMAND_BAR_H #include "kateviewhelpers.h" #include #include #include #include "../searcher.h" #include "activemode.h" namespace KTextEditor { class ViewPrivate; class Command; } class QLabel; class QLayout; namespace KateVi { class MatchHighlighter; class InteractiveSedReplaceMode; class SearchMode; class CommandMode; /** * A KateViewBarWidget that attempts to emulate some of the features of Vim's own command bar, * including insertion of register contents via ctr-r; dismissal via * ctrl-c and ctrl-[; bi-directional incremental searching, with SmartCase; interactive sed-replace; * plus a few extensions such as completion from document and navigable sed search and sed replace history. */ class KTEXTEDITOR_EXPORT EmulatedCommandBar : public KateViewBarWidget { Q_OBJECT public: enum Mode { NoMode, SearchForward, SearchBackward, Command }; explicit EmulatedCommandBar(KateViInputMode* viInputMode, InputModeManager *viInputModeManager, QWidget *parent = nullptr); - ~EmulatedCommandBar() Q_DECL_OVERRIDE; + ~EmulatedCommandBar() override; void init(Mode mode, const QString &initialText = QString()); bool isActive(); void setCommandResponseMessageTimeout(long commandResponseMessageTimeOutMS); bool handleKeyPress(const QKeyEvent *keyEvent); bool isSendingSyntheticSearchCompletedKeypress(); void startInteractiveSearchAndReplace(QSharedPointer interactiveSedReplace); QString executeCommand(const QString &commandToExecute); void setViInputModeManager(InputModeManager *viInputModeManager); private: KateViInputMode *m_viInputMode; InputModeManager *m_viInputModeManager; bool m_isActive = false; bool m_wasAborted = true; Mode m_mode = NoMode; KTextEditor::ViewPrivate *m_view = nullptr; QLineEdit *m_edit = nullptr; QLabel *m_barTypeIndicator = nullptr; void showBarTypeIndicator(Mode mode); bool m_suspendEditEventFiltering = false; bool m_waitingForRegister = false ; QLabel *m_waitingForRegisterIndicator; bool m_insertedTextShouldBeEscapedForSearchingAsLiteral = false; void hideAllWidgetsExcept(QWidget* widgetToKeepVisible); friend class ActiveMode; QScopedPointer m_matchHighligher; QScopedPointer m_completer; QScopedPointer m_interactiveSedReplaceMode; QScopedPointer m_searchMode; QScopedPointer m_commandMode; void switchToMode(ActiveMode *newMode); ActiveMode *m_currentMode = nullptr; bool barHandledKeypress(const QKeyEvent* keyEvent); void insertRegisterContents(const QKeyEvent *keyEvent); - bool eventFilter(QObject *object, QEvent *event) Q_DECL_OVERRIDE; + bool eventFilter(QObject *object, QEvent *event) override; void deleteSpacesToLeftOfCursor(); void deleteWordCharsToLeftOfCursor(); bool deleteNonWordCharsToLeftOfCursor(); - void closed() Q_DECL_OVERRIDE; + void closed() override; void closeWithStatusMessage(const QString& exitStatusMessage); QTimer *m_exitStatusMessageDisplayHideTimer; QLabel *m_exitStatusMessageDisplay; long m_exitStatusMessageHideTimeOutMS = 4000; void createAndAddBarTypeIndicator(QLayout* layout); void createAndAddEditWidget(QLayout* layout); void createAndAddExitStatusMessageDisplay(QLayout* layout); void createAndInitExitStatusMessageDisplayTimer(); void createAndAddWaitingForRegisterIndicator(QLayout* layout); private Q_SLOTS: void editTextChanged(const QString &newText); void startHideExitStatusMessageTimer(); }; } #endif /* KATEVI_EMULATED_COMMAND_BAR_H */ diff --git a/src/vimode/emulatedcommandbar/interactivesedreplacemode.h b/src/vimode/emulatedcommandbar/interactivesedreplacemode.h index 81520109..c8ab319c 100644 --- a/src/vimode/emulatedcommandbar/interactivesedreplacemode.h +++ b/src/vimode/emulatedcommandbar/interactivesedreplacemode.h @@ -1,62 +1,62 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2013-2016 Simon St James * * 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. * * 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. * * 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. */ #ifndef KATEVI_EMULATED_COMMAND_BAR_INTERACTIVESEDREPLACEMODE_H #define KATEVI_EMULATED_COMMAND_BAR_INTERACTIVESEDREPLACEMODE_H #include "activemode.h" #include "../cmds.h" #include class QKeyEvent; class QLabel; namespace KateVi { class EmulatedCommandBar; class MatchHighlighter; class InteractiveSedReplaceMode : public ActiveMode { public: InteractiveSedReplaceMode(EmulatedCommandBar* emulatedCommandBar, MatchHighlighter* matchHighlighter, InputModeManager* viInputModeManager, KTextEditor::ViewPrivate* view); - ~InteractiveSedReplaceMode() Q_DECL_OVERRIDE + ~InteractiveSedReplaceMode() override { } void activate(QSharedPointer interactiveSedReplace); bool isActive() const { return m_isActive; } - bool handleKeyPress(const QKeyEvent* keyEvent) Q_DECL_OVERRIDE; - void deactivate(bool wasAborted) Q_DECL_OVERRIDE; + bool handleKeyPress(const QKeyEvent* keyEvent) override; + void deactivate(bool wasAborted) override; QWidget *label(); private: void updateInteractiveSedReplaceLabelText(); void finishInteractiveSedReplace(); QSharedPointer m_interactiveSedReplacer; bool m_isActive; QLabel *m_interactiveSedReplaceLabel; }; } #endif diff --git a/src/vimode/emulatedcommandbar/searchmode.h b/src/vimode/emulatedcommandbar/searchmode.h index cfa15225..08da74d5 100644 --- a/src/vimode/emulatedcommandbar/searchmode.h +++ b/src/vimode/emulatedcommandbar/searchmode.h @@ -1,71 +1,71 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2013-2016 Simon St James * * 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. * * 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. * * 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. */ #ifndef KATEVI_EMULATED_COMMAND_BAR_SEARCHMODE_H #define KATEVI_EMULATED_COMMAND_BAR_SEARCHMODE_H #include "activemode.h" #include "../searcher.h" namespace KTextEditor { class ViewPrivate; } #include namespace KateVi { class EmulatedCommandBar; QString vimRegexToQtRegexPattern(const QString &vimRegexPattern); // TODO - move these generic helper functions into their own file? QString withCaseSensitivityMarkersStripped(const QString &originalSearchTerm); QString ensuredCharEscaped(const QString &originalString, QChar charToEscape); QStringList reversed(const QStringList &originalList); class SearchMode : public ActiveMode { public: SearchMode(EmulatedCommandBar* emulatedCommandBar, MatchHighlighter* matchHighlighter, InputModeManager* viInputModeManager, KTextEditor::ViewPrivate* view, QLineEdit* edit); - ~SearchMode() Q_DECL_OVERRIDE + ~SearchMode() override { } enum class SearchDirection { Forward, Backward }; void init(SearchDirection); - bool handleKeyPress ( const QKeyEvent* keyEvent ) Q_DECL_OVERRIDE; - void editTextChanged(const QString &newText) Q_DECL_OVERRIDE; - CompletionStartParams completionInvoked(Completer::CompletionInvocation invocationType) Q_DECL_OVERRIDE; - void completionChosen() Q_DECL_OVERRIDE; - void deactivate(bool wasAborted) Q_DECL_OVERRIDE; + bool handleKeyPress ( const QKeyEvent* keyEvent ) override; + void editTextChanged(const QString &newText) override; + CompletionStartParams completionInvoked(Completer::CompletionInvocation invocationType) override; + void completionChosen() override; + void deactivate(bool wasAborted) override; bool isSendingSyntheticSearchCompletedKeypress() const { return m_isSendingSyntheticSearchCompletedKeypress; } private: QLineEdit *m_edit = nullptr; SearchDirection m_searchDirection; KTextEditor::Cursor m_startingCursorPos; KateVi::Searcher::SearchParams m_currentSearchParams; CompletionStartParams activateSearchHistoryCompletion(); enum BarBackgroundStatus { Normal, MatchFound, NoMatchFound }; void setBarBackground(BarBackgroundStatus status); bool m_isSendingSyntheticSearchCompletedKeypress = false; }; } #endif diff --git a/src/vimode/modes/insertvimode.h b/src/vimode/modes/insertvimode.h index e4850e96..ca79f82a 100644 --- a/src/vimode/modes/insertvimode.h +++ b/src/vimode/modes/insertvimode.h @@ -1,120 +1,120 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2008-2011 Erlend Hamberg * Copyright (C) 2011 Svyatoslav Kuzmich * Copyright (C) 2012 - 2013 Simon St James * * 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. * * 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. * * 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. */ #ifndef KATEVI_INSERT_VI_MODE_H #define KATEVI_INSERT_VI_MODE_H #include #include namespace KTextEditor { class ViewPrivate; } class KateViewInternal; class QKeyEvent; namespace KateVi { class Motion; /** * Commands for the vi insert mode */ enum BlockInsert { None, Prepend, Append, AppendEOL }; class KTEXTEDITOR_EXPORT InsertViMode : public ModeBase { Q_OBJECT public: explicit InsertViMode(InputModeManager *viInputModeManager, KTextEditor::ViewPrivate *view, KateViewInternal *viewInternal); - ~InsertViMode() Q_DECL_OVERRIDE; + ~InsertViMode() override; - bool handleKeypress(const QKeyEvent *e) Q_DECL_OVERRIDE; + bool handleKeypress(const QKeyEvent *e) override; bool commandInsertFromAbove(); bool commandInsertFromBelow(); bool commandDeleteWord(); bool commandDeleteLine(); bool commandNewLine(); bool commandDeleteCharBackward(); bool commandIndent(); bool commandUnindent(); bool commandToFirstCharacterInFile(); bool commandToLastCharacterInFile(); bool commandMoveOneWordLeft(); bool commandMoveOneWordRight(); bool commandCompleteNext(); bool commandCompletePrevious(); bool commandInsertContentOfRegister(); bool commandSwitchToNormalModeForJustOneCommand(); void setBlockPrependMode(Range blockRange); void setBlockAppendMode(Range blockRange, BlockInsert b); void setCount(int count) { m_count = count; } void setCountedRepeatsBeginOnNewLine(bool countedRepeatsBeginOnNewLine) { m_countedRepeatsBeginOnNewLine = countedRepeatsBeginOnNewLine; } protected: void leaveInsertMode(bool force = false); void completionFinished(); protected: BlockInsert m_blockInsert; unsigned int m_eolPos; // length of first line in eol mode before text is appended Range m_blockRange; QString m_keys; bool m_waitingRegister; unsigned int m_count; bool m_countedRepeatsBeginOnNewLine; bool m_isExecutingCompletion; QString m_textInsertedByCompletion; KTextEditor::Cursor m_textInsertedByCompletionEndPos; private Q_SLOTS: void textInserted(KTextEditor::Document *document, KTextEditor::Range range); }; } #endif /* KATEVI_INSERT_VI_MODE_H */ diff --git a/src/vimode/modes/normalvimode.h b/src/vimode/modes/normalvimode.h index 1406af8d..35dda322 100644 --- a/src/vimode/modes/normalvimode.h +++ b/src/vimode/modes/normalvimode.h @@ -1,398 +1,398 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2008 - 2009 Erlend Hamberg * Copyright (C) 2009 Paul Gideon Dann * Copyright (C) 2011 Svyatoslav Kuzmich * Copyright (C) 2012 - 2013 Simon St James * * 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. * * 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. * * 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. */ #ifndef KATEVI_NORMAL_VI_MODE_H #define KATEVI_NORMAL_VI_MODE_H #include #include #include #include #include #include #include #include class QKeyEvent; class KateViInputMode; namespace KateVi { class Command; class Motion; class KeyParser; class InputModeManager; /** * Commands for the vi normal mode */ class KTEXTEDITOR_EXPORT NormalViMode : public ModeBase { Q_OBJECT friend KateViInputMode; public: explicit NormalViMode(InputModeManager *viInputModeManager, KTextEditor::ViewPrivate *view, KateViewInternal *viewInternal); - ~NormalViMode() Q_DECL_OVERRIDE; + ~NormalViMode() override; - bool handleKeypress(const QKeyEvent *e) Q_DECL_OVERRIDE; + bool handleKeypress(const QKeyEvent *e) override; bool commandEnterInsertMode(); bool commandEnterInsertModeAppend(); bool commandEnterInsertModeAppendEOL(); bool commandEnterInsertModeBeforeFirstNonBlankInLine(); bool commandEnterInsertModeLast(); bool commandEnterVisualMode(); bool commandEnterVisualLineMode(); bool commandEnterVisualBlockMode(); bool commandReselectVisual(); bool commandToOtherEnd(); bool commandEnterReplaceMode(); bool commandDelete(); bool commandDeleteToEOL(); bool commandDeleteLine(); bool commandMakeLowercase(); bool commandMakeLowercaseLine(); bool commandMakeUppercase(); bool commandMakeUppercaseLine(); bool commandChangeCase(); bool commandChangeCaseRange(); bool commandChangeCaseLine(); bool commandOpenNewLineUnder(); bool commandOpenNewLineOver(); bool commandJoinLines(); bool commandChange(); bool commandChangeLine(); bool commandChangeToEOL(); bool commandSubstituteChar(); bool commandSubstituteLine(); bool commandYank(); bool commandYankLine(); bool commandYankToEOL(); bool commandPaste(); bool commandPasteBefore(); bool commandgPaste(); bool commandgPasteBefore(); bool commandIndentedPaste(); bool commandIndentedPasteBefore(); bool commandDeleteChar(); bool commandDeleteCharBackward(); bool commandReplaceCharacter(); bool commandSwitchToCmdLine(); bool commandSearchBackward(); bool commandSearchForward(); bool commandUndo(); bool commandRedo(); bool commandSetMark(); bool commandIndentLine(); bool commandUnindentLine(); bool commandIndentLines(); bool commandUnindentLines(); bool commandScrollPageDown(); bool commandScrollPageUp(); bool commandScrollHalfPageUp(); bool commandScrollHalfPageDown(); bool commandCenterView(bool onFirst); bool commandCenterViewOnNonBlank(); bool commandCenterViewOnCursor(); bool commandTopView(bool onFirst); bool commandTopViewOnNonBlank(); bool commandTopViewOnCursor(); bool commandBottomView(bool onFirst); bool commandBottomViewOnNonBlank(); bool commandBottomViewOnCursor(); bool commandAbort(); bool commandPrintCharacterCode(); bool commandRepeatLastChange(); bool commandAlignLine(); bool commandAlignLines(); bool commandAddToNumber(); bool commandSubtractFromNumber(); bool commandPrependToBlock(); bool commandAppendToBlock(); bool commandGoToNextJump(); bool commandGoToPrevJump(); bool commandSwitchToLeftView(); bool commandSwitchToUpView(); bool commandSwitchToDownView(); bool commandSwitchToRightView(); bool commandSwitchToNextView(); bool commandSplitHoriz(); bool commandSplitVert(); bool commandCloseView(); bool commandSwitchToNextTab(); bool commandSwitchToPrevTab(); bool commandFormatLine(); bool commandFormatLines(); bool commandCollapseToplevelNodes(); bool commandCollapseLocal(); bool commandExpandAll(); bool commandExpandLocal(); bool commandToggleRegionVisibility(); bool commandStartRecordingMacro(); bool commandReplayMacro(); bool commandCloseWrite(); bool commandCloseNocheck(); // MOTIONS Range motionLeft(); Range motionRight(); Range motionDown(); Range motionUp(); Range motionPageDown(); Range motionPageUp(); Range motionHalfPageDown(); Range motionHalfPageUp(); Range motionUpToFirstNonBlank(); Range motionDownToFirstNonBlank(); Range motionWordForward(); Range motionWordBackward(); Range motionWORDForward(); Range motionWORDBackward(); Range motionToEndOfWord(); Range motionToEndOfWORD(); Range motionToEndOfPrevWord(); Range motionToEndOfPrevWORD(); Range motionFindChar(); Range motionFindCharBackward(); Range motionToChar(); Range motionToCharBackward(); Range motionRepeatlastTF(); Range motionRepeatlastTFBackward(); Range motionToEOL(); Range motionToColumn0(); Range motionToFirstCharacterOfLine(); Range motionToLineFirst(); Range motionToLineLast(); Range motionToScreenColumn(); Range motionToMark(); Range motionToMarkLine(); Range motionToMatchingItem(); Range motionToPreviousBraceBlockStart(); Range motionToNextBraceBlockStart(); Range motionToPreviousBraceBlockEnd(); Range motionToNextBraceBlockEnd(); Range motionToNextOccurrence(); Range motionToPrevOccurrence(); Range motionToFirstLineOfWindow(); Range motionToMiddleLineOfWindow(); Range motionToLastLineOfWindow(); Range motionToNextVisualLine(); Range motionToPrevVisualLine(); Range motionToPreviousSentence(); Range motionToNextSentence(); Range motionToBeforeParagraph(); Range motionToAfterParagraph(); Range motionToIncrementalSearchMatch(); // TEXT OBJECTS Range textObjectAWord(); Range textObjectInnerWord(); Range textObjectAWORD(); Range textObjectInnerWORD(); Range textObjectInnerSentence(); Range textObjectASentence(); Range textObjectInnerParagraph(); Range textObjectAParagraph(); Range textObjectAQuoteDouble(); Range textObjectInnerQuoteDouble(); Range textObjectAQuoteSingle(); Range textObjectInnerQuoteSingle(); Range textObjectABackQuote(); Range textObjectInnerBackQuote(); Range textObjectAParen(); Range textObjectInnerParen(); Range textObjectABracket(); Range textObjectInnerBracket(); Range textObjectACurlyBracket(); Range textObjectInnerCurlyBracket(); Range textObjectAInequalitySign(); Range textObjectInnerInequalitySign(); Range textObjectAComma(); Range textObjectInnerComma(); virtual void reset(); void beginMonitoringDocumentChanges(); protected: void resetParser(); void initializeCommands(); QRegExp generateMatchingItemRegex() const; void executeCommand(const Command *cmd); OperationMode getOperationMode() const; void highlightYank(const Range &range, const OperationMode mode = CharWise); void addHighlightYank(const KTextEditor::Range &range); bool motionWillBeUsedWithCommand() const { return !m_awaitingMotionOrTextObject.isEmpty(); }; void joinLines(unsigned int from, unsigned int to) const; void reformatLines(unsigned int from, unsigned int to) const; bool executeKateCommand(const QString &command); /** * Get the index of the first non-blank character from the given line. * * @param line The line to be picked. The current line will picked instead * if this parameter is set to a negative value. * @returns the index of the first non-blank character from the given line. * If a non-space character cannot be found, the 0 is returned. */ int getFirstNonBlank(int line = -1) const; Range textObjectComma(bool inner) const; void shrinkRangeAroundCursor(Range &toShrink, const Range &rangeToShrinkTo) const; KTextEditor::Cursor findSentenceStart(); KTextEditor::Cursor findSentenceEnd(); KTextEditor::Cursor findParagraphStart(); KTextEditor::Cursor findParagraphEnd(); protected: // The 'current position' is the current cursor position for non-linewise pastes, and the current // line for linewise. enum PasteLocation { AtCurrentPosition, AfterCurrentPosition }; bool paste(NormalViMode::PasteLocation pasteLocation, bool isgPaste, bool isIndentedPaste); KTextEditor::Cursor cursorPosAtEndOfPaste(const KTextEditor::Cursor &pasteLocation, const QString &pastedText) const; protected: QString m_keys; QString m_lastTFcommand; // holds the last t/T/f/F command so that it can be repeated with ;/, unsigned int m_countTemp; int m_motionOperatorIndex; int m_scroll_count_limit; QVector m_commands; QVector m_motions; QVector m_matchingCommands; QVector m_matchingMotions; QStack m_awaitingMotionOrTextObject; bool m_findWaitingForChar; bool m_isRepeatedTFcommand; bool m_linewiseCommand; bool m_commandWithMotion; bool m_lastMotionWasLinewiseInnerBlock; bool m_motionCanChangeWholeVisualModeSelection; bool m_commandShouldKeepSelection; bool m_deleteCommand; // Ctrl-c or ESC have been pressed, leading to a call to reset(). bool m_pendingResetIsDueToExit; bool m_isUndo; bool waitingForRegisterOrCharToSearch(); // item matching ('%' motion) QHash m_matchingItems; QRegExp m_matchItemRegex; KeyParser *m_keyParser; KTextEditor::Attribute::Ptr m_highlightYankAttribute; QSet m_highlightedYanks; QSet &highlightedYankForDocument(); KTextEditor::Cursor m_currentChangeEndMarker; KTextEditor::Cursor m_positionWhenIncrementalSearchBegan; private Q_SLOTS: void textInserted(KTextEditor::Document *document, KTextEditor::Range range); void textRemoved(KTextEditor::Document *, KTextEditor::Range); void undoBeginning(); void undoEnded(); void updateYankHighlightAttrib(); void clearYankHighlight(); void aboutToDeleteMovingInterfaceContent(); }; } #endif /* KATEVI_NORMAL_VI_MODE_H */ diff --git a/src/vimode/modes/replacevimode.h b/src/vimode/modes/replacevimode.h index b50aebd6..b5ef994d 100644 --- a/src/vimode/modes/replacevimode.h +++ b/src/vimode/modes/replacevimode.h @@ -1,91 +1,91 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2008 Erlend Hamberg * * 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. * * 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. * * 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. */ #ifndef KATEVI_REPLACE_MODE_H #define KATEVI_REPLACE_MODE_H #include namespace KateVi { /** * Commands for the vi replace mode */ class ReplaceViMode : public ModeBase { public: explicit ReplaceViMode(InputModeManager *viInputModeManager, KTextEditor::ViewPrivate *view, KateViewInternal *viewInternal); - ~ReplaceViMode() Q_DECL_OVERRIDE; + ~ReplaceViMode() override; /// Update the track of overwritten characters with the \p s character. inline void overwrittenChar(const QChar &s) { m_overwritten += s; } void setCount(int count) { m_count = count;} protected: /** * Checks if the key is a valid command in replace mode. * * @returns true if a command was completed and executed, false otherwise. */ - bool handleKeypress(const QKeyEvent *e) Q_DECL_OVERRIDE; + bool handleKeypress(const QKeyEvent *e) override; private: /** * Replace the character at the current column with a character from * the same column but in a different line. * * @param offset The offset of the line to be picked. This value is * relative to the current line. * @returns true if the character could be replaced, false otherwise. */ bool commandInsertFromLine(int offset); // Auxiliar methods for moving the cursor in replace mode. bool commandMoveOneWordLeft(); bool commandMoveOneWordRight(); // Auxiliar methods for removing modifications. void backspace(); void commandBackWord(); void commandBackLine(); void leaveReplaceMode(); protected: unsigned int m_count; private: /// Keeps track of the characters that have been overwritten so far. QString m_overwritten; }; } #endif /* KATEVI_REPLACE_MODE_H */ diff --git a/src/vimode/modes/visualvimode.h b/src/vimode/modes/visualvimode.h index 6f72ec0d..bd442dbe 100644 --- a/src/vimode/modes/visualvimode.h +++ b/src/vimode/modes/visualvimode.h @@ -1,121 +1,121 @@ /* This file is part of the KDE libraries and the Kate part. * * Copyright (C) 2008 - 2009 Erlend Hamberg * Copyright (C) 2009 Paul Gideon Dann * Copyright (C) 2011 Svyatoslav Kuzmich * Copyright (C) 2012 - 2013 Simon St James * * 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. * * 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. * * 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. */ #ifndef KATEVI_VISUAL_VI_MODE_H #define KATEVI_VISUAL_VI_MODE_H #include #include namespace KateVi { class InputModeManager; class VisualViMode : public NormalViMode { Q_OBJECT public: explicit VisualViMode(InputModeManager *viInputModeManager, KTextEditor::ViewPrivate *view, KateViewInternal *viewInternal); - ~VisualViMode() Q_DECL_OVERRIDE; + ~VisualViMode() override; void init(); bool isVisualLine() const { return m_mode == VisualLineMode; } bool isVisualBlock() const { return m_mode == VisualBlockMode; } void switchStartEnd(); - void reset() Q_DECL_OVERRIDE; + void reset() override; void setVisualModeType(const ViMode mode); void saveRangeMarks(); void setStart(const KTextEditor::Cursor &c) { m_start = c; } KTextEditor::Cursor getStart() { return m_start; } void goToPos(const KTextEditor::Cursor &c); ViMode getLastVisualMode() const { return m_lastVisualMode; } const KTextEditor::Cursor &getStart() const { return m_start; } // Selects all lines in range; void selectLines(const KTextEditor::Range &range); // Selects range between c1 and c2, but includes the end cursor position. void selectInclusive(const KTextEditor::Cursor &c1, const KTextEditor::Cursor &c2); // Select block between c1 and c2. void selectBlockInclusive(const KTextEditor::Cursor &c1, const KTextEditor::Cursor &c2); protected: /** * Called when a motion/text object is used. Updates the cursor position * and modifies the range. A motion will only modify the end of the range * (i.e. move the cursor) while a text object may modify both the start and * the end. Overriden from the ModeBase class. */ - void goToPos(const Range &r) Q_DECL_OVERRIDE; + void goToPos(const Range &r) override; private: void initializeCommands(); public Q_SLOTS: /** * Updates the visual mode's range to reflect a new cursor position. This * needs to be called if modifying the range from outside the vi mode, e.g. * via mouse selection. */ void updateSelection(); private: KTextEditor::Cursor m_start; ViMode m_mode, m_lastVisualMode; }; } #endif /* KATEVI_VISUAL_VI_MODE_H */