diff --git a/CMakeLists.txt b/CMakeLists.txt index 3eec66f..e0d3645 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,94 +1,95 @@ cmake_minimum_required(VERSION 3.5) set(KF5_VERSION "5.64.0") # handled by release scripts set(KF5_DEP_VERSION "5.63.0") # handled by release scripts project(KCompletion VERSION ${KF5_VERSION}) # ECM setup include(FeatureSummary) find_package(ECM 5.63.0 NO_MODULE) set_package_properties(ECM PROPERTIES TYPE REQUIRED DESCRIPTION "Extra CMake Modules." URL "https://projects.kde.org/projects/kdesupport/extra-cmake-modules") feature_summary(WHAT REQUIRED_PACKAGES_NOT_FOUND FATAL_ON_MISSING_REQUIRED_PACKAGES) set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH}) include(KDEInstallDirs) include(KDECMakeSettings) include(KDEFrameworkCompilerSettings NO_POLICY_SCOPE) -include(GenerateExportHeader) +include(ECMGenerateExportHeader) include(ECMSetupVersion) include(ECMGenerateHeaders) include(CMakePackageConfigHelpers) include(ECMAddQch) include(ECMPoQmTools) ecm_setup_version(PROJECT VARIABLE_PREFIX KCOMPLETION VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/kcompletion_version.h" PACKAGE_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/KF5CompletionConfigVersion.cmake" SOVERSION 5) # Dependencies set(REQUIRED_QT_VERSION 5.11.0) find_package(Qt5 ${REQUIRED_QT_VERSION} NO_MODULE REQUIRED Widgets) find_package(KF5Config ${KF5_DEP_VERSION} REQUIRED) find_package(KF5WidgetsAddons ${KF5_DEP_VERSION} REQUIRED) +set(EXCLUDE_DEPRECATED_BEFORE_AND_AT 0 CACHE STRING "Control the range of deprecated API excluded from the build [default=0].") option(BUILD_QCH "Build API documentation in QCH format (for e.g. Qt Assistant, Qt Creator & KDevelop)" OFF) add_feature_info(QCH ${BUILD_QCH} "API documentation in QCH format (for e.g. Qt Assistant, Qt Creator & KDevelop)") option(BUILD_DESIGNERPLUGIN "Build plugin for Qt Designer" ON) add_feature_info(DESIGNERPLUGIN ${BUILD_DESIGNERPLUGIN} "Build plugin for Qt Designer") add_definitions(-DQT_NO_FOREACH) add_definitions(-DQT_DISABLE_DEPRECATED_BEFORE=0x050d00) if (IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/po") ecm_install_po_files_as_qm(po) endif() add_subdirectory(src) if (BUILD_TESTING) add_subdirectory(tests) add_subdirectory(autotests) endif() # create a Config.cmake and a ConfigVersion.cmake file and install them set(CMAKECONFIG_INSTALL_DIR "${KDE_INSTALL_CMAKEPACKAGEDIR}/KF5Completion") if (BUILD_QCH) ecm_install_qch_export( TARGETS KF5Completion_QCH FILE KF5CompletionQchTargets.cmake DESTINATION "${CMAKECONFIG_INSTALL_DIR}" COMPONENT Devel ) set(PACKAGE_INCLUDE_QCHTARGETS "include(\"\${CMAKE_CURRENT_LIST_DIR}/KF5CompletionQchTargets.cmake\")") endif() include(CMakePackageConfigHelpers) configure_package_config_file( "${CMAKE_CURRENT_SOURCE_DIR}/KF5CompletionConfig.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/KF5CompletionConfig.cmake" INSTALL_DESTINATION ${CMAKECONFIG_INSTALL_DIR} ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/KF5CompletionConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/KF5CompletionConfigVersion.cmake" DESTINATION "${CMAKECONFIG_INSTALL_DIR}" COMPONENT Devel ) install(EXPORT KF5CompletionTargets DESTINATION "${CMAKECONFIG_INSTALL_DIR}" FILE KF5CompletionTargets.cmake NAMESPACE KF5:: ) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/kcompletion_version.h DESTINATION ${KDE_INSTALL_INCLUDEDIR_KF5} COMPONENT Devel ) feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/autotests/klineedit_unittest.cpp b/autotests/klineedit_unittest.cpp index 78926ac..3307de3 100644 --- a/autotests/klineedit_unittest.cpp +++ b/autotests/klineedit_unittest.cpp @@ -1,300 +1,300 @@ /* This file is part of the KDE libraries Copyright (c) 2007 David Faure 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 #include #include #include #include class KLineEdit_UnitTest : public QObject { Q_OBJECT private Q_SLOTS: void testPassword() { KLineEdit w; w.setPasswordMode(true); QTest::keyClick(&w, Qt::Key_1); QTest::keyClick(&w, Qt::Key_2); QTest::keyClick(&w, Qt::Key_3); QCOMPARE(w.text(), QString("123")); } void testReturnPressed() { KLineEdit w; w.setText(QStringLiteral("Hello world")); QSignalSpy qReturnPressedSpy(&w, SIGNAL(returnPressed())); QSignalSpy kReturnPressedSpy(&w, SIGNAL(returnPressed(QString))); QTest::keyClick(&w, Qt::Key_Return); QCOMPARE(qReturnPressedSpy.count(), 1); QCOMPARE(kReturnPressedSpy.count(), 1); QCOMPARE(kReturnPressedSpy[0][0].toString(), QString("Hello world")); } void testTextEditedSignals() { KLineEdit w; QVERIFY(!w.isModified()); // setText emits textChanged and userTextChanged, but not textEdited QSignalSpy textChangedSpy(&w, SIGNAL(textChanged(QString))); QSignalSpy textEditedSpy(&w, SIGNAL(textEdited(QString))); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) QSignalSpy userTextChangedSpy(&w, SIGNAL(userTextChanged(QString))); #endif w.setText(QStringLiteral("Hello worl")); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) QCOMPARE(userTextChangedSpy.count(), 1); QCOMPARE(userTextChangedSpy[0][0].toString(), w.text()); #endif QCOMPARE(textChangedSpy.count(), 1); QCOMPARE(textChangedSpy[0][0].toString(), w.text()); QCOMPARE(textEditedSpy.count(), 0); QVERIFY(!w.isModified()); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) userTextChangedSpy.clear(); #endif textChangedSpy.clear(); textEditedSpy.clear(); // calling clear should emit textChanged and userTextChanged, but not textEdited w.clear(); QCOMPARE(textChangedSpy.count(),1); QCOMPARE(textEditedSpy.count(),0); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) QCOMPARE(userTextChangedSpy.count(),1); #endif //if text box is already empty, calling clear() shouldn't emit // any more signals w.clear(); QCOMPARE(textChangedSpy.count(),1); QCOMPARE(textEditedSpy.count(),0); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) QCOMPARE(userTextChangedSpy.count(),1); #endif //set the text back for further tests below w.setText(QStringLiteral("Hello worl")); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) userTextChangedSpy.clear(); #endif textChangedSpy.clear(); textEditedSpy.clear(); // typing emits all three signals QTest::keyClick(&w, Qt::Key_D); QCOMPARE(w.text(), QString::fromLatin1("Hello world")); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) QCOMPARE(userTextChangedSpy.count(), 1); QCOMPARE(userTextChangedSpy[0][0].toString(), w.text()); #endif QCOMPARE(textChangedSpy.count(), 1); QCOMPARE(textChangedSpy[0][0].toString(), w.text()); QCOMPARE(textEditedSpy.count(), 1); QCOMPARE(textEditedSpy[0][0].toString(), w.text()); QVERIFY(w.isModified()); w.setText(QStringLiteral("K")); // prepare for next test -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) userTextChangedSpy.clear(); #endif textChangedSpy.clear(); textEditedSpy.clear(); QVERIFY(!w.isModified()); // the suggestion from auto completion emits textChanged but not userTextChanged nor textEdited w.setCompletionMode(KCompletion::CompletionAuto); KCompletion completion; completion.setSoundsEnabled(false); QStringList items; items << QStringLiteral("KDE is cool") << QStringLiteral("KDE is really cool"); completion.setItems(items); w.setCompletionObject(&completion); w.doCompletion(w.text()); QCOMPARE(w.text(), items.at(0)); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) QCOMPARE(userTextChangedSpy.count(), 0); #endif QCOMPARE(textChangedSpy.count(), 1); QCOMPARE(textChangedSpy[0][0].toString(), w.text()); QCOMPARE(textEditedSpy.count(), 0); QVERIFY(!w.isModified()); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) userTextChangedSpy.clear(); #endif textChangedSpy.clear(); textEditedSpy.clear(); // accepting the completion suggestion now emits all three signals too QTest::keyClick(&w, Qt::Key_Right); QCOMPARE(w.text(), items.at(0)); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) QCOMPARE(userTextChangedSpy.count(), 1); QCOMPARE(userTextChangedSpy[0][0].toString(), w.text()); #endif QCOMPARE(textChangedSpy.count(), 1); QCOMPARE(textChangedSpy[0][0].toString(), w.text()); QCOMPARE(textEditedSpy.count(), 1); QCOMPARE(textEditedSpy[0][0].toString(), w.text()); QVERIFY(w.isModified()); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) userTextChangedSpy.clear(); #endif textChangedSpy.clear(); textEditedSpy.clear(); // Now with popup completion w.setCompletionMode(KCompletion::CompletionPopup); w.setText(QStringLiteral("KDE")); QVERIFY(!w.isModified()); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) userTextChangedSpy.clear(); #endif textChangedSpy.clear(); textEditedSpy.clear(); w.doCompletion(w.text()); // popup appears QCOMPARE(w.text(), QString::fromLatin1("KDE")); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) QCOMPARE(textChangedSpy.count() + userTextChangedSpy.count() + textEditedSpy.count(), 0); #else QCOMPARE(textChangedSpy.count() + textEditedSpy.count(), 0); #endif w.completionBox()->down(); // select 1st item QCOMPARE(w.text(), items.at(0)); QVERIFY(w.isModified()); w.completionBox()->down(); // select 2nd item QCOMPARE(w.text(), items.at(1)); // Selecting an item in the popup completion changes the lineedit text // and emits textChanged and userTextChanged, but not textEdited. -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) QCOMPARE(userTextChangedSpy.count(), 2); #endif QCOMPARE(textChangedSpy.count(), 2); QCOMPARE(textEditedSpy.count(), 0); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) userTextChangedSpy.clear(); #endif textChangedSpy.clear(); textEditedSpy.clear(); QTest::keyClick(&w, Qt::Key_Enter); // activate QVERIFY(!w.completionBox()->isVisible()); QCOMPARE(w.text(), items.at(1)); QVERIFY(w.isModified()); // Nothing else happens, the text was already set in the lineedit QCOMPARE(textChangedSpy.count(), 0); QCOMPARE(textEditedSpy.count(), 0); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) QCOMPARE(userTextChangedSpy.count(), 0); #endif // Now when using the mouse in the popup completion w.setText(QStringLiteral("KDE")); w.doCompletion(w.text()); // popup appears QCOMPARE(w.text(), QString::fromLatin1("KDE")); // Selecting an item in the popup completion changes the lineedit text and emits all 3 signals const QRect rect = w.completionBox()->visualRect(w.completionBox()->model()->index(1, 0)); QSignalSpy activatedSpy(w.completionBox(), SIGNAL(activated(QString))); QTest::mouseClick(w.completionBox()->viewport(), Qt::LeftButton, Qt::NoModifier, rect.center()); QCOMPARE(activatedSpy.count(), 1); QCOMPARE(w.text(), items.at(1)); QVERIFY(w.isModified()); } void testCompletionBox() { KLineEdit w; w.setText(QStringLiteral("/")); w.setCompletionMode(KCompletion::CompletionPopup); KCompletion completion; completion.setSoundsEnabled(false); w.setCompletionObject(&completion); QStringList items; items << QStringLiteral("/home/") << QStringLiteral("/hold/") << QStringLiteral("/hole/"); completion.setItems(items); QTest::keyClick(&w, 'h'); QCOMPARE(w.text(), QString::fromLatin1("/h")); QCOMPARE(w.completionBox()->currentRow(), -1); QCOMPARE(w.completionBox()->items(), items); QTest::keyClick(&w, 'o'); QCOMPARE(w.text(), QString::fromLatin1("/ho")); QCOMPARE(w.completionBox()->currentRow(), -1); w.completionBox()->down(); // select 1st item QCOMPARE(w.text(), items.at(0)); w.completionBox()->down(); // select 2nd item QCOMPARE(w.text(), items.at(1)); w.completionBox()->up(); // select 1st item again QCOMPARE(w.text(), items.at(0)); w.completionBox()->up(); // select last item QCOMPARE(w.text(), items.at(2)); w.completionBox()->down(); // select 1st item again QCOMPARE(w.text(), items.at(0)); QStringList newItems; newItems << QStringLiteral("/home/kde"); completion.setItems(newItems); QTest::keyClick(&w, 'k'); QCOMPARE(w.text(), QString("/home/k")); //QCOMPARE(w.completionBox()->currentRow(), -1); // #247552 w.completionBox()->down(); // select the item QCOMPARE(w.completionBox()->items(), newItems); QCOMPARE(w.text(), newItems.at(0)); } void testPaste() { const QString origText = QApplication::clipboard()->text(); const QString pastedText = QStringLiteral("Test paste from klineedit_unittest"); QApplication::clipboard()->setText(pastedText); KLineEdit w; w.setText(QStringLiteral("Hello world")); w.selectAll(); QTest::keyClick(&w, Qt::Key_V, Qt::ControlModifier); QCOMPARE(w.text(), pastedText); QApplication::clipboard()->setText(origText); } void testClearButtonClicked() { KLineEdit w; w.setText(QStringLiteral("Hello world")); w.setClearButtonEnabled(true); w.setClearButtonEnabled(false); w.setClearButtonEnabled(true); QSignalSpy spy(&w, &KLineEdit::clearButtonClicked); QToolButton *tb = w.findChild(); QTest::mouseClick(tb, Qt::LeftButton, Qt::NoModifier); QCOMPARE(w.text(), QString()); QCOMPARE(spy.count(), 1); } }; QTEST_MAIN(KLineEdit_UnitTest) #include "klineedit_unittest.moc" diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 1023a1f..e07ae90 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,112 +1,119 @@ ecm_create_qm_loader(kcompletion_QM_LOADER kcompletion5_qt) set(kcompletion_SRCS kcombobox.cpp kcompletion.cpp kcompletionbase.cpp kcompletionbox.cpp klineedit.cpp khistorycombobox.cpp kpixmapprovider.cpp kzoneallocator.cpp kcompletionbase.cpp kcompletionmatches.cpp ${kcompletion_QM_LOADER} ) add_library(KF5Completion ${kcompletion_SRCS}) -generate_export_header(KF5Completion BASE_NAME KCompletion) add_library(KF5::Completion ALIAS KF5Completion) +ecm_generate_export_header(KF5Completion + BASE_NAME KCompletion + # GROUP_BASE_NAME KF <- enable once all of KF modules use ecm_generate_export_header + VERSION ${KF5_VERSION} + DEPRECATED_BASE_VERSION 0 + DEPRECATION_VERSIONS 4.0 4.5 5.0 5.46 + EXCLUDE_DEPRECATED_BEFORE_AND_AT ${EXCLUDE_DEPRECATED_BEFORE_AND_AT} +) target_include_directories(KF5Completion INTERFACE "$") target_link_libraries(KF5Completion PUBLIC Qt5::Widgets PRIVATE KF5::ConfigCore # KConfigGroup, used in many places KF5::ConfigGui # KStandardShortcut KF5::WidgetsAddons # KCursor ) set_target_properties(KF5Completion PROPERTIES VERSION ${KCOMPLETION_VERSION_STRING} SOVERSION ${KCOMPLETION_SOVERSION} EXPORT_NAME Completion ) ecm_generate_headers(KCompletion_HEADERS HEADER_NAMES KComboBox KCompletion KCompletionBase KCompletionBox KLineEdit KHistoryComboBox KPixmapProvider KSortableList KCompletionMatches REQUIRED_HEADERS KCompletion_HEADERS ) find_package(PythonModuleGeneration) if (PythonModuleGeneration_FOUND) ecm_generate_python_binding( TARGET KF5::Completion PYTHONNAMESPACE PyKF5 MODULENAME KCompletion RULES_FILE "${CMAKE_SOURCE_DIR}/cmake/rules_PyKF5.py" SIP_DEPENDS QtWidgets/QtWidgetsmod.sip HEADERS kcombobox.h kcompletion.h kcompletionbase.h kcompletionbox.h klineedit.h khistorycombobox.h kpixmapprovider.h ksortablelist.h kcompletionmatches.h ) endif() install(TARGETS KF5Completion EXPORT KF5CompletionTargets ${KF5_INSTALL_TARGETS_DEFAULT_ARGS}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/kcompletion_export.h ${KCompletion_HEADERS} DESTINATION ${KDE_INSTALL_INCLUDEDIR_KF5}/KCompletion COMPONENT Devel ) if(BUILD_DESIGNERPLUGIN) add_subdirectory(designer) endif() if(BUILD_QCH) ecm_add_qch( KF5Completion_QCH NAME KCompletion BASE_NAME KF5Completion VERSION ${KF5_VERSION} ORG_DOMAIN org.kde SOURCES # using only public headers, to cover only public API ${KCompletion_HEADERS} MD_MAINPAGE "${CMAKE_SOURCE_DIR}/README.md" IMAGE_DIRS "${CMAKE_SOURCE_DIR}/docs/pics" LINK_QCHS Qt5Core_QCH Qt5Gui_QCH Qt5Widgets_QCH INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR} BLANK_MACROS KCOMPLETION_EXPORT KCOMPLETION_DEPRECATED TAGFILE_INSTALL_DESTINATION ${KDE_INSTALL_QTQCHDIR} QCH_INSTALL_DESTINATION ${KDE_INSTALL_QTQCHDIR} COMPONENT Devel ) endif() include(ECMGeneratePriFile) ecm_generate_pri_file(BASE_NAME KCompletion LIB_NAME KF5Completion DEPS "widgets" FILENAME_VAR PRI_FILENAME INCLUDE_INSTALL_DIR ${KDE_INSTALL_INCLUDEDIR_KF5}/KCompletion) install(FILES ${PRI_FILENAME} DESTINATION ${ECM_MKSPECS_INSTALL_DIR}) diff --git a/src/kcombobox.cpp b/src/kcombobox.cpp index d06be6c..9c28fad 100644 --- a/src/kcombobox.cpp +++ b/src/kcombobox.cpp @@ -1,408 +1,410 @@ /* This file is part of the KDE libraries Copyright (c) 2000,2001 Dawit Alemayehu Copyright (c) 2000,2001 Carsten Pfeiffer Copyright (c) 2000 Stefan Schimanski <1Stein@gmx.de> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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 "kcombobox.h" #include #include #include #include #include class KComboBoxPrivate { public: KComboBoxPrivate(KComboBox *parent) : q_ptr(parent) { } ~KComboBoxPrivate() { } /** * Initializes the variables upon construction. */ void init(); void _k_lineEditDeleted(); KLineEdit *klineEdit = nullptr; bool trapReturnKey = false; KComboBox * const q_ptr; Q_DECLARE_PUBLIC(KComboBox) }; void KComboBoxPrivate::init() { Q_Q(KComboBox); } void KComboBoxPrivate::_k_lineEditDeleted() { Q_Q(KComboBox); // yes, we need those ugly casts due to the multiple inheritance // sender() is guaranteed to be a KLineEdit (see the connect() to the // destroyed() signal const KCompletionBase *base = static_cast(static_cast(q->sender())); // is it our delegate, that is destroyed? if (base == q->delegate()) { q->setDelegate(nullptr); } } KComboBox::KComboBox(QWidget *parent) : QComboBox(parent), d_ptr(new KComboBoxPrivate(this)) { Q_D(KComboBox); d->init(); } KComboBox::KComboBox(bool rw, QWidget *parent) : QComboBox(parent), d_ptr(new KComboBoxPrivate(this)) { Q_D(KComboBox); d->init(); setEditable(rw); } KComboBox::~KComboBox() { } bool KComboBox::contains(const QString &text) const { if (text.isEmpty()) { return false; } const int itemCount = count(); for (int i = 0; i < itemCount; ++i) { if (itemText(i) == text) { return true; } } return false; } int KComboBox::cursorPosition() const { return (isEditable()) ? lineEdit()->cursorPosition() : -1; } void KComboBox::setAutoCompletion(bool autocomplete) { Q_D(KComboBox); if (d->klineEdit) { if (autocomplete) { d->klineEdit->setCompletionMode(KCompletion::CompletionAuto); setCompletionMode(KCompletion::CompletionAuto); } else { d->klineEdit->setCompletionMode(KCompletion::CompletionPopup); setCompletionMode(KCompletion::CompletionPopup); } } } bool KComboBox::autoCompletion() const { return completionMode() == KCompletion::CompletionAuto; } -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(4, 5) void KComboBox::setContextMenuEnabled(bool showMenu) { Q_D(KComboBox); if (d->klineEdit) { d->klineEdit->setContextMenuPolicy(showMenu ? Qt::DefaultContextMenu : Qt::NoContextMenu); } } +#endif +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(5, 0) void KComboBox::setUrlDropsEnabled(bool enable) { Q_D(KComboBox); if (d->klineEdit) { d->klineEdit->setUrlDropsEnabled(enable); } } #endif bool KComboBox::urlDropsEnabled() const { Q_D(const KComboBox); return d->klineEdit && d->klineEdit->urlDropsEnabled(); } void KComboBox::setCompletedText(const QString &text, bool marked) { Q_D(KComboBox); if (d->klineEdit) { d->klineEdit->setCompletedText(text, marked); } } void KComboBox::setCompletedText(const QString &text) { Q_D(KComboBox); if (d->klineEdit) { d->klineEdit->setCompletedText(text); } } void KComboBox::makeCompletion(const QString &text) { Q_D(KComboBox); if (d->klineEdit) { d->klineEdit->makeCompletion(text); } else { // read-only combo completion if (text.isNull() || !view()) { return; } view()->keyboardSearch(text); } } void KComboBox::rotateText(KCompletionBase::KeyBindingType type) { Q_D(KComboBox); if (d->klineEdit) { d->klineEdit->rotateText(type); } } void KComboBox::setTrapReturnKey(bool trap) { Q_D(KComboBox); d->trapReturnKey = trap; if (d->klineEdit) { d->klineEdit->setTrapReturnKey(trap); } else { qWarning("KComboBox::setTrapReturnKey not supported with a non-KLineEdit."); } } bool KComboBox::trapReturnKey() const { Q_D(const KComboBox); return d->trapReturnKey; } void KComboBox::setEditUrl(const QUrl &url) { QComboBox::setEditText(url.toDisplayString()); } void KComboBox::addUrl(const QUrl &url) { QComboBox::addItem(url.toDisplayString()); } void KComboBox::addUrl(const QIcon &icon, const QUrl &url) { QComboBox::addItem(icon, url.toDisplayString()); } void KComboBox::insertUrl(int index, const QUrl &url) { QComboBox::insertItem(index, url.toDisplayString()); } void KComboBox::insertUrl(int index, const QIcon &icon, const QUrl &url) { QComboBox::insertItem(index, icon, url.toDisplayString()); } void KComboBox::changeUrl(int index, const QUrl &url) { QComboBox::setItemText(index, url.toDisplayString()); } void KComboBox::changeUrl(int index, const QIcon &icon, const QUrl &url) { QComboBox::setItemIcon(index, icon); QComboBox::setItemText(index, url.toDisplayString()); } void KComboBox::setCompletedItems(const QStringList &items, bool autosubject) { Q_D(KComboBox); if (d->klineEdit) { d->klineEdit->setCompletedItems(items, autosubject); } } KCompletionBox *KComboBox::completionBox(bool create) { Q_D(KComboBox); if (d->klineEdit) { return d->klineEdit->completionBox(create); } return nullptr; } QSize KComboBox::minimumSizeHint() const { Q_D(const KComboBox); QSize size = QComboBox::minimumSizeHint(); if (isEditable() && d->klineEdit) { // if it's a KLineEdit and it's editable add the clear button size // to the minimum size hint, otherwise looks ugly because the // clear button will cover the last 2/3 letters of the biggest entry QSize bs = d->klineEdit->clearButtonUsedSize(); if (bs.isValid()) { size.rwidth() += bs.width(); size.rheight() = qMax(size.height(), bs.height()); } } return size; } void KComboBox::setLineEdit(QLineEdit *edit) { Q_D(KComboBox); if (!isEditable() && edit && !qstrcmp(edit->metaObject()->className(), "QLineEdit")) { // uic generates code that creates a read-only KComboBox and then // calls combo->setEditable(true), which causes QComboBox to set up // a dumb QLineEdit instead of our nice KLineEdit. // As some KComboBox features rely on the KLineEdit, we reject // this order here. delete edit; KLineEdit *kedit = new KLineEdit(this); if (isEditable()) { kedit->setClearButtonEnabled(true); } edit = kedit; } // reuse an existing completion object, if it does not belong to the previous // line edit and gets destroyed with it QPointer completion = compObj(); QComboBox::setLineEdit(edit); edit->setCompleter(nullptr); // remove Qt's builtin completer (set by setLineEdit), we have our own d->klineEdit = qobject_cast(edit); setDelegate(d->klineEdit); if (completion && d->klineEdit) { d->klineEdit->setCompletionObject(completion); } // Connect the returnPressed signal for both Q[K]LineEdits' if (edit) { connect(edit, QOverload<>::of(&QLineEdit::returnPressed), this, QOverload<>::of(&KComboBox::returnPressed)); } if (d->klineEdit) { // someone calling KComboBox::setEditable(false) destroys our // line edit without us noticing. And KCompletionBase::delegate would // be a dangling pointer then, so prevent that. Note: only do this // when it is a KLineEdit! connect(edit, SIGNAL(destroyed()), SLOT(_k_lineEditDeleted())); connect(d->klineEdit, QOverload::of(&KLineEdit::returnPressed), this, QOverload::of(&KComboBox::returnPressed)); connect(d->klineEdit, &KLineEdit::completion, this, &KComboBox::completion); connect(d->klineEdit, &KLineEdit::substringCompletion, this, &KComboBox::substringCompletion); connect(d->klineEdit, &KLineEdit::textRotation, this, &KComboBox::textRotation); connect(d->klineEdit, &KLineEdit::completionModeChanged, this, &KComboBox::completionModeChanged); connect(d->klineEdit, &KLineEdit::aboutToShowContextMenu, this, &KComboBox::aboutToShowContextMenu); // match the declaration of the deprecated signal #if QT_DEPRECATED_SINCE(5, 15) || QT_VERSION < QT_VERSION_CHECK(5, 14, 0) connect(d->klineEdit, &KLineEdit::completionBoxActivated, this, QOverload::of(&QComboBox::activated)); #endif #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) connect(d->klineEdit, &KLineEdit::completionBoxActivated, this, QOverload::of(&QComboBox::textActivated)); #endif d->klineEdit->setTrapReturnKey(d->trapReturnKey); } } void KComboBox::setCurrentItem(const QString &item, bool insert, int index) { int sel = -1; const int itemCount = count(); for (int i = 0; i < itemCount; ++i) { if (itemText(i) == item) { sel = i; break; } } if (sel == -1 && insert) { if (index >= 0) { insertItem(index, item); sel = index; } else { addItem(item); sel = count() - 1; } } setCurrentIndex(sel); } void KComboBox::setEditable(bool editable) { if (editable == isEditable()) { return; } if (editable) { // Create a KLineEdit instead of a QLineEdit // Compared to QComboBox::setEditable, we might be missing the SH_ComboBox_Popup code though... // If a style needs this, then we'll need to call QComboBox::setEditable and then setLineEdit again KLineEdit *edit = new KLineEdit(this); edit->setClearButtonEnabled(true); setLineEdit(edit); } else { QComboBox::setEditable(editable); } } #include "moc_kcombobox.cpp" diff --git a/src/kcombobox.h b/src/kcombobox.h index 43d689e..96e7352 100644 --- a/src/kcombobox.h +++ b/src/kcombobox.h @@ -1,537 +1,543 @@ /* This file is part of the KDE libraries Copyright (c) 2000,2001 Dawit Alemayehu Copyright (c) 2000,2001 Carsten Pfeiffer This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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 KCOMBOBOX_H #define KCOMBOBOX_H #include #include #include #include class KCompletionBox; class KComboBoxPrivate; class QLineEdit; class QMenu; /** * @class KComboBox kcombobox.h KComboBox * * @short A combo box with completion support. * * This widget inherits from QComboBox and implements the following * additional features: * @li a completion object that provides both automatic * and manual text completion as well as text rotation * @li configurable key bindings to activate these features * @li a popup menu item that can be used to allow the user to change * the text completion mode on the fly. * * To support these new features, KComboBox emits a few additional signals * such as completion(const QString&) and textRotation(KeyBindingType). * The completion signal can be connected to a slot that will assist the user in * filling out the remaining text while the rotation signal can be used to traverse * through all possible matches whenever text completion results in multiple matches. * Additionally, the returnPressed() and returnPressed(const QString&) * signals are emitted when the user presses the Enter/Return key. * * KCombobox by default creates a completion object when you invoke the * completionObject(bool) member function for the first time or * explicitly use setCompletionObject(KCompletion*, bool) to assign your * own completion object. Additionally, to make this widget more functional, * KComboBox will by default handle text rotation and completion events * internally whenever a completion object is created through either one of the * methods mentioned above. If you do not need this functionality, simply use * KCompletionBase::setHandleSignals(bool) or alternatively set the boolean * parameter in the @c setCompletionObject call to false. * * Beware: The completion object can be deleted on you, especially if a call * such as setEditable(false) is made. Store the pointer at your own risk, * and consider using QPointer. * * The default key bindings for completion and rotation are determined from the * global settings in KStandardShortcut. These values, however, can be overridden * locally by invoking KCompletionBase::setKeyBinding(). The values can * easily be reverted back to the default settings by calling * useGlobalSettings(). An alternate method would be to default individual * key bindings by using setKeyBinding() with the default second argument. * * A non-editable combo box only has one completion mode, @c CompletionAuto. * Unlike an editable combo box, the CompletionAuto mode works by matching * any typed key with the first letter of entries in the combo box. Please note * that if you call setEditable(false) to change an editable combo box to a * non-editable one, the text completion object associated with the combo box will * no longer exist unless you created the completion object yourself and assigned * it to this widget or you called setAutoDeleteCompletionObject(false). In other * words do not do the following: * * \code * KComboBox* combo = new KComboBox(true, this); * KCompletion* comp = combo->completionObject(); * combo->setEditable(false); * comp->clear(); // CRASH: completion object does not exist anymore. * \endcode * * * A read-only KComboBox will have the same background color as a * disabled KComboBox, but its foreground color will be the one used for * the editable mode. This differs from QComboBox's implementation * and is done to give visual distinction between the three different modes: * disabled, read-only, and editable. * * \b Usage \n * * To enable the basic completion feature: * * \code * KComboBox *combo = new KComboBox(true, this); * KCompletion *comp = combo->completionObject(); * // Connect to the return pressed signal - optional * connect(combo,SIGNAL(returnPressed(const QString&)),comp,SLOT(addItem(const QString&))); * * // Provide the to be completed strings. Note that those are separate from the combo's * // contents. * comp->insertItems(someQStringList); * \endcode * * To use your own completion object: * * \code * KComboBox *combo = new KComboBox(this); * KUrlCompletion *comp = new KUrlCompletion(); * combo->setCompletionObject(comp); * // Connect to the return pressed signal - optional * connect(combo,SIGNAL(returnPressed(const QString&)),comp,SLOT(addItem(const QString&))); * \endcode * * Note that you have to either delete the allocated completion object * when you don't need it anymore, or call * setAutoDeleteCompletionObject(true); * * Miscellaneous function calls: * * \code * // Tell the widget not to handle completion and rotation * combo->setHandleSignals(false); * // Set your own completion key for manual completions. * combo->setKeyBinding(KCompletionBase::TextCompletion, Qt::End); * \endcode * * \image html kcombobox.png "KComboBox widgets, one non-editable, one editable with KUrlCompletion" * * @author Dawit Alemayehu */ class KCOMPLETION_EXPORT KComboBox : public QComboBox, public KCompletionBase //krazy:exclude=qclasses { Q_OBJECT Q_PROPERTY(bool autoCompletion READ autoCompletion WRITE setAutoCompletion) -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(5, 0) Q_PROPERTY(bool urlDropsEnabled READ urlDropsEnabled WRITE setUrlDropsEnabled) #endif Q_PROPERTY(bool trapReturnKey READ trapReturnKey WRITE setTrapReturnKey) Q_DECLARE_PRIVATE(KComboBox) public: /** * Constructs a read-only (or rather select-only) combo box. * * @param parent The parent object of this widget */ explicit KComboBox(QWidget *parent = nullptr); /** * Constructs an editable or read-only combo box. * * @param rw When @c true, widget will be editable. * @param parent The parent object of this widget. */ explicit KComboBox(bool rw, QWidget *parent = nullptr); /** * Destructor. */ ~KComboBox() override; +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) /** * Deprecated to reflect Qt api changes * @deprecated since 4.5 */ -#ifndef KCOMPLETION_NO_DEPRECATED - KCOMPLETION_DEPRECATED void insertURL(const QUrl &url, int index = -1) + KCOMPLETION_DEPRECATED_VERSION(4, 5, "Use KComboBox::insertUrl(int, const QUrl&)") + void insertURL(const QUrl &url, int index = -1) { insertUrl(index < 0 ? count() : index, url); } - KCOMPLETION_DEPRECATED void insertURL(const QPixmap &pixmap, const QUrl &url, int index = -1) + KCOMPLETION_DEPRECATED_VERSION(4, 5, "Use KComboBox::insertUrl(int, const QIcon&, const QUrl&)") + void insertURL(const QPixmap &pixmap, const QUrl &url, int index = -1) { insertUrl(index < 0 ? count() : index, QIcon(pixmap), url); } - KCOMPLETION_DEPRECATED void changeURL(const QUrl &url, int index) + KCOMPLETION_DEPRECATED_VERSION(4, 5, "Use KComboBox::changeUrl(int, const QUrl&)") + void changeURL(const QUrl &url, int index) { changeUrl(index, url); } - KCOMPLETION_DEPRECATED void changeURL(const QPixmap &pixmap, const QUrl &url, int index) + KCOMPLETION_DEPRECATED_VERSION(4, 5, "Use KComboBox::changeUrl(int, const QIcon&, const QUrl&)") + void changeURL(const QPixmap &pixmap, const QUrl &url, int index) { changeUrl(index, QIcon(pixmap), url); } #endif /** * Sets @p url into the edit field of the combo box. * * It uses QUrl::toDisplayString() so that the url is properly decoded for * displaying. */ void setEditUrl(const QUrl &url); /** * Appends @p url to the combo box. * * QUrl::toDisplayString() is used so that the url is properly decoded * for displaying. */ void addUrl(const QUrl &url); /** * Appends @p url with the @p icon to the combo box. * * QUrl::toDisplayString() is used so that the url is properly decoded * for displaying. */ void addUrl(const QIcon &icon, const QUrl &url); /** * Inserts @p url at position @p index into the combo box. * * QUrl::toDisplayString() is used so that the url is properly decoded * for displaying. */ void insertUrl(int index, const QUrl &url); /** * Inserts @p url with the @p icon at position @p index into * the combo box. * * QUrl::toDisplayString() is used so that the url is * properly decoded for displaying. */ void insertUrl(int index, const QIcon &icon, const QUrl &url); /** * Replaces the item at position @p index with @p url. * * QUrl::toDisplayString() is used so that the url is properly decoded * for displaying. */ void changeUrl(int index, const QUrl &url); /** * Replaces the item at position @p index with @p url and @p icon. * * QUrl::toDisplayString() is used so that the url is properly decoded * for displaying. */ void changeUrl(int index, const QIcon &icon, const QUrl &url); /** * Returns the current cursor position. * * This method always returns a -1 if the combo box is @em not * editable (read-only). * * @return Current cursor position. */ int cursorPosition() const; /** * Reimplemented from QComboBox. * * If @c true, the completion mode will be set to automatic. * Otherwise, it is defaulted to the global setting. This * method has been replaced by the more comprehensive * setCompletionMode(). * * @param autocomplete Flag to enable/disable automatic completion mode. */ virtual void setAutoCompletion(bool autocomplete); /** * Reimplemented from QComboBox. * * Returns @c true if the current completion mode is set * to automatic. See its more comprehensive replacement * completionMode(). * * @return @c true when completion mode is automatic. */ bool autoCompletion() const; +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(4, 5) /** * Enables or disables the popup (context) menu. * * This method only works if this widget is editable, and * allows you to enable/disable the context menu. It does nothing if invoked * for a non-editable combo box. * * By default, the context menu is created if this widget is editable. * Call this function with the argument set to false to disable the popup * menu. * * @param showMenu If @c true, show the context menu. * @deprecated since 4.5, use setContextMenuPolicy instead */ -#ifndef KCOMPLETION_NO_DEPRECATED - virtual KCOMPLETION_DEPRECATED void setContextMenuEnabled(bool showMenu); + KCOMPLETION_DEPRECATED_VERSION(4, 5, "Use QWidget::setContextMenuPolicy(...)") + virtual void setContextMenuEnabled(bool showMenu); #endif +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(5, 0) /** * Enables/Disables handling of URL drops. * * If enabled and the user drops an URL, the decoded URL will * be inserted. Otherwise the default behavior of QComboBox is used, * which inserts the encoded URL. * * @param enable If @c true, insert decoded URLs * @deprecated since 5.0. Use lineEdit()->installEventFilter with a LineEditUrlDropEventFilter */ -#ifndef KCOMPLETION_NO_DEPRECATED - KCOMPLETION_DEPRECATED void setUrlDropsEnabled(bool enable); + KCOMPLETION_DEPRECATED_VERSION(5, 0, "Use KComboBox::lineEdit()->installEventFilter(...) with a LineEditUrlDropEventFilter") + void setUrlDropsEnabled(bool enable); #endif /** * Returns @c true when decoded URL drops are enabled */ bool urlDropsEnabled() const; /** * Convenience method which iterates over all items and checks if * any of them is equal to @p text. * * If @p text is an empty string, @c false * is returned. * * @return @c true if an item with the string @p text is in the combo box. */ bool contains(const QString &text) const; /** * By default, KComboBox recognizes Key_Return and Key_Enter * and emits the returnPressed() signals, but it also lets the * event pass, for example causing a dialog's default button to * be called. * * Call this method with @p trap equal to true to make KComboBox * stop these events. The signals will still be emitted of course. * * Only affects editable combo boxes. * * @see setTrapReturnKey() */ void setTrapReturnKey(bool trap); /** * @return @c true if key events of Key_Return or Key_Enter will * be stopped; @c false if they will be propagated. * * @see setTrapReturnKey () */ bool trapReturnKey() const; /** * @returns the completion box that is used in completion mode * CompletionPopup and CompletionPopupAuto. * * This method will create a completion box by calling * KLineEdit::completionBox, if none is there yet. * * @param create Set this to false if you don't want the box to be created * i.e. to test if it is available. */ KCompletionBox *completionBox(bool create = true); /** * Reimplemented for internal reasons. API remains unaffected. * Note that QComboBox::setLineEdit is not virtual in Qt4, do not * use a KComboBox in a QComboBox pointer. * * NOTE: Only editable combo boxes can have a line editor. As such * any attempt to assign a line edit to a non-editable combo box will * simply be ignored. */ virtual void setLineEdit(QLineEdit *); /** * Reimplemented so that setEditable(true) creates a KLineEdit * instead of QLineEdit. * * Note that QComboBox::setEditable is not virtual, so do not * use a KComboBox in a QComboBox pointer. */ void setEditable(bool editable); Q_SIGNALS: /** * Emitted when the user presses the Enter key. * * Note that this signal is only emitted when the widget is editable. */ void returnPressed(); /** * Emitted when the user presses the Enter key. * * The argument is the current text being edited. This signal is just like * returnPressed() except that it contains the current text as its argument. * * Note that this signal is only emitted when the * widget is editable. */ void returnPressed(const QString &); /** * Emitted when the completion key is pressed. * * The argument is the current text being edited. * * Note that this signal is @em not available when the widget is non-editable * or the completion mode is set to @c CompletionNone. */ void completion(const QString &); /** * Emitted when the shortcut for substring completion is pressed. */ void substringCompletion(const QString &); /** * Emitted when the text rotation key bindings are pressed. * * The argument indicates which key binding was pressed. In this case this * can be either one of four values: @c PrevCompletionMatch, * @c NextCompletionMatch, @c RotateUp or @c RotateDown. * * Note that this signal is @em not emitted if the completion * mode is set to CompletionNone. * * @see KCompletionBase::setKeyBinding() for details */ void textRotation(KCompletionBase::KeyBindingType); /** * Emitted whenever the completion mode is changed by the user * through the context menu. */ void completionModeChanged(KCompletion::CompletionMode); /** * Emitted before the context menu is displayed. * * The signal allows you to add your own entries into the context menu. * Note that you must not store the pointer to the QPopupMenu since it is * created and deleted on demand. Otherwise, you can crash your app. * * @param contextMenu the context menu about to be displayed */ void aboutToShowContextMenu(QMenu *contextMenu); public Q_SLOTS: /** * Iterates through all possible matches of the completed text * or the history list. * * Depending on the value of the argument, this function either * iterates through the history list of this widget or all the * possible matches in whenever multiple matches result from a * text completion request. Note that the all-possible-match * iteration will not work if there are no previous matches, i.e. * no text has been completed and the *nix shell history list * rotation is only available if the insertion policy for this * widget is set either @c QComobBox::AtTop or @c QComboBox::AtBottom. * For other insertion modes whatever has been typed by the user * when the rotation event was initiated will be lost. * * @param type The key binding invoked. */ void rotateText(KCompletionBase::KeyBindingType type); /** * Sets the completed text in the line edit appropriately. * * This function is an implementation for * KCompletionBase::setCompletedText. */ void setCompletedText(const QString &) override; /** * Sets @p items into the completion box if completionMode() is * CompletionPopup. The popup will be shown immediately. */ void setCompletedItems(const QStringList &items, bool autosubject = true) override; /** * Selects the first item that matches @p item. * * If there is no such item, it is inserted at position @p index * if @p insert is true. Otherwise, no item is selected. */ void setCurrentItem(const QString &item, bool insert = false, int index = -1); protected Q_SLOTS: /** * Completes text according to the completion mode. * * Note: this method is not invoked if the completion mode is * set to @c CompletionNone. Also if the mode is set to @c CompletionShell * and multiple matches are found, this method will complete the * text to the first match with a beep to indicate that there are * more matches. Then any successive completion key event iterates * through the remaining matches. This way the rotation functionality * is left to iterate through the list as usual. */ virtual void makeCompletion(const QString &); protected: /** * This function sets the line edit text and * highlights the text appropriately if the boolean * value is set to true. * * @param text The text to be set in the line edit * @param marked Whether the text inserted should be highlighted */ virtual void setCompletedText(const QString &text, bool marked); // TODO KF6: make public like in base classes, so consumers do not need to cast to base classes // when they have a KComboBox (or subclasses) object and want to access this property QSize minimumSizeHint() const override; private: const QScopedPointer d_ptr; Q_PRIVATE_SLOT(d_func(), void _k_lineEditDeleted()) }; #endif diff --git a/src/kcompletion.h b/src/kcompletion.h index cb6977a..545d378 100644 --- a/src/kcompletion.h +++ b/src/kcompletion.h @@ -1,573 +1,580 @@ /* This file is part of the KDE libraries Copyright (C) 1999,2000 Carsten Pfeiffer 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 KCOMPLETION_H #define KCOMPLETION_H #include #include #include #include #include class KCompTreeNode; class KCompletionPrivate; class KCompletionMatchesWrapper; class KCompletionMatches; /** * @class KCompletion kcompletion.h KCompletion * * @short A generic class for completing QStrings * * This class offers easy use of "auto completion", "manual completion" or * "shell completion" on QString objects. A common use is completing filenames * or URLs (see KUrlCompletion()). * But it is not limited to URL-completion -- everything should be completable! * The user should be able to complete email addresses, telephone numbers, * commands, SQL queries... * Every time your program knows what the user can type into an edit field, you * should offer completion. With KCompletion, this is very easy, and if you are * using a line edit widget (KLineEdit), it is even easier. * Basically, you tell a KCompletion object what strings should be completable * and, whenever completion should be invoked, you call makeCompletion(). * KLineEdit and (an editable) KComboBox even do this automatically for you. * * KCompletion offers the completed string via the signal match() and * all matching strings (when the result is ambiguous) via the method * allMatches(). * * Notice: auto completion, shell completion and manual completion work * slightly differently: * * @li auto completion always returns a complete item as match. * When more than one matching item is available, it will deliver just * the first one (depending on sorting order). Iterating over all matches * is possible via nextMatch() and previousMatch(). * * @li popup completion works in the same way, the only difference being that * the completed items are not put into the edit widget, but into a * separate popup box. * * @li manual completion works the same way as auto completion, except that * it is not invoked automatically while the user is typing, * but only when the user presses a special key. The difference * of manual and auto completion is therefore only visible in UI classes. * KCompletion needs to know whether to deliver partial matches * (shell completion) or whole matches (auto/manual completion), therefore * KCompletion::CompletionMan and KCompletion::CompletionAuto have the exact * same effect in KCompletion. * * @li shell completion works like "tab completion" in a shell: * when multiple matches are available, the longest possible string of all * matches is returned (i.e. only a partial item). * Iterating over all matching items (complete, not partial) is possible * via nextMatch() and previousMatch(). * * As an application programmer, you do not normally have to worry about * the different completion modes; KCompletion handles * that for you, according to the setting setCompletionMode(). * The default setting is globally configured by the user and read * from completionMode(). * * A short example: * \code * KCompletion completion; * completion.setOrder(KCompletion::Sorted); * completion.addItem("pfeiffer@kde.org"); * completion.addItem("coolo@kde.org"); * completion.addItem("carpdjih@sp.zrz.tu-berlin.de"); * completion.addItem("carp@cs.tu-berlin.de"); * * cout << completion.makeCompletion("ca").latin1() << endl; * \endcode * * In shell-completion mode, this will be "carp"; in auto-completion * mode it will be "carp\@cs.tu-berlin.de", as that is alphabetically * smaller. * If setOrder was set to Insertion, "carpdjih\@sp.zrz.tu-berlin.de" * would be completed in auto-completion mode, as that was inserted before * "carp\@cs.tu-berlin.de". * * You can dynamically update the completable items by removing and adding them * whenever you want. * For advanced usage, you could even use multiple KCompletion objects. E.g. * imagine an editor like kwrite with multiple open files. You could store * items of each file in a different KCompletion object, so that you know (and * tell the user) where a completion comes from. * * Note: KCompletion does not work with strings that contain 0x0 characters * (unicode null), as this is used internally as a delimiter. * * You may inherit from KCompletion and override makeCompletion() in * special cases (like reading directories or urls and then supplying the * contents to KCompletion, as KUrlCompletion does), but this is usually * not necessary. * * * @author Carsten Pfeiffer */ class KCOMPLETION_EXPORT KCompletion : public QObject { Q_PROPERTY(CompOrder order READ order WRITE setOrder) Q_PROPERTY(bool ignoreCase READ ignoreCase WRITE setIgnoreCase) Q_PROPERTY(QStringList items READ items WRITE setItems) Q_OBJECT Q_DECLARE_PRIVATE(KCompletion) public: /** * This enum describes the completion mode used for by the KCompletion class. * See * the styleguide. * * @since 5.0 **/ enum CompletionMode { /** * No completion is used. */ CompletionNone = 1, /** * Text is automatically filled in whenever possible. */ CompletionAuto, /** * Same as automatic, but shortest match is used for completion. */ CompletionMan, /** * Completes text much in the same way as a typical *nix shell would. */ CompletionShell, /** * Lists all possible matches in a popup list box to choose from. */ CompletionPopup, /** * Lists all possible matches in a popup list box to choose from, and automatically * fills the result whenever possible. */ CompletionPopupAuto }; /** * Constants that represent the order in which KCompletion performs * completion lookups. */ enum CompOrder { Sorted, ///< Use alphabetically sorted order Insertion, ///< Use order of insertion Weighted ///< Use weighted order }; Q_ENUM(CompOrder) /** * Constructor, nothing special here :) */ KCompletion(); /** * Destructor, nothing special here, either. */ virtual ~KCompletion(); /** * Returns a list of all completion items that contain the given @p string. * @param string the string to complete * @return a list of items which contain @p text as a substring, * i.e. not necessarily at the beginning. * * @see makeCompletion */ QStringList substringCompletion(const QString &string) const; /** * Returns the last match. Might be useful if you need to check whether * a completion is different from the last one. * @return the last match. QString() is returned when there is no * last match. */ virtual const QString &lastMatch() const; /** * Returns a list of all items inserted into KCompletion. This is useful * if you need to save the state of a KCompletion object and restore it * later. * * Important note: when order() == Weighted, then every item in the * stringlist has its weight appended, delimited by a colon. E.g. an item * "www.kde.org" might look like "www.kde.org:4", where 4 is the weight. * * This is necessary so that you can save the items along with its * weighting on disk and load them back with setItems(), restoring its * weight as well. If you really don't want the appended weightings, call * setOrder( KCompletion::Insertion ) before calling items(). * * @return a list of all items * @see setItems */ QStringList items() const; /** * Returns true if the completion object contains no entries. */ bool isEmpty() const; /** * Sets the completion mode. * @param mode the completion mode * @see CompletionMode */ virtual void setCompletionMode(CompletionMode mode); /** * Returns the current completion mode. * * @return the current completion mode, default is CompletionPopup * @see setCompletionMode * @see CompletionMode */ CompletionMode completionMode() const; /** * KCompletion offers three different ways in which it offers its items: * @li in the order of insertion * @li sorted alphabetically * @li weighted * * Choosing weighted makes KCompletion perform an implicit weighting based * on how often an item is inserted. Imagine a web browser with a location * bar, where the user enters URLs. The more often a URL is entered, the * higher priority it gets. * * Note: Setting the order to sorted only affects new inserted items, * already existing items will stay in the current order. So you probably * want to call setOrder(Sorted) before inserting items if you want * everything sorted. * * Default is insertion order. * @param order the new order * @see order */ virtual void setOrder(CompOrder order); /** * Returns the completion order. * @return the current completion order. * @see setOrder */ CompOrder order() const; /** * Setting this to true makes KCompletion behave case insensitively. * E.g. makeCompletion("CA"); might return "carp\@cs.tu-berlin.de". * Default is false (case sensitive). * @param ignoreCase true to ignore the case * @see ignoreCase */ virtual void setIgnoreCase(bool ignoreCase); /** * Returns whether KCompletion acts case insensitively or not. * Default is false (case sensitive). * @return true if the case will be ignored * @see setIgnoreCase */ bool ignoreCase() const; /** * Returns a list of all items matching the last completed string. * It might take some time if you have a @em lot of items. * @return a list of all matches for the last completed string. * @see substringCompletion */ QStringList allMatches(); /** * Returns a list of all items matching @p string. * @param string the string to match * @return the list of all matches */ QStringList allMatches(const QString &string); /** * Returns a list of all items matching the last completed string. * It might take some time if you have a @em lot of items. * The matches are returned as KCompletionMatches, which also * keeps the weight of the matches, allowing * you to modify some matches or merge them with matches * from another call to allWeightedMatches(), and sort the matches * after that in order to have the matches ordered correctly. * * @return a list of all completion matches * @see substringCompletion */ KCompletionMatches allWeightedMatches(); /** * Returns a list of all items matching @p string. * @param string the string to match * @return a list of all matches */ KCompletionMatches allWeightedMatches(const QString &string); /** * Enables/disables emitting a sound when * @li makeCompletion() can't find a match * @li there is a partial completion (= multiple matches in * Shell-completion mode) * @li nextMatch() or previousMatch() hit the last possible * match and the list is rotated * * KNotifyClient() is used to emit the sounds. * * @param enable true to enable sounds * @see soundsEnabled */ virtual void setSoundsEnabled(bool enable); /** * Tells you whether KCompletion will emit sounds on certain occasions. * Default is enabled. * @return true if sounds are enabled * @see setSoundsEnabled */ bool soundsEnabled() const; /** * Returns true when more than one match is found. * @return true if there is more than one match * @see multipleMatches */ bool hasMultipleMatches() const; public Q_SLOTS: /** * Attempts to find an item in the list of available completions * that begins with @p string. Will either return the first matching item * (if there is more than one match) or QString(), if no match is * found. * * In the latter case, a sound will be emitted, depending on * soundsEnabled(). * If a match is found, it will be emitted via the signal * match(). * * If this is called twice or more with the same string while no * items were added or removed in the meantime, all available completions * will be emitted via the signal matches(). * This happens only in shell-completion mode. * * @param string the string to complete * @return the matching item, or QString() if there is no matching * item. * @see substringCompletion */ virtual QString makeCompletion(const QString &string); /** * Returns the next item from the list of matching items. * When reaching the beginning, the list is rotated so it will return the * last match and a sound is emitted (depending on soundsEnabled()). * @return the next item from the list of matching items. * When there is no match, QString() is returned and * a sound is emitted. */ QString previousMatch(); /** * Returns the next item from the list of matching items. * When reaching the last item, the list is rotated, so it will return * the first match and a sound is emitted (depending on * soundsEnabled()). * @return the next item from the list of matching items. When there is no * match, QString() is returned and a sound is emitted. */ QString nextMatch(); +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(5, 0) /** * Attempts to complete "string" and emits the completion via match(). * Same as makeCompletion(), but in this case as a slot. * @param string the string to complete * @see makeCompletion * @deprecated since 5.0, use makeCompletion() instead */ -#ifndef KCOMPLETION_NO_DEPRECATED - KCOMPLETION_DEPRECATED void slotMakeCompletion(const QString &string) //inline (redirect) + KCOMPLETION_DEPRECATED_VERSION(5, 0, "Use KCompletion::makeCompletion(const QString &)") + void slotMakeCompletion(const QString &string) //inline (redirect) { (void) makeCompletion(string); } +#endif +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(5, 0) /** * Searches the previous matching item and emits it via match(). * Same as previousMatch(), but in this case as a slot. * @see previousMatch * @deprecated since 5.0, use previousMatch() instead */ - KCOMPLETION_DEPRECATED void slotPreviousMatch() //inline (redirect) + KCOMPLETION_DEPRECATED_VERSION(5, 0, "Use KCompletion::previousMatch()") + void slotPreviousMatch() //inline (redirect) { (void) previousMatch(); } +#endif +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(5, 0) /** * Searches the next matching item and emits it via match(). * Same as nextMatch(), but in this case as a slot. * @see nextMatch * @deprecated since 5.0, use nextMatch() instead */ - KCOMPLETION_DEPRECATED void slotNextMatch() //inline (redirect) + KCOMPLETION_DEPRECATED_VERSION(5, 0, "Use KCompletion::nextMatch()") + void slotNextMatch() //inline (redirect) { (void) nextMatch(); } #endif /** * Inserts @p items into the list of possible completions. * It does the same as setItems(), but without calling clear() before. * @param items the items to insert */ void insertItems(const QStringList &items); /** * Sets the list of items available for completion. Removes all previous * items. * * Notice: when order() == Weighted, then the weighting is looked up for * every item in the stringlist. Every item should have ":number" appended, * where number is an unsigned integer, specifying the weighting. * * If you don't like this, call * setOrder(KCompletion::Insertion) * before calling setItems(). * * @param itemList the list of items that are available for completion * @see items */ virtual void setItems(const QStringList &itemList); /** * Adds an item to the list of available completions. * Resets the current item state (previousMatch() and nextMatch() * won't work the next time they are called). * @param item the item to add */ void addItem(const QString &item); /** * Adds an item to the list of available completions. * Resets the current item state (previousMatch() and nextMatch() * won't work the next time they are called). * * Sets the weight of the item to @p weight or adds it to the current * weight if the item is already available. The weight has to be greater * than 1 to take effect (default weight is 1). * @param item the item to add * @param weight the weight of the item, default is 1 */ void addItem(const QString &item, uint weight); /** * Removes an item from the list of available completions. * Resets the current item state (previousMatch() and nextMatch() * won't work the next time they are called). * @param item the item to remove */ void removeItem(const QString &item); /** * Removes all inserted items. */ virtual void clear(); Q_SIGNALS: /** * This signal is emitted when a match is found. * * In particular, makeCompletion(), previousMatch() and nextMatch() * all emit this signal; makeCompletion() will only emit it when a * match is found, but the other methods will alwasy emit it (and so * may emit it with an empty string). * * @param item the matching item, or QString() if there were no more * matching items. */ void match(const QString &item); /** * This signal is emitted by makeCompletion() in shell-completion mode * when the same string is passed to makeCompletion() multiple times in * a row. * @param matchlist the list of all matching items */ void matches(const QStringList &matchlist); /** * This signal is emitted when calling makeCompletion() and more than * one matching item is found. * @see hasMultipleMatches */ void multipleMatches(); protected: /** * This method is called after a completion is found and before the * matching string is emitted. You can override this method to modify the * string that will be emitted. * This is necessary e.g. in KUrlCompletion(), where files with spaces * in their names are shown escaped ("filename\ with\ spaces"), but stored * unescaped inside KCompletion. * Never delete that pointer! * * Default implementation does nothing. * @param match the match to process * @see postProcessMatches */ virtual void postProcessMatch(QString *match) const; /** * This method is called before a list of all available completions is * emitted via matches(). You can override this method to modify the * found items before match() or matches() are emitted. * Never delete that pointer! * * Default implementation does nothing. * @param matchList the matches to process * @see postProcessMatch */ virtual void postProcessMatches(QStringList *matchList) const; /** * This method is called before a list of all available completions is * emitted via #matches(). You can override this method to modify the * found items before #match() or #matches() are emitted. * Never delete that pointer! * * Default implementation does nothing. * @param matches the matches to process * @see postProcessMatch */ virtual void postProcessMatches(KCompletionMatches *matches) const; private: Q_DISABLE_COPY(KCompletion) const QScopedPointer d_ptr; }; #endif // KCOMPLETION_H diff --git a/src/kcompletionbase.h b/src/kcompletionbase.h index f80bedb..3b67dc7 100644 --- a/src/kcompletionbase.h +++ b/src/kcompletionbase.h @@ -1,378 +1,380 @@ /* This file is part of the KDE libraries Copyright (C) 1999,2000 Carsten Pfeiffer 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 KCOMPLETIONBASE_H #define KCOMPLETIONBASE_H #include #include #include class KCompletionBasePrivate; /** * @class KCompletionBase kcompletionbase.h KCompletionBase * * An abstract base class for adding a completion feature * into widgets. * * This is a convenience class that provides the basic functions * needed to add text completion support into widgets. All that * is required is an implementation for the pure virtual function * setCompletedText(). Refer to KLineEdit or KComboBox * to see how easily such support can be added using this as a base * class. * * @short An abstract class for adding text completion support to widgets. * @author Dawit Alemayehu */ class KCOMPLETION_EXPORT KCompletionBase { public: Q_DECLARE_PRIVATE(KCompletionBase) /** * Constants that represent the items whose shortcut * key binding is programmable. The default key bindings * for these items are defined in KStandardShortcut. */ enum KeyBindingType { /** * Text completion (by default Ctrl-E). */ TextCompletion, /** * Switch to previous completion (by default Ctrl-Up). */ PrevCompletionMatch, /** * Switch to next completion (by default Ctrl-Down). */ NextCompletionMatch, /** * Substring completion (by default Ctrl-T). */ SubstringCompletion }; // Map for the key binding types mentioned above. typedef QMap > KeyBindingMap; /** * Default constructor. */ KCompletionBase(); /** * Destructor. */ virtual ~KCompletionBase(); /** * Returns a pointer to the current completion object. * * If the completion object does not exist, it is automatically created and * by default handles all the completion signals internally unless @c handleSignals * is set to false. It is also automatically destroyed when the destructor * is called. You can change this default behavior using the * @ref setAutoDeleteCompletionObject and @ref setHandleSignals member * functions. * * See also @ref compObj. * * @param handleSignals if true, handles completion signals internally. * @return a pointer to the completion object. */ KCompletion *completionObject(bool handleSignals = true); /** * Sets up the completion object to be used. * * This method assigns the completion object and sets it up to automatically * handle the completion and rotation signals internally. You should use * this function if you want to share one completion object among your * widgets or need to use a customized completion object. * * The object assigned through this method is not deleted when this object's * destructor is invoked unless you explicitly call @ref setAutoDeleteCompletionObject * after calling this method. Be sure to set the bool argument to false, if * you want to handle the completion signals yourself. * * @param completionObject a KCompletion or a derived child object. * @param handleCompletionSignals if true, handles completion signals internally. */ virtual void setCompletionObject(KCompletion *completionObject, bool handleSignals = true); /** * Enables this object to handle completion and rotation * events internally. * * This function simply assigns a boolean value that * indicates whether it should handle rotation and * completion events or not. Note that this does not * stop the object from emitting signals when these * events occur. * * @param handle if true, it handles completion and rotation internally. */ virtual void setHandleSignals(bool handle); /** * Returns true if the completion object is deleted * upon this widget's destruction. * * See setCompletionObject() and enableCompletion() * for details. * * @return true if the completion object will be deleted * automatically */ bool isCompletionObjectAutoDeleted() const; /** * Sets the completion object when this widget's destructor * is called. * * If the argument is set to true, the completion object * is deleted when this widget's destructor is called. * * @param autoDelete if true, delete completion object on destruction. */ void setAutoDeleteCompletionObject(bool autoDelete); /** * Sets the widget's ability to emit text completion and * rotation signals. * * Invoking this function with @p enable set to @c false will * cause the completion and rotation signals not to be emitted. * However, unlike setting the completion object to @c nullptr * using setCompletionObject, disabling the emission of * the signals through this method does not affect the current * completion object. * * There is no need to invoke this function by default. When a * completion object is created through completionObject or * setCompletionObject, these signals are set to emit * automatically. Also note that disabling this signals will not * necessarily interfere with the objects' ability to handle these * events internally. See setHandleSignals. * * @param enable if false, disables the emission of completion and rotation signals. */ void setEnableSignals(bool enable); /** * Returns true if the object handles the signals. * * @return true if this signals are handled internally. */ bool handleSignals() const; /** * Returns true if the object emits the signals. * * @return true if signals are emitted */ bool emitSignals() const; /** * Sets whether the object emits rotation signals. * * @param emitRotationSignals if false, disables the emission of rotation signals. */ void setEmitSignals(bool emitRotationSignals); /** * Sets the type of completion to be used. * * @param mode Completion type * @see CompletionMode */ virtual void setCompletionMode(KCompletion::CompletionMode mode); /** * Returns the current completion mode. * * @return the completion mode. */ KCompletion::CompletionMode completionMode() const; /** * Sets the key binding to be used for manual text * completion, text rotation in a history list as * well as a completion list. * * * When the keys set by this function are pressed, a * signal defined by the inheriting widget will be activated. * If the default value or 0 is specified by the second * parameter, then the key binding as defined in the global * setting should be used. This method returns false * when @p key is negative or the supplied key binding conflicts * with another one set for another feature. * * NOTE: To use a modifier key (Shift, Ctrl, Alt) as part of * the key binding simply @p sum up the values of the * modifier and the actual key. For example, to use CTRL+E, supply * @c "Qt::CtrlButton + Qt::Key_E" as the second argument to this * function. * * @param item the feature whose key binding needs to be set: * @li TextCompletion the manual completion key binding. * @li PrevCompletionMatch the previous match key for multiple completion. * @li NextCompletionMatch the next match key for for multiple completion. * @li SubstringCompletion the key for substring completion * @param key key binding used to rotate down in a list. * @return true if key binding is successfully set. * @see keyBinding */ bool setKeyBinding(KeyBindingType item, const QList &key); /** * Returns the key binding used for the specified item. * * This method returns the key binding used to activate * the feature given by @p item. If the binding * contains modifier key(s), the sum of the modifier key * and the actual key code is returned. * * @param item the item to check * @return the key binding used for the feature given by @p item. * @since 5.0 * @see setKeyBinding */ QList keyBinding(KeyBindingType item) const; +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(5, 0) /** * @deprecated since 5.0, use keyBinding instead */ -#ifndef KCOMPLETION_NO_DEPRECATED - KCOMPLETION_DEPRECATED QList getKeyBinding(KeyBindingType item) const + KCOMPLETION_DEPRECATED_VERSION(5, 0, "Use KCompletionBase::keyBinding(KeyBindingType)") + QList getKeyBinding(KeyBindingType item) const { return keyBinding(item); } #endif /** * Sets this object to use global values for key bindings. * * This method changes the values of the key bindings for * rotation and completion features to the default values * provided in KGlobalSettings. * * NOTE: By default, inheriting widgets should use the * global key bindings so that there is no need to * call this method. */ void useGlobalKeyBindings(); /** * A pure virtual function that must be implemented by * all inheriting classes. * * This function is intended to allow external completion * implementations to set completed text appropriately. It * is mostly relevant when the completion mode is set to * CompletionAuto and CompletionManual modes. See * KCompletionBase::setCompletedText. * Does nothing in CompletionPopup mode, as all available * matches will be shown in the popup. * * @param text the completed text to be set in the widget. */ virtual void setCompletedText(const QString &text) = 0; /** * A pure virtual function that must be implemented by * all inheriting classes. * @param items the list of completed items * @param autoSuggest if @c true, the first element of @p items * is automatically completed (i.e. preselected). */ virtual void setCompletedItems(const QStringList &items, bool autoSuggest = true) = 0; /** * Returns a pointer to the completion object. * * This method is only different from completionObject() * in that it does not create a new KCompletion object even if * the internal pointer is @c NULL. Use this method to get the * pointer to a completion object when inheriting so that you * will not inadvertently create it. * * @return the completion object or @c NULL if one does not exist. */ KCompletion *compObj() const; protected: /** * Returns a key binding map. * * This method is the same as getKeyBinding(), except that it * returns the whole keymap containing the key bindings. * * @return the key binding used for the feature given by @p item. * @since 5.0 */ KeyBindingMap keyBindingMap() const; +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(5, 0) /** * @deprecated since 5.0, use keyBindingMap instead */ -#ifndef KCOMPLETION_NO_DEPRECATED - KCOMPLETION_DEPRECATED KeyBindingMap getKeyBindings() const + KCOMPLETION_DEPRECATED_VERSION(5, 0, "Use KCompletionBase::keyBindingMap()") + KeyBindingMap getKeyBindings() const { return keyBindingMap(); } #endif /** * Sets the keymap. * * @param keyBindingMap */ void setKeyBindingMap(KeyBindingMap keyBindingMap); /** * Sets or removes the delegation object. If a delegation object is * set, all function calls will be forwarded to the delegation object. * @param delegate the delegation object, or @c nullptr to remove it */ void setDelegate(KCompletionBase *delegate); /** * Returns the delegation object. * @return the delegation object, or @c nullptr if there is none * @see setDelegate() */ KCompletionBase *delegate() const; /** Virtual hook, used to add new "virtual" functions while maintaining binary compatibility. Unused in this class. */ virtual void virtual_hook(int id, void *data); private: Q_DISABLE_COPY(KCompletionBase) const QScopedPointer d_ptr; }; #endif // KCOMPLETIONBASE_H diff --git a/src/kcompletionbox.h b/src/kcompletionbox.h index 5f2562d..91112b0 100644 --- a/src/kcompletionbox.h +++ b/src/kcompletionbox.h @@ -1,253 +1,254 @@ /* This file is part of the KDE libraries Copyright (c) 2000 Carsten Pfeiffer 2000 Stefan Schimanski <1Stein@gmx.de> 2000,2001,2002,2003,2004 Dawit Alemayehu This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License (LGPL) 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 KCOMPLETIONBOX_H #define KCOMPLETIONBOX_H #include #include "kcompletion_export.h" class KCompletionBoxPrivate; class QEvent; /** * @class KCompletionBox kcompletionbox.h KCompletionBox * * @short A helper widget for "completion-widgets" (KLineEdit, KComboBox)) * * A little utility class for "completion-widgets", like KLineEdit or * KComboBox. KCompletionBox is a listbox, displayed as a rectangle without * any window decoration, usually directly under the lineedit or combobox. * It is filled with all possible matches for a completion, so the user * can select the one he wants. * * It is used when KCompletion::CompletionMode == CompletionPopup or CompletionPopupAuto. * * @author Carsten Pfeiffer */ class KCOMPLETION_EXPORT KCompletionBox : public QListWidget { Q_OBJECT Q_DECLARE_PRIVATE(KCompletionBox) Q_PROPERTY(bool isTabHandling READ isTabHandling WRITE setTabHandling) Q_PROPERTY(QString cancelledText READ cancelledText WRITE setCancelledText) Q_PROPERTY(bool activateOnSelect READ activateOnSelect WRITE setActivateOnSelect) public: /** * Constructs a KCompletionBox. * * The parent widget is used to give the focus back when pressing the * up-button on the very first item. */ explicit KCompletionBox(QWidget *parent = nullptr); /** * Destroys the box */ ~KCompletionBox() override; QSize sizeHint() const override; /** * @returns true if selecting an item results in the emission of the selected() signal. */ bool activateOnSelect() const; /** * Returns a list of all items currently in the box. */ QStringList items() const; /** * @returns true if this widget is handling Tab-key events to traverse the * items in the dropdown list, otherwise false. * * Default is true. * * @see setTabHandling */ bool isTabHandling() const; /** * @returns the text set via setCancelledText() or QString(). */ QString cancelledText() const; public Q_SLOTS: /** * Inserts @p items into the box. Does not clear the items before. * @p index determines at which position @p items will be inserted. * (defaults to appending them at the end) */ void insertItems(const QStringList &items, int index = -1); /** * Clears the box and inserts @p items. */ void setItems(const QStringList &items); /** * Adjusts the size of the box to fit the width of the parent given in the * constructor and pops it up at the most appropriate place, relative to * the parent. * * Depending on the screensize and the position of the parent, this may * be a different place, however the default is to pop it up and the * lower left corner of the parent. * * Make sure to hide() the box when appropriate. */ virtual void popup(); /** * Makes this widget (when visible) capture Tab-key events to traverse the * items in the dropdown list (Tab goes down, Shift+Tab goes up). * * On by default, but should be turned off when used in combination with KUrlCompletion. * When off, KLineEdit handles Tab itself, making it select the current item from the completion box, * which is particularly useful when using KUrlCompletion. * * @see isTabHandling */ void setTabHandling(bool enable); /** * Sets the text to be emitted if the user chooses not to * pick from the available matches. * * If the cancelled text is not set through this function, the * userCancelled signal will not be emitted. * * @see userCancelled( const QString& ) * @param text the text to be emitted if the user cancels this box */ void setCancelledText(const QString &text); /** * Set whether or not the selected signal should be emitted when an * item is selected. By default the selected() signal is emitted. * * @param doEmit false if the signal should not be emitted. */ void setActivateOnSelect(bool doEmit); /** * Moves the selection one line down or select the first item if nothing is selected yet. */ void down(); /** * Moves the selection one line up or select the first item if nothing is selected yet. */ void up(); /** * Moves the selection one page down. */ void pageDown(); /** * Moves the selection one page up. */ void pageUp(); /** * Moves the selection up to the first item. */ void home(); /** * Moves the selection down to the last item. */ void end(); /** * Reimplemented for internal reasons. API is unaffected. * Call it only if you really need it (i.e. the widget was hidden before) to have better performance. */ void setVisible(bool visible) override; Q_SIGNALS: /** * Emitted when an item was selected, contains the text of * the selected item. */ void activated(const QString &); /** * Emitted whenever the user chooses to ignore the available * selections and closes this box. */ void userCancelled(const QString &); protected: /** * This calculates the size of the dropdown and the relative position of the top * left corner with respect to the parent widget. This matches the geometry and position * normally used by K/QComboBox when used with one. */ QRect calculateGeometry() const; +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(5, 0) /** * @deprecated since 5.0, use resizeAndReposition instead. */ -#ifndef KCOMPLETION_NO_DEPRECATED - KCOMPLETION_DEPRECATED void sizeAndPosition() + KCOMPLETION_DEPRECATED_VERSION(5, 0, "Use KCompletionBox::resizeAndReposition()") + void sizeAndPosition() { resizeAndReposition(); } #endif /** * This properly resizes and repositions the listbox. * * @since 5.0 */ void resizeAndReposition(); /** * Reimplemented from QListWidget to get events from the viewport (to hide * this widget on mouse-click, Escape-presses, etc. */ bool eventFilter(QObject *, QEvent *) override; /** * The preferred global coordinate at which the completion box's top left corner * should be positioned. */ virtual QPoint globalPositionHint() const; protected Q_SLOTS: /** * Called when an item was activated. Emits * activated() with the item. */ virtual void slotActivated(QListWidgetItem *); private: const QScopedPointer d_ptr; Q_PRIVATE_SLOT(d_func(), void _k_itemClicked(QListWidgetItem *)) }; #endif // KCOMPLETIONBOX_H diff --git a/src/klineedit.cpp b/src/klineedit.cpp index 47897ce..acabe6f 100644 --- a/src/klineedit.cpp +++ b/src/klineedit.cpp @@ -1,1484 +1,1488 @@ /* This file is part of the KDE libraries Copyright (C) 1997 Sven Radej (sven.radej@iname.com) Copyright (c) 1999 Patrick Ward Copyright (c) 1999 Preston Brown Re-designed for KDE 2.x by Copyright (c) 2000, 2001 Dawit Alemayehu Copyright (c) 2000, 2001 Carsten Pfeiffer This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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 "klineedit.h" #include "klineedit_p.h" #include #include #include #include #include #include #include #include #include #include #include #include KLineEditPrivate::~KLineEditPrivate() { // causes a weird crash in KWord at least, so let Qt delete it for us. // delete completionBox; } void KLineEditPrivate::_k_textChanged(const QString &text) { Q_Q(KLineEdit); // COMPAT (as documented): emit userTextChanged whenever textChanged is emitted if (!completionRunning && (text != userText)) { userText = text; -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(4, 5) emit q->userTextChanged(text); #endif } } // Call this when a completion operation changes the lineedit text // "as if it had been edited by the user". void KLineEditPrivate::updateUserText(const QString &text) { Q_Q(KLineEdit); if (!completionRunning && (text != userText)) { userText = text; q->setModified(true); -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(4, 5) emit q->userTextChanged(text); #endif emit q->textEdited(text); emit q->textChanged(text); } } bool KLineEditPrivate::s_backspacePerformsCompletion = false; bool KLineEditPrivate::s_initialized = false; void KLineEditPrivate::init() { Q_Q(KLineEdit); //--- completionBox = nullptr; handleURLDrops = true; trapReturnKeyEvents = false; userSelection = true; autoSuggest = false; disableRestoreSelection = false; enableSqueezedText = false; completionRunning = false; if (!s_initialized) { KConfigGroup config(KSharedConfig::openConfig(), "General"); s_backspacePerformsCompletion = config.readEntry("Backspace performs completion", false); s_initialized = true; } urlDropEventFilter = new LineEditUrlDropEventFilter(q); // i18n: Placeholder text in line edit widgets is the text appearing // before any user input, briefly explaining to the user what to type // (e.g. "Enter search pattern"). // By default the text is set in italic, which may not be appropriate // for some languages and scripts (e.g. for CJK ideographs). QString metaMsg = KLineEdit::tr("1", "Italic placeholder text in line edits: 0 no, 1 yes"); italicizePlaceholder = (metaMsg.trimmed() != QLatin1Char('0')); //--- possibleTripleClick = false; bgRole = q->backgroundRole(); // Enable the context menu by default. q->QLineEdit::setContextMenuPolicy(Qt::DefaultContextMenu); KCursor::setAutoHideCursor(q, true, true); KCompletion::CompletionMode mode = q->completionMode(); autoSuggest = (mode == KCompletion::CompletionMan || mode == KCompletion::CompletionPopupAuto || mode == KCompletion::CompletionAuto); q->connect(q, SIGNAL(selectionChanged()), q, SLOT(_k_restoreSelectionColors())); if (handleURLDrops) { q->installEventFilter(urlDropEventFilter); } const QPalette p = q->palette(); if (!previousHighlightedTextColor.isValid()) { previousHighlightedTextColor = p.color(QPalette::Normal, QPalette::HighlightedText); } if (!previousHighlightColor.isValid()) { previousHighlightColor = p.color(QPalette::Normal, QPalette::Highlight); } q->connect(q, SIGNAL(textChanged(QString)), q, SLOT(_k_textChanged(QString))); } KLineEdit::KLineEdit(const QString &string, QWidget *parent) : QLineEdit(string, parent), d_ptr(new KLineEditPrivate(this)) { Q_D(KLineEdit); d->init(); } KLineEdit::KLineEdit(QWidget *parent) : QLineEdit(parent), d_ptr(new KLineEditPrivate(this)) { Q_D(KLineEdit); d->init(); } KLineEdit::~KLineEdit() { } -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(5, 0) QString KLineEdit::clickMessage() const { return placeholderText(); } #endif +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(5, 46) void KLineEdit::setClearButtonShown(bool show) { setClearButtonEnabled(show); } +#endif +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(5, 46) bool KLineEdit::isClearButtonShown() const { return isClearButtonEnabled(); } +#endif QSize KLineEdit::clearButtonUsedSize() const { QSize s; if (isClearButtonEnabled()) { // from qlineedit_p.cpp const int iconSize = height() < 34 ? 16 : 32; const int buttonWidth = iconSize + 6; const int buttonHeight = iconSize + 2; s = QSize(buttonWidth, buttonHeight); } return s; } void KLineEdit::setCompletionMode(KCompletion::CompletionMode mode) { Q_D(KLineEdit); KCompletion::CompletionMode oldMode = completionMode(); if (oldMode != mode && (oldMode == KCompletion::CompletionPopup || oldMode == KCompletion::CompletionPopupAuto) && d->completionBox && d->completionBox->isVisible()) { d->completionBox->hide(); } // If the widgets echo mode is not Normal, no completion // feature will be enabled even if one is requested. if (echoMode() != QLineEdit::Normal) { mode = KCompletion::CompletionNone; // Override the request. } if (!KAuthorized::authorize(QStringLiteral("lineedit_text_completion"))) { mode = KCompletion::CompletionNone; } if (mode == KCompletion::CompletionPopupAuto || mode == KCompletion::CompletionAuto || mode == KCompletion::CompletionMan) { d->autoSuggest = true; } else { d->autoSuggest = false; } KCompletionBase::setCompletionMode(mode); } void KLineEdit::setCompletionModeDisabled(KCompletion::CompletionMode mode, bool disable) { Q_D(KLineEdit); d->disableCompletionMap[ mode ] = disable; } void KLineEdit::setCompletedText(const QString &t, bool marked) { Q_D(KLineEdit); if (!d->autoSuggest) { return; } const QString txt = text(); if (t != txt) { setText(t); if (marked) { setSelection(t.length(), txt.length() - t.length()); } setUserSelection(false); } else { setUserSelection(true); } } void KLineEdit::setCompletedText(const QString &text) { KCompletion::CompletionMode mode = completionMode(); const bool marked = (mode == KCompletion::CompletionAuto || mode == KCompletion::CompletionMan || mode == KCompletion::CompletionPopup || mode == KCompletion::CompletionPopupAuto); setCompletedText(text, marked); } void KLineEdit::rotateText(KCompletionBase::KeyBindingType type) { KCompletion *comp = compObj(); if (comp && (type == KCompletionBase::PrevCompletionMatch || type == KCompletionBase::NextCompletionMatch)) { QString input; if (type == KCompletionBase::PrevCompletionMatch) { input = comp->previousMatch(); } else { input = comp->nextMatch(); } // Skip rotation if previous/next match is null or the same text if (input.isEmpty() || input == displayText()) { return; } setCompletedText(input, hasSelectedText()); } } void KLineEdit::makeCompletion(const QString &text) { Q_D(KLineEdit); KCompletion *comp = compObj(); KCompletion::CompletionMode mode = completionMode(); if (!comp || mode == KCompletion::CompletionNone) { return; // No completion object... } const QString match = comp->makeCompletion(text); if (mode == KCompletion::CompletionPopup || mode == KCompletion::CompletionPopupAuto) { if (match.isEmpty()) { if (d->completionBox) { d->completionBox->hide(); d->completionBox->clear(); } } else { setCompletedItems(comp->allMatches()); } } else { // Auto, ShortAuto (Man) and Shell // all other completion modes // If no match or the same match, simply return without completing. if (match.isEmpty() || match == text) { return; } if (mode != KCompletion::CompletionShell) { setUserSelection(false); } if (d->autoSuggest) { setCompletedText(match); } } } void KLineEdit::setReadOnly(bool readOnly) { Q_D(KLineEdit); // Do not do anything if nothing changed... if (readOnly == isReadOnly()) { return; } QLineEdit::setReadOnly(readOnly); if (readOnly) { d->bgRole = backgroundRole(); setBackgroundRole(QPalette::Window); if (d->enableSqueezedText && d->squeezedText.isEmpty()) { d->squeezedText = text(); d->setSqueezedText(); } } else { if (!d->squeezedText.isEmpty()) { setText(d->squeezedText); d->squeezedText.clear(); } setBackgroundRole(d->bgRole); } } void KLineEdit::setSqueezedText(const QString &text) { setSqueezedTextEnabled(true); setText(text); } void KLineEdit::setSqueezedTextEnabled(bool enable) { Q_D(KLineEdit); d->enableSqueezedText = enable; } bool KLineEdit::isSqueezedTextEnabled() const { Q_D(const KLineEdit); return d->enableSqueezedText; } void KLineEdit::setText(const QString &text) { Q_D(KLineEdit); if (d->enableSqueezedText && isReadOnly()) { d->squeezedText = text; d->setSqueezedText(); return; } QLineEdit::setText(text); } void KLineEditPrivate::setSqueezedText() { Q_Q(KLineEdit); squeezedStart = 0; squeezedEnd = 0; const QString fullText = squeezedText; const int fullLength = fullText.length(); const QFontMetrics fm(q->fontMetrics()); const int labelWidth = q->size().width() - 2 * q->style()->pixelMetric(QStyle::PM_DefaultFrameWidth) - 2; const int textWidth = fm.boundingRect(fullText).width(); // TODO: investigate use of QFontMetrics::elidedText for this if (textWidth > labelWidth) { // TODO: better would be "…" char (0x2026), but for that one would need to ensure it's from the main font, // otherwise if resulting in use of a new fallback font this can affect the metrics of the complete text, // resulting in shifted characters const QString ellipsisText = QStringLiteral("..."); // start with the dots only QString squeezedText = ellipsisText; int squeezedWidth = fm.boundingRect(squeezedText).width(); // estimate how many letters we can add to the dots on both sides int letters = fullText.length() * (labelWidth - squeezedWidth) / textWidth / 2; squeezedText = fullText.leftRef(letters) + ellipsisText + fullText.rightRef(letters); squeezedWidth = fm.boundingRect(squeezedText).width(); if (squeezedWidth < labelWidth) { // we estimated too short // add letters while text < label do { letters++; squeezedText = fullText.leftRef(letters) + ellipsisText + fullText.rightRef(letters); squeezedWidth = fm.boundingRect(squeezedText).width(); } while (squeezedWidth < labelWidth && letters <= fullLength / 2); letters--; squeezedText = fullText.leftRef(letters) + ellipsisText + fullText.rightRef(letters); } else if (squeezedWidth > labelWidth) { // we estimated too long // remove letters while text > label do { letters--; squeezedText = fullText.leftRef(letters) + ellipsisText + fullText.rightRef(letters); squeezedWidth = fm.boundingRect(squeezedText).width(); } while (squeezedWidth > labelWidth && letters >= 5); } if (letters < 5) { // too few letters added -> we give up squeezing q->QLineEdit::setText(fullText); } else { q->QLineEdit::setText(squeezedText); squeezedStart = letters; squeezedEnd = fullText.length() - letters; } q->setToolTip(fullText); } else { q->QLineEdit::setText(fullText); q->setToolTip(QString()); QToolTip::showText(q->pos(), QString()); // hide } q->setCursorPosition(0); } void KLineEdit::copy() const { Q_D(const KLineEdit); if (!d->copySqueezedText(true)) { QLineEdit::copy(); } } bool KLineEditPrivate::copySqueezedText(bool copy) const { Q_Q(const KLineEdit); if (!squeezedText.isEmpty() && squeezedStart) { KLineEdit *that = const_cast(q); if (!that->hasSelectedText()) { return false; } int start = q->selectionStart(), end = start + q->selectedText().length(); if (start >= squeezedStart + 3) { start = start - 3 - squeezedStart + squeezedEnd; } else if (start > squeezedStart) { start = squeezedStart; } if (end >= squeezedStart + 3) { end = end - 3 - squeezedStart + squeezedEnd; } else if (end > squeezedStart) { end = squeezedEnd; } if (start == end) { return false; } QString t = squeezedText; t = t.mid(start, end - start); q->disconnect(QApplication::clipboard(), SIGNAL(selectionChanged()), q, nullptr); QApplication::clipboard()->setText(t, copy ? QClipboard::Clipboard : QClipboard::Selection); q->connect(QApplication::clipboard(), SIGNAL(selectionChanged()), q, SLOT(_q_clipboardChanged())); return true; } return false; } void KLineEdit::resizeEvent(QResizeEvent *ev) { Q_D(KLineEdit); if (!d->squeezedText.isEmpty()) { d->setSqueezedText(); } QLineEdit::resizeEvent(ev); } void KLineEdit::keyPressEvent(QKeyEvent *e) { Q_D(KLineEdit); const int key = e->key() | e->modifiers(); if (KStandardShortcut::copy().contains(key)) { copy(); return; } else if (KStandardShortcut::paste().contains(key)) { // TODO: // we should restore the original text (not autocompleted), otherwise the paste // will get into troubles Bug: 134691 if (!isReadOnly()) { paste(); } return; } else if (KStandardShortcut::pasteSelection().contains(key)) { QString text = QApplication::clipboard()->text(QClipboard::Selection); insert(text); deselect(); return; } else if (KStandardShortcut::cut().contains(key)) { if (!isReadOnly()) { cut(); } return; } else if (KStandardShortcut::undo().contains(key)) { if (!isReadOnly()) { undo(); } return; } else if (KStandardShortcut::redo().contains(key)) { if (!isReadOnly()) { redo(); } return; } else if (KStandardShortcut::deleteWordBack().contains(key)) { cursorWordBackward(true); if (hasSelectedText() && !isReadOnly()) { del(); } e->accept(); return; } else if (KStandardShortcut::deleteWordForward().contains(key)) { // Workaround for QT bug where cursorWordForward(true); if (hasSelectedText() && !isReadOnly()) { del(); } e->accept(); return; } else if (KStandardShortcut::backwardWord().contains(key)) { cursorWordBackward(false); e->accept(); return; } else if (KStandardShortcut::forwardWord().contains(key)) { cursorWordForward(false); e->accept(); return; } else if (KStandardShortcut::beginningOfLine().contains(key)) { home(false); e->accept(); return; } else if (KStandardShortcut::endOfLine().contains(key)) { end(false); e->accept(); return; } // Filter key-events if EchoMode is normal and // completion mode is not set to CompletionNone if (echoMode() == QLineEdit::Normal && completionMode() != KCompletion::CompletionNone) { if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) { const bool trap = (d->completionBox && d->completionBox->isVisible()); const bool stopEvent = (trap || (d->trapReturnKeyEvents && (e->modifiers() == Qt::NoButton || e->modifiers() == Qt::KeypadModifier))); if (stopEvent) { emit QLineEdit::returnPressed(); e->accept(); } emit returnPressed(displayText()); if (trap) { d->completionBox->hide(); deselect(); setCursorPosition(text().length()); } // Eat the event if the user asked for it, or if a completionbox was visible if (stopEvent) { return; } } const KeyBindingMap keys = keyBindingMap(); const KCompletion::CompletionMode mode = completionMode(); const bool noModifier = (e->modifiers() == Qt::NoButton || e->modifiers() == Qt::ShiftModifier || e->modifiers() == Qt::KeypadModifier); if ((mode == KCompletion::CompletionAuto || mode == KCompletion::CompletionPopupAuto || mode == KCompletion::CompletionMan) && noModifier) { if (!d->userSelection && hasSelectedText() && (e->key() == Qt::Key_Right || e->key() == Qt::Key_Left) && e->modifiers() == Qt::NoButton) { const QString old_txt = text(); d->disableRestoreSelection = true; const int start = selectionStart(); deselect(); QLineEdit::keyPressEvent(e); const int cPosition = cursorPosition(); setText(old_txt); // keep cursor at cPosition setSelection(old_txt.length(), cPosition - old_txt.length()); if (e->key() == Qt::Key_Right && cPosition > start) { //the user explicitly accepted the autocompletion d->updateUserText(text()); } d->disableRestoreSelection = false; return; } if (e->key() == Qt::Key_Escape) { if (hasSelectedText() && !d->userSelection) { del(); setUserSelection(true); } // Don't swallow the Escape press event for the case // of dialogs, which have Escape associated to Cancel e->ignore(); return; } } if ((mode == KCompletion::CompletionAuto || mode == KCompletion::CompletionMan) && noModifier) { const QString keycode = e->text(); if (!keycode.isEmpty() && (keycode.unicode()->isPrint() || e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete)) { const bool hasUserSelection = d->userSelection; const bool hadSelection = hasSelectedText(); bool cursorNotAtEnd = false; const int start = selectionStart(); const int cPos = cursorPosition(); // When moving the cursor, we want to keep the autocompletion as an // autocompletion, so we want to process events at the cursor position // as if there was no selection. After processing the key event, we // can set the new autocompletion again. if (hadSelection && !hasUserSelection && start > cPos) { del(); setCursorPosition(cPos); cursorNotAtEnd = true; } d->disableRestoreSelection = true; QLineEdit::keyPressEvent(e); d->disableRestoreSelection = false; QString txt = text(); int len = txt.length(); if (!hasSelectedText() && len /*&& cursorPosition() == len */) { if (e->key() == Qt::Key_Backspace) { if (hadSelection && !hasUserSelection && !cursorNotAtEnd) { backspace(); txt = text(); len = txt.length(); } if (!d->s_backspacePerformsCompletion || !len) { d->autoSuggest = false; } } if (e->key() == Qt::Key_Delete) { d->autoSuggest = false; } doCompletion(txt); if ((e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete)) { d->autoSuggest = true; } e->accept(); } return; } } else if ((mode == KCompletion::CompletionPopup || mode == KCompletion::CompletionPopupAuto) && noModifier && !e->text().isEmpty()) { const QString old_txt = text(); const bool hasUserSelection = d->userSelection; const bool hadSelection = hasSelectedText(); bool cursorNotAtEnd = false; const int start = selectionStart(); const int cPos = cursorPosition(); const QString keycode = e->text(); // When moving the cursor, we want to keep the autocompletion as an // autocompletion, so we want to process events at the cursor position // as if there was no selection. After processing the key event, we // can set the new autocompletion again. if (hadSelection && !hasUserSelection && start > cPos && ((!keycode.isEmpty() && keycode.unicode()->isPrint()) || e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete)) { del(); setCursorPosition(cPos); cursorNotAtEnd = true; } const int selectedLength = selectedText().length(); d->disableRestoreSelection = true; QLineEdit::keyPressEvent(e); d->disableRestoreSelection = false; if ((selectedLength != selectedText().length()) && !hasUserSelection) { d->_k_restoreSelectionColors(); // and set userSelection to true } QString txt = text(); int len = txt.length(); if ((txt != old_txt || txt != e->text()) && len/* && ( cursorPosition() == len || force )*/ && ((!keycode.isEmpty() && keycode.unicode()->isPrint()) || e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete)) { if (e->key() == Qt::Key_Backspace) { if (hadSelection && !hasUserSelection && !cursorNotAtEnd) { backspace(); txt = text(); len = txt.length(); } if (!d->s_backspacePerformsCompletion) { d->autoSuggest = false; } } if (e->key() == Qt::Key_Delete) { d->autoSuggest = false; } if (d->completionBox) { d->completionBox->setCancelledText(txt); } doCompletion(txt); if ((e->key() == Qt::Key_Backspace || e->key() == Qt::Key_Delete) && mode == KCompletion::CompletionPopupAuto) { d->autoSuggest = true; } e->accept(); } else if (!len && d->completionBox && d->completionBox->isVisible()) { d->completionBox->hide(); } return; } else if (mode == KCompletion::CompletionShell) { // Handles completion. QList cut; if (keys[TextCompletion].isEmpty()) { cut = KStandardShortcut::shortcut(KStandardShortcut::TextCompletion); } else { cut = keys[TextCompletion]; } if (cut.contains(key)) { // Emit completion if the completion mode is CompletionShell // and the cursor is at the end of the string. const QString txt = text(); const int len = txt.length(); if (cursorPosition() == len && len != 0) { doCompletion(txt); return; } } else if (d->completionBox) { d->completionBox->hide(); } } // handle rotation // Handles previous match QList cut; if (keys[PrevCompletionMatch].isEmpty()) { cut = KStandardShortcut::shortcut(KStandardShortcut::PrevCompletion); } else { cut = keys[PrevCompletionMatch]; } if (cut.contains(key)) { if (emitSignals()) { emit textRotation(KCompletionBase::PrevCompletionMatch); } if (handleSignals()) { rotateText(KCompletionBase::PrevCompletionMatch); } return; } // Handles next match if (keys[NextCompletionMatch].isEmpty()) { cut = KStandardShortcut::shortcut(KStandardShortcut::NextCompletion); } else { cut = keys[NextCompletionMatch]; } if (cut.contains(key)) { if (emitSignals()) { emit textRotation(KCompletionBase::NextCompletionMatch); } if (handleSignals()) { rotateText(KCompletionBase::NextCompletionMatch); } return; } // substring completion if (compObj()) { QList cut; if (keys[SubstringCompletion].isEmpty()) { cut = KStandardShortcut::shortcut(KStandardShortcut::SubstringCompletion); } else { cut = keys[SubstringCompletion]; } if (cut.contains(key)) { if (emitSignals()) { emit substringCompletion(text()); } if (handleSignals()) { setCompletedItems(compObj()->substringCompletion(text())); e->accept(); } return; } } } const int selectedLength = selectedText().length(); // Let QLineEdit handle any other keys events. QLineEdit::keyPressEvent(e); if (selectedLength != selectedText().length()) { d->_k_restoreSelectionColors(); // and set userSelection to true } } void KLineEdit::mouseDoubleClickEvent(QMouseEvent *e) { Q_D(KLineEdit); if (e->button() == Qt::LeftButton) { d->possibleTripleClick = true; QTimer::singleShot(QApplication::doubleClickInterval(), this, SLOT(_k_tripleClickTimeout())); } QLineEdit::mouseDoubleClickEvent(e); } void KLineEdit::mousePressEvent(QMouseEvent *e) { Q_D(KLineEdit); if (e->button() == Qt::LeftButton && d->possibleTripleClick) { selectAll(); e->accept(); return; } // if middle clicking and if text is present in the clipboard then clear the selection // to prepare paste operation if (e->button() == Qt::MidButton) { if (hasSelectedText() && !isReadOnly()) { if (QApplication::clipboard()->text(QClipboard::Selection).length() > 0) { backspace(); } } } QLineEdit::mousePressEvent(e); } void KLineEdit::mouseReleaseEvent(QMouseEvent *e) { Q_D(KLineEdit); QLineEdit::mouseReleaseEvent(e); if (QApplication::clipboard()->supportsSelection()) { if (e->button() == Qt::LeftButton) { // Fix copying of squeezed text if needed d->copySqueezedText(false); } } } void KLineEditPrivate::_k_tripleClickTimeout() { possibleTripleClick = false; } QMenu *KLineEdit::createStandardContextMenu() { Q_D(KLineEdit); QMenu *popup = QLineEdit::createStandardContextMenu(); if (!isReadOnly()) { // FIXME: This code depends on Qt's action ordering. const QList actionList = popup->actions(); enum { UndoAct, RedoAct, Separator1, CutAct, CopyAct, PasteAct, DeleteAct, ClearAct, Separator2, SelectAllAct, NCountActs }; QAction *separatorAction = nullptr; // separator we want is right after Delete right now. const int idx = actionList.indexOf(actionList[DeleteAct]) + 1; if (idx < actionList.count()) { separatorAction = actionList.at(idx); } if (separatorAction) { QAction *clearAllAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-clear")), tr("C&lear"), this); clearAllAction->setShortcuts(QKeySequence::keyBindings(QKeySequence::DeleteCompleteLine)); connect(clearAllAction, &QAction::triggered, this, &QLineEdit::clear); if (text().isEmpty()) { clearAllAction->setEnabled(false); } popup->insertAction(separatorAction, clearAllAction); } } // If a completion object is present and the input // widget is not read-only, show the Text Completion // menu item. if (compObj() && !isReadOnly() && KAuthorized::authorize(QStringLiteral("lineedit_text_completion"))) { QMenu *subMenu = popup->addMenu(QIcon::fromTheme(QStringLiteral("text-completion")), tr("Text Completion", "@title:menu")); connect(subMenu, SIGNAL(triggered(QAction*)), this, SLOT(_k_completionMenuActivated(QAction*))); popup->addSeparator(); QActionGroup *ag = new QActionGroup(this); d->noCompletionAction = ag->addAction(tr("None", "@item:inmenu Text Completion")); d->shellCompletionAction = ag->addAction(tr("Manual", "@item:inmenu Text Completion")); d->autoCompletionAction = ag->addAction(tr("Automatic", "@item:inmenu Text Completion")); d->popupCompletionAction = ag->addAction(tr("Dropdown List", "@item:inmenu Text Completion")); d->shortAutoCompletionAction = ag->addAction(tr("Short Automatic", "@item:inmenu Text Completion")); d->popupAutoCompletionAction = ag->addAction(tr("Dropdown List && Automatic", "@item:inmenu Text Completion")); subMenu->addActions(ag->actions()); //subMenu->setAccel( KStandardShortcut::completion(), ShellCompletion ); d->shellCompletionAction->setCheckable(true); d->noCompletionAction->setCheckable(true); d->popupCompletionAction->setCheckable(true); d->autoCompletionAction->setCheckable(true); d->shortAutoCompletionAction->setCheckable(true); d->popupAutoCompletionAction->setCheckable(true); d->shellCompletionAction->setEnabled(!d->disableCompletionMap[ KCompletion::CompletionShell ]); d->noCompletionAction->setEnabled(!d->disableCompletionMap[ KCompletion::CompletionNone ]); d->popupCompletionAction->setEnabled(!d->disableCompletionMap[ KCompletion::CompletionPopup ]); d->autoCompletionAction->setEnabled(!d->disableCompletionMap[ KCompletion::CompletionAuto ]); d->shortAutoCompletionAction->setEnabled(!d->disableCompletionMap[ KCompletion::CompletionMan ]); d->popupAutoCompletionAction->setEnabled(!d->disableCompletionMap[ KCompletion::CompletionPopupAuto ]); const KCompletion::CompletionMode mode = completionMode(); d->noCompletionAction->setChecked(mode == KCompletion::CompletionNone); d->shellCompletionAction->setChecked(mode == KCompletion::CompletionShell); d->popupCompletionAction->setChecked(mode == KCompletion::CompletionPopup); d->autoCompletionAction->setChecked(mode == KCompletion::CompletionAuto); d->shortAutoCompletionAction->setChecked(mode == KCompletion::CompletionMan); d->popupAutoCompletionAction->setChecked(mode == KCompletion::CompletionPopupAuto); const KCompletion::CompletionMode defaultMode = KCompletion::CompletionPopup; if (mode != defaultMode && !d->disableCompletionMap[ defaultMode ]) { subMenu->addSeparator(); d->defaultAction = subMenu->addAction(tr("Default", "@item:inmenu Text Completion")); } } return popup; } void KLineEdit::contextMenuEvent(QContextMenuEvent *e) { if (QLineEdit::contextMenuPolicy() != Qt::DefaultContextMenu) { return; } QMenu *popup = createStandardContextMenu(); // ### do we really need this? Yes, Please do not remove! This // allows applications to extend the popup menu without having to // inherit from this class! (DA) emit aboutToShowContextMenu(popup); popup->exec(e->globalPos()); delete popup; } void KLineEditPrivate::_k_completionMenuActivated(QAction *act) { Q_Q(KLineEdit); KCompletion::CompletionMode oldMode = q->completionMode(); if (act == noCompletionAction) { q->setCompletionMode(KCompletion::CompletionNone); } else if (act == shellCompletionAction) { q->setCompletionMode(KCompletion::CompletionShell); } else if (act == autoCompletionAction) { q->setCompletionMode(KCompletion::CompletionAuto); } else if (act == popupCompletionAction) { q->setCompletionMode(KCompletion::CompletionPopup); } else if (act == shortAutoCompletionAction) { q->setCompletionMode(KCompletion::CompletionMan); } else if (act == popupAutoCompletionAction) { q->setCompletionMode(KCompletion::CompletionPopupAuto); } else if (act == defaultAction) { q->setCompletionMode(KCompletion::CompletionPopup); } else { return; } if (oldMode != q->completionMode()) { if ((oldMode == KCompletion::CompletionPopup || oldMode == KCompletion::CompletionPopupAuto) && completionBox && completionBox->isVisible()) { completionBox->hide(); } emit q->completionModeChanged(q->completionMode()); } } bool KLineEdit::event(QEvent *ev) { Q_D(KLineEdit); KCursor::autoHideEventFilter(this, ev); if (ev->type() == QEvent::ShortcutOverride) { QKeyEvent *e = static_cast(ev); if (d->overrideShortcut(e)) { ev->accept(); } } else if (ev->type() == QEvent::ApplicationPaletteChange || ev->type() == QEvent::PaletteChange) { // Assume the widget uses the application's palette QPalette p = QApplication::palette(); d->previousHighlightedTextColor = p.color(QPalette::Normal, QPalette::HighlightedText); d->previousHighlightColor = p.color(QPalette::Normal, QPalette::Highlight); setUserSelection(d->userSelection); } else if (ev->type() == QEvent::ChildAdded) { QObject *obj = static_cast(ev)->child(); if (obj) { connect(obj, &QObject::objectNameChanged, this, [this, obj] { if (obj->objectName() == QLatin1String("_q_qlineeditclearaction")) { QAction *action = qobject_cast(obj); connect(action, &QAction::triggered, this, &KLineEdit::clearButtonClicked); } }); } } return QLineEdit::event(ev); } -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(5, 0) void KLineEdit::setUrlDropsEnabled(bool enable) { Q_D(KLineEdit); if (enable && !d->handleURLDrops) { installEventFilter(d->urlDropEventFilter); d->handleURLDrops = true; } else if (!enable && d->handleURLDrops) { removeEventFilter(d->urlDropEventFilter); d->handleURLDrops = false; } } #endif bool KLineEdit::urlDropsEnabled() const { Q_D(const KLineEdit); return d->handleURLDrops; } void KLineEdit::setTrapReturnKey(bool trap) { Q_D(KLineEdit); d->trapReturnKeyEvents = trap; } bool KLineEdit::trapReturnKey() const { Q_D(const KLineEdit); return d->trapReturnKeyEvents; } void KLineEdit::setUrl(const QUrl &url) { setText(url.toDisplayString()); } void KLineEdit::setCompletionBox(KCompletionBox *box) { Q_D(KLineEdit); if (d->completionBox) { return; } d->completionBox = box; if (handleSignals()) { connect(d->completionBox, SIGNAL(currentTextChanged(QString)), SLOT(_k_completionBoxTextChanged(QString))); connect(d->completionBox, &KCompletionBox::userCancelled, this, &KLineEdit::userCancelled); connect(d->completionBox, SIGNAL(activated(QString)), SIGNAL(completionBoxActivated(QString))); connect(d->completionBox, SIGNAL(activated(QString)), SIGNAL(textEdited(QString))); } } /* * Set the line edit text without changing the modified flag. By default * calling setText resets the modified flag to false. */ static void setEditText(KLineEdit *edit, const QString &text) { if (!edit) { return; } const bool wasModified = edit->isModified(); edit->setText(text); edit->setModified(wasModified); } void KLineEdit::userCancelled(const QString &cancelText) { Q_D(KLineEdit); if (completionMode() != KCompletion::CompletionPopupAuto) { setEditText(this, cancelText); } else if (hasSelectedText()) { if (d->userSelection) { deselect(); } else { d->autoSuggest = false; const int start = selectionStart(); const QString s = text().remove(selectionStart(), selectedText().length()); setEditText(this, s); setCursorPosition(start); d->autoSuggest = true; } } } bool KLineEditPrivate::overrideShortcut(const QKeyEvent *e) { Q_Q(KLineEdit); QList scKey; const int key = e->key() | e->modifiers(); const KLineEdit::KeyBindingMap keys = q->keyBindingMap(); if (keys[KLineEdit::TextCompletion].isEmpty()) { scKey = KStandardShortcut::shortcut(KStandardShortcut::TextCompletion); } else { scKey = keys[KLineEdit::TextCompletion]; } if (scKey.contains(key)) { return true; } if (keys[KLineEdit::NextCompletionMatch].isEmpty()) { scKey = KStandardShortcut::shortcut(KStandardShortcut::NextCompletion); } else { scKey = keys[KLineEdit::NextCompletionMatch]; } if (scKey.contains(key)) { return true; } if (keys[KLineEdit::PrevCompletionMatch].isEmpty()) { scKey = KStandardShortcut::shortcut(KStandardShortcut::PrevCompletion); } else { scKey = keys[KLineEdit::PrevCompletionMatch]; } if (scKey.contains(key)) { return true; } // Override all the text manupilation accelerators... if (KStandardShortcut::copy().contains(key)) { return true; } else if (KStandardShortcut::paste().contains(key)) { return true; } else if (KStandardShortcut::cut().contains(key)) { return true; } else if (KStandardShortcut::undo().contains(key)) { return true; } else if (KStandardShortcut::redo().contains(key)) { return true; } else if (KStandardShortcut::deleteWordBack().contains(key)) { return true; } else if (KStandardShortcut::deleteWordForward().contains(key)) { return true; } else if (KStandardShortcut::forwardWord().contains(key)) { return true; } else if (KStandardShortcut::backwardWord().contains(key)) { return true; } else if (KStandardShortcut::beginningOfLine().contains(key)) { return true; } else if (KStandardShortcut::endOfLine().contains(key)) { return true; } // Shortcut overrides for shortcuts that QLineEdit handles // but doesn't dare force as "stronger than kaction shortcuts"... else if (e->matches(QKeySequence::SelectAll)) { return true; } else if (qApp->platformName() == QLatin1String("xcb") && (key == Qt::CTRL + Qt::Key_E || key == Qt::CTRL + Qt::Key_U)) { return true; } if (completionBox && completionBox->isVisible()) { const int key = e->key(); const Qt::KeyboardModifiers modifiers = e->modifiers(); if ((key == Qt::Key_Backtab || key == Qt::Key_Tab) && (modifiers == Qt::NoModifier || (modifiers & Qt::ShiftModifier))) { return true; } } return false; } void KLineEdit::setCompletedItems(const QStringList &items, bool autoSuggest) { Q_D(KLineEdit); QString txt; if (d->completionBox && d->completionBox->isVisible()) { // The popup is visible already - do the matching on the initial string, // not on the currently selected one. txt = completionBox()->cancelledText(); } else { txt = text(); } if (!items.isEmpty() && !(items.count() == 1 && txt == items.first())) { // create completion box if non-existent completionBox(); if (d->completionBox->isVisible()) { QListWidgetItem *currentItem = d->completionBox->currentItem(); QString currentSelection; if (currentItem != nullptr) { currentSelection = currentItem->text(); } d->completionBox->setItems(items); const QList matchedItems = d->completionBox->findItems(currentSelection, Qt::MatchExactly); QListWidgetItem *matchedItem = matchedItems.isEmpty() ? nullptr : matchedItems.first(); if (matchedItem) { const bool blocked = d->completionBox->blockSignals(true); d->completionBox->setCurrentItem(matchedItem); d->completionBox->blockSignals(blocked); } else { d->completionBox->setCurrentRow(-1); } } else { // completion box not visible yet -> show it if (!txt.isEmpty()) { d->completionBox->setCancelledText(txt); } d->completionBox->setItems(items); d->completionBox->popup(); } if (d->autoSuggest && autoSuggest) { const int index = items.first().indexOf(txt); const QString newText = items.first().mid(index); setUserSelection(false); // can be removed? setCompletedText sets it anyway setCompletedText(newText, true); } } else { if (d->completionBox && d->completionBox->isVisible()) { d->completionBox->hide(); } } } KCompletionBox *KLineEdit::completionBox(bool create) { Q_D(KLineEdit); if (create && !d->completionBox) { setCompletionBox(new KCompletionBox(this)); d->completionBox->setObjectName(QStringLiteral("completion box")); d->completionBox->setFont(font()); } return d->completionBox; } void KLineEdit::setCompletionObject(KCompletion *comp, bool handle) { KCompletion *oldComp = compObj(); if (oldComp && handleSignals()) disconnect(oldComp, SIGNAL(matches(QStringList)), this, SLOT(setCompletedItems(QStringList))); if (comp && handle) connect(comp, SIGNAL(matches(QStringList)), this, SLOT(setCompletedItems(QStringList))); KCompletionBase::setCompletionObject(comp, handle); } void KLineEdit::setUserSelection(bool userSelection) { Q_D(KLineEdit); //if !d->userSelection && userSelection we are accepting a completion, //so trigger an update if (!d->userSelection && userSelection) { d->updateUserText(text()); } QPalette p = palette(); if (userSelection) { p.setColor(QPalette::Highlight, d->previousHighlightColor); p.setColor(QPalette::HighlightedText, d->previousHighlightedTextColor); } else { QColor color = p.color(QPalette::Disabled, QPalette::Text); p.setColor(QPalette::HighlightedText, color); color = p.color(QPalette::Active, QPalette::Base); p.setColor(QPalette::Highlight, color); } d->userSelection = userSelection; setPalette(p); } void KLineEditPrivate::_k_restoreSelectionColors() { Q_Q(KLineEdit); if (disableRestoreSelection) { return; } q->setUserSelection(true); } void KLineEditPrivate::_k_completionBoxTextChanged(const QString &text) { Q_Q(KLineEdit); if (!text.isEmpty()) { q->setText(text); q->setModified(true); q->end(false); // force cursor at end } } QString KLineEdit::originalText() const { Q_D(const KLineEdit); if (d->enableSqueezedText && isReadOnly()) { return d->squeezedText; } return text(); } QString KLineEdit::userText() const { Q_D(const KLineEdit); return d->userText; } bool KLineEdit::autoSuggest() const { Q_D(const KLineEdit); return d->autoSuggest; } void KLineEdit::paintEvent(QPaintEvent *ev) { Q_D(KLineEdit); if (echoMode() == Password && d->threeStars) { // ### hack alert! // QLineEdit has currently no hooks to modify the displayed string. // When we call setText(), an update() is triggered and we get // into an infinite recursion. // Qt offers the setUpdatesEnabled() method, but when we re-enable // them, update() is triggered, and we get into the same recursion. // To work around this problem, we set/clear the internal Qt flag which // marks the updatesDisabled state manually. setAttribute(Qt::WA_UpdatesDisabled, true); blockSignals(true); const QString oldText = text(); const bool isModifiedState = isModified(); // save modified state because setText resets it setText(oldText + oldText + oldText); QLineEdit::paintEvent(ev); setText(oldText); setModified(isModifiedState); blockSignals(false); setAttribute(Qt::WA_UpdatesDisabled, false); } else { QLineEdit::paintEvent(ev); } } -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(5, 0) void KLineEdit::setClickMessage(const QString &msg) { setPlaceholderText(msg); } #endif -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(4, 5) void KLineEdit::setContextMenuEnabled(bool showMenu) { QLineEdit::setContextMenuPolicy(showMenu ? Qt::DefaultContextMenu : Qt::NoContextMenu); } #endif -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(4, 5) bool KLineEdit::isContextMenuEnabled() const { return (contextMenuPolicy() == Qt::DefaultContextMenu); } #endif void KLineEdit::setPasswordMode(bool passwordMode) { Q_D(KLineEdit); if (passwordMode) { KConfigGroup cg(KSharedConfig::openConfig(), "Passwords"); const QString val = cg.readEntry("EchoMode", "OneStar"); if (val == QLatin1String("NoEcho")) { setEchoMode(NoEcho); } else { d->threeStars = (val == QLatin1String("ThreeStars")); setEchoMode(Password); } } else { setEchoMode(Normal); } } bool KLineEdit::passwordMode() const { return echoMode() == NoEcho || echoMode() == Password; } void KLineEdit::doCompletion(const QString &text) { Q_D(KLineEdit); if (emitSignals()) { emit completion(text); // emit when requested... } d->completionRunning = true; if (handleSignals()) { makeCompletion(text); // handle when requested... } d->completionRunning = false; } #include "moc_klineedit.cpp" diff --git a/src/klineedit.h b/src/klineedit.h index 9875e91..0b09d0a 100644 --- a/src/klineedit.h +++ b/src/klineedit.h @@ -1,644 +1,653 @@ /* This file is part of the KDE libraries This class was originally inspired by Torben Weis' fileentry.cpp for KFM II. Copyright (C) 1997 Sven Radej Copyright (c) 1999 Patrick Ward Copyright (c) 1999 Preston Brown Completely re-designed: Copyright (c) 2000,2001 Dawit Alemayehu This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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 KLINEEDIT_H #define KLINEEDIT_H #include #include #include #include class QAction; class QMenu; class KCompletionBox; class QUrl; class KLineEditPrivate; /** * @class KLineEdit klineedit.h KLineEdit * * An enhanced QLineEdit widget for inputting text. * * \b Detail \n * * This widget inherits from QLineEdit and implements the following * additional functionalities: a completion object that provides both * automatic and manual text completion as well as multiple match iteration * features, configurable key-bindings to activate these features and a * popup-menu item that can be used to allow the user to set text completion * modes on the fly based on their preference. * * To support these new features KLineEdit also emits a few more * additional signals. These are: completion( const QString& ), * textRotation( KeyBindingType ), and returnPressed( const QString& ). * The completion signal can be connected to a slot that will assist the * user in filling out the remaining text. The text rotation signal is * intended to be used to iterate through the list of all possible matches * whenever there is more than one match for the entered text. The * @c returnPressed( const QString& ) signals are the same as QLineEdit's * except it provides the current text in the widget as its argument whenever * appropriate. * * This widget by default creates a completion object when you invoke * the completionObject( bool ) member function for the first time or * use setCompletionObject( KCompletion*, bool ) to assign your own * completion object. Additionally, to make this widget more functional, * KLineEdit will by default handle the text rotation and completion * events internally when a completion object is created through either one * of the methods mentioned above. If you do not need this functionality, * simply use KCompletionBase::setHandleSignals( bool ) or set the * boolean parameter in the above functions to false. * * The default key-bindings for completion and rotation is determined * from the global settings in KStandardShortcut. These values, however, * can be overridden locally by invoking KCompletionBase::setKeyBinding(). * The values can easily be reverted back to the default setting, by simply * calling useGlobalSettings(). An alternate method would be to default * individual key-bindings by using setKeyBinding() with the default * second argument. * * If @c EchoMode for this widget is set to something other than @c QLineEdit::Normal, * the completion mode will always be defaulted to CompletionNone. * This is done purposefully to guard against protected entries such as passwords being * cached in KCompletion's list. Hence, if the @c EchoMode is not QLineEdit::Normal, the * completion mode is automatically disabled. * * A read-only KLineEdit will have the same background color as a * disabled KLineEdit, but its foreground color will be the one used * for the read-write mode. This differs from QLineEdit's implementation * and is done to give visual distinction between the three different modes: * disabled, read-only, and read-write. * * KLineEdit has also a password mode which depends of globals KDE settings. Use * KLineEdit::setPasswordMode instead of QLineEdit::echoMode property to have a password field. * * \b Usage \n * * To enable the basic completion feature: * * \code * KLineEdit *edit = new KLineEdit( this ); * KCompletion *comp = edit->completionObject(); * // Connect to the return pressed signal - optional * connect(edit,SIGNAL(returnPressed(const QString&)),comp,SLOT(addItem(const QString&))); * \endcode * * To use a customized completion objects or your * own completion object: * * \code * KLineEdit *edit = new KLineEdit( this ); * KUrlCompletion *comp = new KUrlCompletion(); * edit->setCompletionObject( comp ); * // Connect to the return pressed signal - optional * connect(edit,SIGNAL(returnPressed(const QString&)),comp,SLOT(addItem(const QString&))); * \endcode * * Note if you specify your own completion object you have to either delete * it when you don't need it anymore, or you can tell KLineEdit to delete it * for you: * \code * edit->setAutoDeleteCompletionObject( true ); * \endcode * * Miscellaneous function calls :\n * * \code * // Tell the widget to not handle completion and iteration automatically. * edit->setHandleSignals( false ); * * // Set your own key-bindings for a text completion mode. * edit->setKeyBinding( KCompletionBase::TextCompletion, Qt::End ); * * // Hide the context (popup) menu * edit->setContextMenuPolicy( Qt::NoContextMenu ); * * // Default the key-bindings back to the default system settings. * edit->useGlobalKeyBindings(); * \endcode * * \image html klineedit.png "KLineEdit widgets with clear-button" * * @author Dawit Alemayehu */ class KCOMPLETION_EXPORT KLineEdit : public QLineEdit, public KCompletionBase //krazy:exclude=qclasses { friend class KComboBox; friend class KLineEditStyle; Q_OBJECT Q_DECLARE_PRIVATE(KLineEdit) -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(4, 5) Q_PROPERTY(bool contextMenuEnabled READ isContextMenuEnabled WRITE setContextMenuEnabled) #endif -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(5, 0) Q_PROPERTY(bool urlDropsEnabled READ urlDropsEnabled WRITE setUrlDropsEnabled) #endif Q_PROPERTY(bool trapEnterKeyEvent READ trapReturnKey WRITE setTrapReturnKey) Q_PROPERTY(bool squeezedTextEnabled READ isSqueezedTextEnabled WRITE setSqueezedTextEnabled) -#ifndef KCOMPLETION_NO_DEPRECATED +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(5, 0) Q_PROPERTY(QString clickMessage READ clickMessage WRITE setClickMessage) #endif +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(5, 46) Q_PROPERTY(bool showClearButton READ isClearButtonShown WRITE setClearButtonShown) +#endif Q_PROPERTY(bool passwordMode READ passwordMode WRITE setPasswordMode) public: /** * Constructs a KLineEdit object with a default text, a parent, * and a name. * * @param string Text to be shown in the edit widget. * @param parent The parent widget of the line edit. */ explicit KLineEdit(const QString &string, QWidget *parent = nullptr); /** * Constructs a line edit * @param parent The parent widget of the line edit. */ explicit KLineEdit(QWidget *parent = nullptr); /** * Destructor. */ ~KLineEdit() override; /** * Sets @p url into the lineedit. It uses QUrl::toDisplayString() so * that the url is properly decoded for displaying. */ void setUrl(const QUrl &url); /** * Reimplemented from KCompletionBase for internal reasons. * * This function is re-implemented in order to make sure that * the EchoMode is acceptable before we set the completion mode. * * See KCompletionBase::setCompletionMode */ void setCompletionMode(KCompletion::CompletionMode mode) override; /** * Disables completion modes by makeing them non-checkable. * * The context menu allows to change the completion mode. * This method allows to disable some modes. */ void setCompletionModeDisabled(KCompletion::CompletionMode mode, bool disable = true); +#if KCOMPLETION_BUILD_DEPRECATED_SINCE(4, 5) /** * Enables/disables the popup (context) menu. * * This method only works if this widget is editable, i.e. read-write and * allows you to enable/disable the context menu. It does nothing if invoked * for a none-editable combo-box. * * By default, the context menu is created if this widget is editable. * Call this function with the argument set to false to disable the popup * menu. * * @param showMenu If @c true, show the context menu. * @deprecated since 4.5, use setContextMenuPolicy instead */ -#ifndef KCOMPLETION_NO_DEPRECATED - virtual KCOMPLETION_DEPRECATED void setContextMenuEnabled(bool showMenu); + KCOMPLETION_DEPRECATED_VERSION(4, 5, "Use QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy)") + virtual void setContextMenuEnabled(bool showMenu); #endif +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) /** * Returns @c true when the context menu is enabled. * @deprecated since 4.5, use contextMenuPolicy instead */ -#ifndef KCOMPLETION_NO_DEPRECATED - KCOMPLETION_DEPRECATED bool isContextMenuEnabled() const; + KCOMPLETION_DEPRECATED_VERSION(4, 5, "Use QWidget::contextMenuPolicy()") + bool isContextMenuEnabled() const; #endif /** * Enables/Disables handling of URL drops. If enabled and the user * drops an URL, the decoded URL will be inserted. Otherwise the default * behavior of QLineEdit is used, which inserts the encoded URL. * Call setUrlDropsEnabled(false) if you need dropEvent to be called in a KLineEdit subclass. * * @param enable If @c true, insert decoded URLs */ void setUrlDropsEnabled(bool enable); // KF6: remove it and don't create LineEditUrlDropEventFilter by default. /** * Returns @c true when decoded URL drops are enabled */ bool urlDropsEnabled() const; /** * By default, KLineEdit recognizes @c Key_Return and @c Key_Enter and emits * the returnPressed() signals, but it also lets the event pass, * for example causing a dialog's default-button to be called. * * Call this method with @p trap = @c true to make @c KLineEdit stop these * events. The signals will still be emitted of course. * * @see trapReturnKey() */ void setTrapReturnKey(bool trap); /** * @returns @c true if keyevents of @c Key_Return or * @c Key_Enter will be stopped or if they will be propagated. * * @see setTrapReturnKey () */ bool trapReturnKey() const; /** * @returns the completion-box, that is used in completion mode * CompletionPopup. * This method will create a completion-box if none is there, yet. * * @param create Set this to false if you don't want the box to be created * i.e. to test if it is available. */ virtual KCompletionBox *completionBox(bool create = true); /** * Reimplemented for internal reasons, the API is not affected. */ void setCompletionObject(KCompletion *, bool handle = true) override; /** * Reimplemented for internal reasons, the API is not affected. */ virtual void copy() const; /** * Enable text squeezing whenever the supplied text is too long. * Only works for "read-only" mode. * * Note that once text squeezing is enabled, QLineEdit::text() * and QLineEdit::displayText() return the squeezed text. If * you want the original text, use @ref originalText. * * @see QLineEdit */ void setSqueezedTextEnabled(bool enable); /** * Returns true if text squeezing is enabled. * This is only valid when the widget is in read-only mode. */ bool isSqueezedTextEnabled() const; /** * Returns the original text if text squeezing is enabled. * If the widget is not in "read-only" mode, this function * returns the same thing as QLineEdit::text(). * * @see QLineEdit */ QString originalText() const; /** * Returns the text as given by the user (i.e. not autocompleted) * if the widget has autocompletion disabled, this function * returns the same as QLineEdit::text(). * @since 4.2.2 */ QString userText() const; /** * Set the completion-box to be used in completion mode * CompletionPopup. * This will do nothing if a completion-box already exists. * * @param box The KCompletionBox to set */ void setCompletionBox(KCompletionBox *box); +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(5, 0) /** * This makes the line edit display a grayed-out hinting text as long as * the user didn't enter any text. It is often used as indication about * the purpose of the line edit. * @deprecated since 5.0, use QLineEdit::setPlaceholderText instead. */ -#ifndef KCOMPLETION_NO_DEPRECATED - KCOMPLETION_DEPRECATED void setClickMessage(const QString &msg); + KCOMPLETION_DEPRECATED_VERSION(5, 0, "Use QLineEdit::setPlaceholderText(const QString&)") + void setClickMessage(const QString &msg); #endif +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(5, 0) /** * @return the message set with setClickMessage * @deprecated since 5.0, use QLineEdit::placeholderText instead. */ -#ifndef KCOMPLETION_NO_DEPRECATED - KCOMPLETION_DEPRECATED QString clickMessage() const; + KCOMPLETION_DEPRECATED_VERSION(5, 0, "Use QLineEdit::placeholderText()") + QString clickMessage() const; #endif +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(5, 46) /** * This makes the line edit display an icon on one side of the line edit * which, when clicked, clears the contents of the line edit. * This is useful for such things as location or search bars. * * @deprecated since 5.46 Use QLineEdit::setClearButtonEnabled **/ -#ifndef KCOMPLETION_NO_DEPRECATED - KCOMPLETION_DEPRECATED void setClearButtonShown(bool show); + KCOMPLETION_DEPRECATED_VERSION(5, 46, "Use QLineEdit::setClearButtonEnabled(bool)") + void setClearButtonShown(bool show); #endif +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(5, 46) /** * @return whether or not the clear button is shown * * @deprecated since 5.46 Use QLineEdit::isClearButtonEnabled **/ -#ifndef KCOMPLETION_NO_DEPRECATED - KCOMPLETION_DEPRECATED bool isClearButtonShown() const; + KCOMPLETION_DEPRECATED_VERSION(5, 46, "Use QLineEdit::isClearButtonEnabled()") + bool isClearButtonShown() const; #endif /** * @return the size used by the clear button * @since 4.1 **/ QSize clearButtonUsedSize() const; /** * Do completion now. This is called automatically when typing a key for instance. * Emits completion() and/or calls makeCompletion(), depending on * emitSignals and handleSignals. * * @since 4.2.1 */ void doCompletion(const QString &text); Q_SIGNALS: /** * Emitted whenever the completion box is activated. */ void completionBoxActivated(const QString &); /** * Emitted when the user presses the return key. * * The argument is the current text. Note that this * signal is @em not emitted if the widget's @c EchoMode is set to * QLineEdit::EchoMode. */ void returnPressed(const QString &); /** * Emitted when the completion key is pressed. * * Please note that this signal is @em not emitted if the * completion mode is set to @c CompletionNone or @c EchoMode is * @em normal. */ void completion(const QString &); /** * Emitted when the shortcut for substring completion is pressed. */ void substringCompletion(const QString &); +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 5) /** * Emitted when the text is changed NOT by the suggested autocompletion: * either when the user is physically typing keys, or when the text is changed programmatically, * for example, by calling setText(). * But not when automatic completion changes the text temporarily. * * @since 4.2.2 * @deprecated since 4.5. You probably want to connect to textEdited() instead, * which is emitted whenever the text is actually changed by the user * (by typing or accepting autocompletion), without side effects from * suggested autocompletion either. userTextChanged isn't needed anymore. */ -#ifndef KCOMPLETION_NO_DEPRECATED + KCOMPLETION_DEPRECATED_VERSION(4, 5, "Use QLineEdit::textEdited(const QString&)") QT_MOC_COMPAT void userTextChanged(const QString &); #endif /** * Emitted when the text rotation key-bindings are pressed. * * The argument indicates which key-binding was pressed. * In KLineEdit's case this can be either one of two values: * PrevCompletionMatch or NextCompletionMatch. See * KCompletionBase::setKeyBinding for details. * * Note that this signal is @em not emitted if the completion * mode is set to @c CompletionNone or @c echoMode() is @em not normal. */ void textRotation(KCompletionBase::KeyBindingType); /** * Emitted when the user changed the completion mode by using the * popupmenu. */ void completionModeChanged(KCompletion::CompletionMode); /** * Emitted before the context menu is displayed. * * The signal allows you to add your own entries into the * the context menu that is created on demand. * * NOTE: Do not store the pointer to the QMenu * provided through since it is created and deleted * on demand. * * @param contextMenu the context menu about to be displayed */ void aboutToShowContextMenu(QMenu *contextMenu); /** * Emitted when the user clicked on the clear button */ void clearButtonClicked(); public Q_SLOTS: /** * Sets the lineedit to read-only. Similar to QLineEdit::setReadOnly * but also takes care of the background color, and the clear button. */ virtual void setReadOnly(bool); /** * Iterates through all possible matches of the completed text or * the history list. * * This function simply iterates over all possible matches in case * multiple matches are found as a result of a text completion request. * It will have no effect if only a single match is found. * * @param type The key-binding invoked. */ void rotateText(KCompletionBase::KeyBindingType type); /** * See KCompletionBase::setCompletedText. */ void setCompletedText(const QString &) override; /** * Same as the above function except it allows you to temporarily * turn off text completion in CompletionPopupAuto mode. * * * @param items list of completion matches to be shown in the completion box. * @param autoSuggest true if you want automatic text completion (suggestion) enabled. */ void setCompletedItems(const QStringList &items, bool autoSuggest = true) override; /** * Squeezes @p text into the line edit. * This can only be used with read-only line-edits. */ void setSqueezedText(const QString &text); /** * Reimplemented to enable text squeezing. API is not affected. */ virtual void setText(const QString &); /** * @brief set the line edit in password mode. * this change the EchoMode according to KDE preferences. * @param passwordMode true to set in password mode */ void setPasswordMode(bool passwordMode = true); /** * @return returns true if the lineedit is set to password mode echoing */ bool passwordMode() const; protected Q_SLOTS: /** * Completes the remaining text with a matching one from * a given list. */ virtual void makeCompletion(const QString &); /** * Resets the current displayed text. * Call this function to revert a text completion if the user * cancels the request. Mostly applies to popup completions. */ void userCancelled(const QString &cancelText); protected: /** * Reimplemented for internal reasons. API not affected. */ bool event(QEvent *) override; /** * Reimplemented for internal reasons. API not affected. * * See QLineEdit::resizeEvent(). */ void resizeEvent(QResizeEvent *) override; /** * Reimplemented for internal reasons. API not affected. * * See QLineEdit::keyPressEvent(). */ void keyPressEvent(QKeyEvent *) override; /** * Reimplemented for internal reasons. API not affected. * * See QLineEdit::mousePressEvent(). */ void mousePressEvent(QMouseEvent *) override; /** * Reimplemented for internal reasons. API not affected. * * See QLineEdit::mouseReleaseEvent(). */ void mouseReleaseEvent(QMouseEvent *) override; /** * Reimplemented for internal reasons. API not affected. * * See QWidget::mouseDoubleClickEvent(). */ void mouseDoubleClickEvent(QMouseEvent *) override; /** * Reimplemented for internal reasons. API not affected. * * See QLineEdit::contextMenuEvent(). */ void contextMenuEvent(QContextMenuEvent *) override; /** * Reimplemented for internal reasons. API not affected. * * See QLineEdit::createStandardContextMenu(). */ QMenu *createStandardContextMenu(); /** * This function simply sets the lineedit text and * highlights the text appropriately if the boolean * value is set to true. * * @param text * @param marked */ virtual void setCompletedText(const QString & /*text*/, bool /*marked*/); /** * Sets the widget in userSelection mode or in automatic completion * selection mode. This changes the colors of selections. */ void setUserSelection(bool userSelection); /** * Whether in current state text should be auto-suggested */ bool autoSuggest() const; void paintEvent(QPaintEvent *ev) override; private: const QScopedPointer d_ptr; Q_PRIVATE_SLOT(d_func(), void _k_textChanged(const QString &)) Q_PRIVATE_SLOT(d_func(), void _k_completionMenuActivated(QAction *)) Q_PRIVATE_SLOT(d_func(), void _k_tripleClickTimeout()) Q_PRIVATE_SLOT(d_func(), void _k_restoreSelectionColors()) Q_PRIVATE_SLOT(d_func(), void _k_completionBoxTextChanged(const QString &)) }; #endif diff --git a/src/ksortablelist.h b/src/ksortablelist.h index c1c2ead..96fb5cd 100644 --- a/src/ksortablelist.h +++ b/src/ksortablelist.h @@ -1,213 +1,214 @@ /* This file is part of the KDE libraries Copyright (C) 2001 Carsten Pfeiffer 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 KSORTABLELIST_H #define KSORTABLELIST_H #include #include #include #include /** * \class KSortableItem ksortablelist.h * * KSortableItem is a QPair that provides several operators * for sorting. * @see KSortableList */ template class KSortableItem : public QPair { public: /** * Creates a new KSortableItem with the given values. * @param i the first value (the key) * @param t the second value (the item) */ KSortableItem(Key i, const T &t) : QPair(i, t) {} /** * Creates a new KSortableItem that copies another one. * @param rhs the other item to copy */ KSortableItem(const KSortableItem &rhs) : QPair(rhs.first, rhs.second) {} /** * Creates a new KSortableItem with uninitialized values. */ KSortableItem() {} /** * Assignment operator, just copies the item. */ KSortableItem &operator=(const KSortableItem &i) { this->first = i.first; this->second = i.second; return *this; } // operators for sorting /** * Compares the two items. This implementation only compares * the first value. */ bool operator> (const KSortableItem &i2) const { return (i2.first < this->first); } /** * Compares the two items. This implementation only compares * the first value. */ bool operator< (const KSortableItem &i2) const { return (this->first < i2.first); } /** * Compares the two items. This implementation only compares * the first value. */ bool operator>= (const KSortableItem &i2) const { return (this->first >= i2.first); } /** * Compares the two items. This implementation only compares * the first value. */ bool operator<= (const KSortableItem &i2) const { return !(i2.first < this->first); } /** * Compares the two items. This implementation only compares * the first value. */ bool operator== (const KSortableItem &i2) const { return (this->first == i2.first); } /** * Compares the two items. This implementation only compares * the first value. */ bool operator!= (const KSortableItem &i2) const { return (this->first != i2.first); } /** * @return the second value (the item) */ T &value() { return this->second; } /** * @return the second value (the item) */ const T &value() const { return this->second; } +#if KCOMPLETION_ENABLE_DEPRECATED_SINCE(4, 0) /** * @return the first value (the key) - * @deprecated use key() + * @deprecated Since 4.0. Use key() */ -#ifndef KCOMPLETION_NO_DEPRECATED - KCOMPLETION_DEPRECATED Key index() const + KCOMPLETION_DEPRECATED_VERSION(4, 0, "Use KSortableItem::key()") + Key index() const { return this->first; } #endif /** * @return the first value. */ Key key() const { return this->first; } }; /** * \class KSortableList ksortablelist.h * * KSortableList is a QList which associates a key with each item in the list. * This key is used for sorting when calling sort(). * * This allows to temporarily calculate a key and use it for sorting, without having * to store that key in the items, or calculate that key many times for the same item * during sorting if that calculation is expensive. */ template class KSortableList : public QList > { public: /** * Insert a KSortableItem with the given values. * @param i the first value * @param t the second value */ void insert(Key i, const T &t) { QList >::append(KSortableItem(i, t)); } // add more as you please... /** * Returns the first value of the KSortableItem at the given position. * @return the first value of the KSortableItem */ T &operator[](Key i) { return QList >::operator[](i).value(); } /** * Returns the first value of the KSortableItem at the given position. * @return the first value of the KSortableItem */ const T &operator[](Key i) const { return QList >::operator[](i).value(); } /** * Sorts the KSortableItems. */ void sort() { std::sort(this->begin(), this->end()); } }; #ifdef Q_CC_MSVC template inline uint qHash(const KSortableItem &) { Q_ASSERT(0); return 0; } #endif #endif // KSORTABLELIST_H