diff --git a/.gitignore b/.gitignore index d1f638d..dff8c35 100644 --- a/.gitignore +++ b/.gitignore @@ -28,4 +28,5 @@ compile_commands.json .cache Testing/ /.vscode/ +/flatpak/flatpak-builder-tools/ .qtcreator/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 0157082..62067d7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -39,10 +39,14 @@ find_package(Qt6 ${QT_MIN_VERSION} REQUIRED COMPONENTS Core Gui Qml - VirtualKeyboard + Quick WaylandClient ) +if(PLASMA_KEYBOARD_SOUNDS_ENABLED) + find_package(Qt6Multimedia ${QT_MIN_VERSION} REQUIRED) +endif() + find_package(Qt6GuiPrivate ${QT_MIN_VERSION} REQUIRED NO_MODULE) find_package(Qt6WaylandClientPrivate ${QT_MIN_VERSION} REQUIRED NO_MODULE) @@ -50,6 +54,7 @@ find_package(KF6 ${KF6_MIN_VERSION} REQUIRED COMPONENTS CoreAddons I18n KCMUtils + Package Config Crash ) @@ -68,7 +73,10 @@ pkg_check_modules(XKBCommon REQUIRED IMPORTED_TARGET xkbcommon) find_package(Wayland 1.2 REQUIRED COMPONENTS Client) find_package(QtWaylandScanner REQUIRED ${QT_MIN_VERSION}) find_package(WaylandProtocols 1.19 REQUIRED) +find_package(PlasmaWaylandProtocols REQUIRED) +add_subdirectory(virtualkeyboard) +add_subdirectory(layouts) add_subdirectory(kcm) add_subdirectory(src) if(BUILD_TESTING) diff --git a/README.md b/README.md index 3379664..da456f0 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ # Plasma Keyboard -The plasma-keyboard is a virtual keyboard based on [Qt Virtual Keyboard](https://doc.qt.io/qt-6/qtvirtualkeyboard-overview.html) designed to integrate in Plasma. +The plasma-keyboard is a virtual keyboard and input engine designed to integrate in Plasma. -It wraps Qt Virtual Keyboard in a window, and uses the input-method-v1 Wayland protocol to communicate with the compositor to function as an input method. +It uses the input-method-v1 Wayland protocol to communicate with the compositor to function as an input method. It also can leverage KWin's fake-input protocol in order to emulate keyboard keys (ex. Meta, Ctrl). ## Install using the flatpak nightly repository @@ -92,13 +92,20 @@ get started with development! We have a room specifically for input handling: ## Layouts -The keyboard layouts are located in the [src/layouts](/src/layouts) folder. +The keyboard layouts are located in the [layouts](/layouts) folder. -They are forked from Qt's [layouts](https://github.com/qt/qtvirtualkeyboard/tree/dev/src/layouts), with modifications that we want for Plasma. Please view the official [Qt documentation](https://doc.qt.io/qt-6/qtvirtualkeyboard-overview.html#adding-new-keyboard-layouts) for a guide on how to create and modify keyboard layouts. +See the existing layouts there for examples on creating layout packages. They are installed (roughly) to `/usr/share/plasma/keyboard/keyboardpackages`. -To use Qt's built-in keyboard layouts rather than the ones we supply in `plasma-keyboard`, set `PLASMA_KEYBOARD_USE_QT_LAYOUTS=1` when starting KWin (or the login session). +See the component library for making layouts for documentation at [virtualkeyboard/components](/virtualkeyboard/components). + +### Text composers + +A default text composer is provided that emits keys directly to the input engine (see [directtextcomposer](virtualkeyboard/textcomposers/directtextcomposer.h)) which works for most languages. + +Some languages require some extra processing in preedit to form words, and so have their own text composers: + +Text composers are located in [virtualkeyboard/textcomposers](/virtualkeyboard/textcomposers). ## Troubleshooting KWin by default only shows the keyboard when a text field is interacted with by touch. Set `KWIN_IM_SHOW_ALWAYS=1` when starting KWin (or the login session) in order to force the keyboard to always pop up. - diff --git a/autotests/CMakeLists.txt b/autotests/CMakeLists.txt index e660766..62b4787 100644 --- a/autotests/CMakeLists.txt +++ b/autotests/CMakeLists.txt @@ -4,6 +4,15 @@ find_package(Qt6 ${QT_MIN_VERSION} REQUIRED COMPONENTS Test WaylandCompositor) include(ECMAddTests) +ecm_add_test(inputenginetest.cpp + TEST_NAME inputenginetest + LINK_LIBRARIES + plasma-keyboard-virtualkeyboard + Qt::Gui + Qt::Qml + Qt::Test +) + file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/mockinputmethodcompositor_config.h CONTENT "#pragma once\n#define PLASMA_KEYBOARD_BINARY_PATH \"$\"\n" diff --git a/autotests/inputenginetest.cpp b/autotests/inputenginetest.cpp new file mode 100644 index 0000000..9eb680d --- /dev/null +++ b/autotests/inputenginetest.cpp @@ -0,0 +1,424 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "inputengine.h" +#include "basictextcomposer.h" +#include "directtextcomposer.h" +#include "inputbackend.h" + +#include +#include +#include + +Q_LOGGING_CATEGORY(PlasmaKeyboard, "org.kde.plasma.keyboard") + +class TestInputBackend : public InputBackend +{ +public: + bool isActive() const override + { + return m_active; + } + + Qt::InputMethodHints inputMethodHints() const override + { + return m_inputMethodHints; + } + + QString surroundingText() const override + { + return m_surroundingText; + } + + uint32_t cursorPositionUtf8() const override + { + return m_cursorPositionUtf8; + } + + uint32_t anchorPositionUtf8() const override + { + return m_anchorPositionUtf8; + } + + void setPreeditText(const QString &text) override + { + preeditRequests.append(text); + events.append(QStringLiteral("preedit:%1").arg(text)); + } + + void commitText(const QString &text) override + { + commitRequests.append(text); + events.append(QStringLiteral("commit:%1").arg(text)); + } + + void deleteSurroundingText(int index, int length) override + { + deleteRequests.append({index, length}); + events.append(QStringLiteral("delete:%1:%2").arg(index).arg(length)); + } + + bool sendKeyClick(int key) override + { + keyClickRequests.append(key); + events.append(QStringLiteral("click:%1").arg(key)); + return keyClickHandled; + } + + bool sendKeyPressed(int key, bool pressed) override + { + keyPressedRequests.append({key, pressed}); + events.append(QStringLiteral("key:%1:%2").arg(key).arg(pressed)); + if (keyPressedHandled) { + setKeyPressed(key, pressed); + } + return keyPressedHandled; + } + + void setActiveState(bool active) + { + if (m_active == active) { + return; + } + m_active = active; + Q_EMIT activeChanged(); + } + + void setInputMethodHintsState(Qt::InputMethodHints hints) + { + if (m_inputMethodHints == hints) { + return; + } + m_inputMethodHints = hints; + Q_EMIT inputMethodHintsChanged(); + } + + void setSurroundingState(const QString &text, uint32_t cursorPositionUtf8, uint32_t anchorPositionUtf8) + { + if (m_surroundingText == text && m_cursorPositionUtf8 == cursorPositionUtf8 && m_anchorPositionUtf8 == anchorPositionUtf8) { + return; + } + m_surroundingText = text; + m_cursorPositionUtf8 = cursorPositionUtf8; + m_anchorPositionUtf8 = anchorPositionUtf8; + Q_EMIT surroundingTextChanged(); + } + + void setSurroundingState(const QString &text, uint32_t cursorPositionUtf8) + { + setSurroundingState(text, cursorPositionUtf8, cursorPositionUtf8); + } + + QStringList preeditRequests; + QStringList commitRequests; + QList> deleteRequests; + QList keyClickRequests; + QList> keyPressedRequests; + QStringList events; + bool keyClickHandled = true; + bool keyPressedHandled = true; + +private: + bool m_active = false; + // Keep automatic capitalization disabled unless a test opts in + Qt::InputMethodHints m_inputMethodHints = Qt::ImhNoAutoUppercase; + QString m_surroundingText; + uint32_t m_cursorPositionUtf8 = 0; + uint32_t m_anchorPositionUtf8 = 0; +}; + +class CandidateTextComposer : public DirectTextComposer +{ +public: + bool selectCandidate(int index) override + { + selectedCandidate = index; + return true; + } + + int selectedCandidate = -1; +}; + +class InputEngineTest : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + // Basic input + + void commitsExistingPreedit() + { + auto *backend = new TestInputBackend; + InputEngine engine(backend); + engine.setPreeditText(QStringLiteral("composed")); + backend->events.clear(); + + // An empty commit request accepts the current preedit + engine.commit(); + + QCOMPARE(backend->events, QStringList({QStringLiteral("commit:composed"), QStringLiteral("preedit:")})); + QVERIFY(engine.preeditText().isEmpty()); + } + + void routesEditingKeysAsClicks() + { + auto *backend = new TestInputBackend; + InputEngine engine(backend); + engine.setTextComposer(new DirectTextComposer); + + const QList keys = { + Qt::Key_Backspace, + Qt::Key_Delete, + Qt::Key_Left, + Qt::Key_Right, + Qt::Key_Up, + Qt::Key_Down, + Qt::Key_Home, + Qt::Key_End, + Qt::Key_Return, + Qt::Key_Enter, + Qt::Key_Tab, + Qt::Key_Space, + }; + + // Editing keys are forwarded as backend clicks instead of text + for (Qt::Key key : keys) { + QVERIFY(engine.sendTextComposerKey(key, QString())); + } + + QCOMPARE(backend->keyClickRequests, QList(keys.cbegin(), keys.cend())); + QVERIFY(backend->commitRequests.isEmpty()); + } + + void routesComposerKeysDirectlyWithPressedModifier() + { + auto *backend = new TestInputBackend; + InputEngine engine(backend); + engine.setTextComposer(new DirectTextComposer); + + // A held modifier routes composer keys directly to the backend + QVERIFY(engine.sendDirectKey(Qt::Key_Control, true)); + QVERIFY(engine.sendTextComposerKey(Qt::Key_Q, QStringLiteral("q"))); + + QCOMPARE(backend->keyClickRequests, QList{Qt::Key_Q}); + QVERIFY(backend->commitRequests.isEmpty()); + QCOMPARE(engine.pressedKeys(), QList{Qt::Key_Control}); + } + + // Surrounding text + + void convertsUtf8PositionsAndSelections() + { + auto *backend = new TestInputBackend; + InputEngine engine(backend); + QString text = QStringLiteral("a😀éz"); + + // UTF-8 byte offsets are converted to UTF-16 string positions + backend->setSurroundingState(text, 5, 7); + QCOMPARE(engine.cursorPosition(), 3); + QCOMPARE(engine.anchorPosition(), 4); + QCOMPARE(engine.selectedText(), QStringLiteral("é")); + + // Reverse selections preserve the selected text range + backend->setSurroundingState(text, 7, 1); + QCOMPARE(engine.cursorPosition(), 4); + QCOMPARE(engine.anchorPosition(), 1); + QCOMPARE(engine.selectedText(), QStringLiteral("😀é")); + } + + // Composition + + void commitsReplacementAndClearsComposition() + { + auto *backend = new TestInputBackend; + InputEngine engine(backend); + engine.setTextComposer(new DirectTextComposer); + engine.setPreeditPrefix(QStringLiteral("prefix")); + engine.setPreeditText(QStringLiteral("preedit")); + engine.setCandidates({QStringLiteral("one"), QStringLiteral("two")}); + backend->events.clear(); + + // Replacement deletes before committing and then clears composition + engine.commit(QStringLiteral("replacement"), -2, 2); + + QCOMPARE(backend->events, QStringList({QStringLiteral("delete:-2:2"), QStringLiteral("commit:replacement"), QStringLiteral("preedit:")})); + QVERIFY(engine.preeditPrefix().isEmpty()); + QVERIFY(engine.preeditText().isEmpty()); + QVERIFY(engine.candidates().isEmpty()); + QVERIFY(!engine.wordCandidateListVisibleHint()); + } + + void candidateModelTracksAndSelectsCandidates() + { + auto *backend = new TestInputBackend; + InputEngine engine(backend); + auto *composer = new CandidateTextComposer; + engine.setTextComposer(composer); + WordCandidateListModel *model = engine.wordCandidateListModel(); + QSignalSpy countSpy(model, &WordCandidateListModel::countChanged); + + engine.setCandidates({QStringLiteral("first"), QStringLiteral("second")}); + + // Candidate updates are exposed through the list model + QCOMPARE(model->count(), 2); + QCOMPARE(model->rowCount(), 2); + QCOMPARE(model->data(model->index(0), WordCandidateListModel::DisplayRole).toString(), QStringLiteral("first")); + QCOMPARE(model->data(model->index(1), Qt::DisplayRole).toString(), QStringLiteral("second")); + QCOMPARE(countSpy.count(), 1); + QVERIFY(engine.wordCandidateListVisibleHint()); + + // Valid selections reach the composer and invalid ones are ignored + model->selectItem(1); + QCOMPARE(composer->selectedCandidate, 1); + model->selectItem(2); + QCOMPARE(composer->selectedCandidate, 1); + + // Clearing candidates updates model count and visibility + engine.clear(); + QCOMPARE(model->count(), 0); + QCOMPARE(countSpy.count(), 2); + QVERIFY(!engine.wordCandidateListVisibleHint()); + } + + // Engine state + + void resetClearsTransientState() + { + auto *backend = new TestInputBackend; + InputEngine engine(backend); + engine.setTextComposer(new DirectTextComposer); + backend->setActiveState(true); + engine.setCapsLockActive(true); + engine.setPreeditText(QStringLiteral("preedit")); + engine.setCandidates({QStringLiteral("candidate")}); + QVERIFY(engine.sendDirectKey(Qt::Key_Control, true)); + + // Backend reset clears transient state and releases held keys + backend->reset(); + + QVERIFY(!engine.capsLockActive()); + QVERIFY(!engine.shiftActive()); + QVERIFY(engine.preeditText().isEmpty()); + QVERIFY(engine.candidates().isEmpty()); + QVERIFY(engine.pressedKeys().isEmpty()); + QCOMPARE(backend->keyPressedRequests.last(), qMakePair(int(Qt::Key_Control), false)); + } + + // Casing and automatic capitalization + + void commitsComposerText() + { + auto *backend = new TestInputBackend; + // Enable automatic capitalization to test one-shot shift + backend->setInputMethodHintsState(Qt::ImhNone); + InputEngine engine(backend); + engine.setTextComposer(new BasicTextComposer); + backend->setActiveState(true); + + // One-shot shift is consumed after committing text + QVERIFY(engine.sendTextComposerKey(Qt::Key_Q, QStringLiteral("q"))); + QCOMPARE(backend->commitRequests, QStringList{QStringLiteral("Q")}); + QVERIFY(!engine.shiftActive()); + + // Caps lock remains active after committing text + engine.setCapsLockActive(true); + QVERIFY(engine.sendTextComposerKey(Qt::Key_W, QStringLiteral("w"))); + QCOMPARE(backend->commitRequests, QStringList({QStringLiteral("Q"), QStringLiteral("W")})); + QVERIFY(engine.capsLockActive()); + } + + void appliesLocaleAwareCasing() + { + auto *backend = new TestInputBackend; + // Enable automatic capitalization to exercise locale-aware uppercasing + backend->setInputMethodHintsState(Qt::ImhNone); + InputEngine engine(backend); + engine.setLocale(QStringLiteral("tr_TR")); + engine.setTextComposer(new BasicTextComposer); + backend->setActiveState(true); + + // Turkish dotted i follows locale-aware uppercasing + QVERIFY(engine.sendTextComposerKey(Qt::Key_I, QStringLiteral("i"))); + QCOMPARE(backend->commitRequests, QStringList{QStringLiteral("İ")}); + } + + void automaticShiftFollowsContext_data() + { + QTest::addColumn("text"); + QTest::addColumn("cursorPositionUtf8"); + QTest::addColumn("expected"); + + QTest::newRow("empty-input") << QString() << 0u << true; + QTest::newRow("middle-of-sentence") << QStringLiteral("Hello") << 5u << false; + QTest::newRow("punctuation-without-space") << QStringLiteral("Hello.") << 6u << false; + QTest::newRow("sentence-boundary") << QStringLiteral("Hello. ") << 7u << true; + QTest::newRow("text-after-cursor") << QStringLiteral("First. second") << 7u << true; + QTest::newRow("middle-after-boundary") << QStringLiteral("First. second") << 9u << false; + QTest::newRow("utf-8-boundary") << QStringLiteral("é. ") << 4u << true; + } + + void automaticShiftFollowsContext() + { + QFETCH(QString, text); + QFETCH(uint32_t, cursorPositionUtf8); + QFETCH(bool, expected); + + auto *backend = new TestInputBackend; + // Enable automatic capitalization for these context checks + backend->setInputMethodHintsState(Qt::ImhNone); + backend->setSurroundingState(text, cursorPositionUtf8); + InputEngine engine(backend); + engine.setTextComposer(new BasicTextComposer); + backend->setActiveState(true); + + QCOMPARE(engine.shiftActive(), expected); + } + + void automaticShiftFollowsEngineState() + { + auto *backend = new TestInputBackend; + // Enable automatic capitalization for this state transition test + backend->setInputMethodHintsState(Qt::ImhNone); + InputEngine engine(backend); + backend->setActiveState(true); + + // Automatic shift requires a supporting composer + QVERIFY(!engine.shiftActive()); + engine.setTextComposer(new BasicTextComposer); + QVERIFY(engine.shiftActive()); + + // Preedit and input hints can suppress automatic shift + engine.setPreeditText(QStringLiteral("composition")); + QVERIFY(!engine.shiftActive()); + engine.setPreeditText(QString()); + QVERIFY(engine.shiftActive()); + + backend->setInputMethodHintsState(Qt::ImhNoAutoUppercase); + QVERIFY(!engine.shiftActive()); + backend->setInputMethodHintsState(Qt::ImhNone); + QVERIFY(engine.shiftActive()); + + // Uppercase preference uses persistent caps lock + backend->setInputMethodHintsState(Qt::ImhPreferUppercase); + QVERIFY(engine.capsLockActive()); + QVERIFY(engine.uppercase()); + + // Unsupported composers and inactive input clear uppercase state + engine.setTextComposer(new DirectTextComposer); + QVERIFY(!engine.shiftActive()); + QVERIFY(!engine.capsLockActive()); + + engine.setTextComposer(new BasicTextComposer); + backend->setInputMethodHintsState(Qt::ImhNone); + backend->setActiveState(false); + QVERIFY(!engine.shiftActive()); + QVERIFY(!engine.capsLockActive()); + } +}; + +QTEST_GUILESS_MAIN(InputEngineTest) + +#include "inputenginetest.moc" diff --git a/autotests/mockinputmethodcompositor.cpp b/autotests/mockinputmethodcompositor.cpp index 09177e7..adcac1c 100644 --- a/autotests/mockinputmethodcompositor.cpp +++ b/autotests/mockinputmethodcompositor.cpp @@ -538,7 +538,7 @@ private Q_SLOTS: { KConfig cfg(QStringLiteral("plasmakeyboardrc")); KConfigGroup grp(&cfg, QStringLiteral("General")); - grp.writeEntry(QStringLiteral("enabledLocales"), QStringLiteral("it_IT")); + grp.writeEntry(QStringLiteral("enabledKeyboardLayoutIds"), QStringLiteral("org.kde.plasma.keyboard.en/mobile-qwerty")); grp.writeEntry(QStringLiteral("keyboardNavigationEnabled"), true); // Set the long press threshold to max to avoid potential flakiness in CI where timing can be unpredictable. grp.writeEntry(QStringLiteral("diacriticsHoldThresholdMs"), 1500); @@ -746,6 +746,7 @@ private Q_SLOTS: QCOMPARE(commitStringSpy.first().first().toString(), QStringLiteral("q")); } + // Verify navigation consumes its keys and Escape restores forwarding void testKeyboardNavigationCommitsCharacter() { if (!m_inputPanel->surface()) { @@ -759,20 +760,102 @@ private Q_SLOTS: QSignalSpy commitStringSpy(m_inputMethod->context(), &InputMethodContext::commitStringChanged); QSignalSpy keysymSpy(m_inputMethod->context(), &InputMethodContext::keysymReceived); + QSignalSpy keySpy(m_inputMethod->context(), &InputMethodContext::keyReceived); - sendKey(KEY_RIGHT, 100); sendKey(KEY_RIGHT, 100); sendKey(KEY_RIGHT, 100); sendKey(KEY_ENTER, 100); QVERIFY(commitStringSpy.count() || commitStringSpy.wait()); QCOMPARE(commitStringSpy.count(), 1); - QCOMPARE(commitStringSpy.first().first().toString(), QStringLiteral("x")); + QCOMPARE(commitStringSpy.first().first().toString(), QStringLiteral("w")); for (const QList &args : keysymSpy) { const uint32_t sym = args.at(0).toUInt(); QVERIFY2(sym != XKB_KEY_Right && sym != XKB_KEY_Return, "Keyboard navigation keys were incorrectly forwarded via keysym"); } + + sendKey(KEY_ESC, 100); + sendKey(KEY_ENTER, 100); + + QTRY_COMPARE(commitStringSpy.count(), 2); + QCOMPARE(commitStringSpy.at(1).first().toString(), QStringLiteral("\r")); + + bool enterForwarded = false; + for (const QList &args : keySpy) { + const uint32_t key = args.at(0).toUInt(); + QVERIFY2(key != KEY_RIGHT && key != KEY_ESC, "A keyboard navigation key was incorrectly forwarded via key"); + enterForwarded = enterForwarded || key == KEY_ENTER; + } + QVERIFY(enterForwarded); + } + + // Verify Right continues at the start of the next row + void testKeyboardNavigationMovesRightToNextRow() + { + QSignalSpy commitStringSpy(m_inputMethod->context(), &InputMethodContext::commitStringChanged); + + for (int i = 0; i < 11; ++i) { + sendKey(KEY_RIGHT, 20); + } + sendKey(KEY_ENTER, 100); + + QVERIFY(commitStringSpy.count() || commitStringSpy.wait()); + QCOMPARE(commitStringSpy.count(), 1); + QCOMPARE(commitStringSpy.first().first().toString(), QStringLiteral("a")); + + sendKey(KEY_ESC, 100); + } + + // Verify reopening the keyboard resets navigation + void testKeyboardNavigationResetsAfterReopen() + { + sendKey(KEY_RIGHT, 20); + sendKey(KEY_RIGHT, 20); + + m_inputMethod->sendDeactivate(); + wl_display_flush_clients(m_compositor->display()); + QTest::qWait(100); + + m_inputMethod->sendActivate(); + wl_display_flush_clients(m_compositor->display()); + QVERIFY(m_inputMethod->context()); + if (!m_inputMethod->context()->keyboard()) { + QSignalSpy grabSpy(m_inputMethod->context(), &InputMethodContext::keyboardGrabbed); + QVERIFY(grabSpy.wait()); + } + + QSignalSpy commitStringSpy(m_inputMethod->context(), &InputMethodContext::commitStringChanged); + sendKey(KEY_RIGHT, 20); + sendKey(KEY_ENTER, 100); + + QVERIFY(commitStringSpy.count() || commitStringSpy.wait()); + QCOMPARE(commitStringSpy.count(), 1); + QCOMPARE(commitStringSpy.first().first().toString(), QStringLiteral("q")); + + sendKey(KEY_ESC, 100); + } + + // Verify long press keeps alternate selection open + void testKeyboardNavigationLongPressOpensAlternativeKeys() + { + QSignalSpy commitStringSpy(m_inputMethod->context(), &InputMethodContext::commitStringChanged); + + sendKey(KEY_RIGHT, 20); + sendKey(KEY_RIGHT, 20); + sendKey(KEY_RIGHT, 20); + sendKey(KEY_ENTER, 600); + QTest::qWait(100); + QVERIFY(commitStringSpy.isEmpty()); + + sendKey(KEY_RIGHT, 100); + sendKey(KEY_ENTER, 100); + + QVERIFY(commitStringSpy.count() || commitStringSpy.wait()); + QCOMPARE(commitStringSpy.count(), 1); + QCOMPARE(commitStringSpy.first().first().toString(), QStringLiteral("ë")); + + sendKey(KEY_ESC, 100); } void testLongPressShowsOverlayPanel() @@ -786,7 +869,7 @@ private Q_SLOTS: sendKey(KEY_1, 10); QVERIFY(commitStringSpy.count() || commitStringSpy.wait()); QCOMPARE(commitStringSpy.count(), 1); - QCOMPARE(commitStringSpy.first().first().toString(), QStringLiteral("à")); + QCOMPARE(commitStringSpy.first().first().toString(), QStringLiteral("á")); } /** Test that a short press of a key does not trigger the overlay panel and commits the expected character. */ diff --git a/kcm/CMakeLists.txt b/kcm/CMakeLists.txt index 40c60d5..117017f 100644 --- a/kcm/CMakeLists.txt +++ b/kcm/CMakeLists.txt @@ -8,10 +8,20 @@ kcmutils_add_qml_kcm(kcm_plasmakeyboard) kconfig_add_kcfg_files(kcm_plasmakeyboard GENERATE_MOC plasmakeyboardsettings.kcfgc) target_sources(kcm_plasmakeyboard PRIVATE + ../virtualkeyboard/keyboardlayoutmetadata.cpp + ../virtualkeyboard/keyboardlayoutmetadata.h + keyboardlayoutgroupmodel.cpp + keyboardlayoutgroupmodel.h + keyboardlayoutmodel.cpp + keyboardlayoutmodel.h plasmakeyboardkcm.cpp plasmakeyboardkcm.h ) +target_include_directories(kcm_plasmakeyboard PRIVATE + ${CMAKE_SOURCE_DIR}/virtualkeyboard +) + target_link_libraries(kcm_plasmakeyboard PRIVATE Qt::Core Qt::Qml diff --git a/kcm/keyboardlayoutgroupmodel.cpp b/kcm/keyboardlayoutgroupmodel.cpp new file mode 100644 index 0000000..3a0c3f4 --- /dev/null +++ b/kcm/keyboardlayoutgroupmodel.cpp @@ -0,0 +1,244 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "keyboardlayoutgroupmodel.h" + +#include "keyboardlayoutmetadata.h" + +#include +#include + +KeyboardLayoutGroupModel::KeyboardLayoutGroupModel(QObject *parent) + : QAbstractListModel(parent) + , m_flatLayouts(new KeyboardLayoutModel(this)) +{ +} + +int KeyboardLayoutGroupModel::rowCount(const QModelIndex &parent) const +{ + if (parent.isValid()) { + return 0; + } + return m_groups.size(); +} + +QVariant KeyboardLayoutGroupModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid() || index.row() < 0 || index.row() >= m_groups.size()) { + return {}; + } + + const Group &group = m_groups.at(index.row()); + switch (role) { + case GroupIdRole: + return group.groupId; + case NameRole: + return group.name; + case DescriptionRole: + return group.description; + case LayoutsRole: + return QVariant::fromValue(group.layouts); + case VisibleRole: + return group.layouts && group.layouts->visibleLayoutCount() > 0; + case DisplayExpandedRole: + return m_expandedGroupIds.contains(group.groupId) || !m_filterText.isEmpty(); + case SelectedCountRole: + return group.layouts ? group.layouts->enabledVisibleLayoutCount() : 0; + case VisibleLayoutCountRole: + return group.layouts ? group.layouts->visibleLayoutCount() : 0; + default: + return {}; + } +} + +QHash KeyboardLayoutGroupModel::roleNames() const +{ + return { + {GroupIdRole, "groupId"}, + {NameRole, "name"}, + {DescriptionRole, "description"}, + {LayoutsRole, "layouts"}, + {VisibleRole, "matchesFilter"}, + {DisplayExpandedRole, "displayExpanded"}, + {SelectedCountRole, "selectedCount"}, + {VisibleLayoutCountRole, "visibleLayoutCount"}, + }; +} + +KeyboardLayoutModel *KeyboardLayoutGroupModel::layouts() const +{ + return m_flatLayouts; +} + +QString KeyboardLayoutGroupModel::layoutForLocale(const QString &locale) const +{ + return m_flatLayouts->layoutForLocale(locale); +} + +QString KeyboardLayoutGroupModel::filterText() const +{ + return m_filterText; +} + +void KeyboardLayoutGroupModel::setFilterText(const QString &filterText) +{ + const QString normalizedFilter = filterText.toLower(); + if (m_filterText == normalizedFilter) { + return; + } + + m_filterText = normalizedFilter; + refreshChildModels(); + Q_EMIT filterTextChanged(); + emitDataChanged(); +} + +void KeyboardLayoutGroupModel::setEnabledLayoutIds(const QStringList &enabledLayoutIds) +{ + if (m_enabledLayoutIds == enabledLayoutIds) { + return; + } + + m_enabledLayoutIds = enabledLayoutIds; + refreshChildModels(); + emitDataChanged(); +} + +void KeyboardLayoutGroupModel::toggleExpanded(const QString &groupId) +{ + const int index = m_expandedGroupIds.indexOf(groupId); + if (index == -1) { + m_expandedGroupIds.append(groupId); + } else { + m_expandedGroupIds.removeAt(index); + } + emitDataChanged(); +} + +void KeyboardLayoutGroupModel::setFormFactorFilter(const QStringList &formFactorFilter) +{ + if (m_formFactorFilter == formFactorFilter) { + return; + } + + m_formFactorFilter = formFactorFilter; + loadInstalledGroups(); +} + +void KeyboardLayoutGroupModel::loadInstalledGroups() +{ + beginResetModel(); + clearGroups(); + + QHash groupIndexByPackageId; + QList flatLayouts; + QList> groupedLayouts; + + for (const auto &entry : KeyboardLayoutMetadata::keyboardLayouts()) { + if (!matchesFormFactor(entry.formFactors)) { + continue; + } + + const QString layoutName = KeyboardLayoutMetadata::keyboardLayoutName(entry.layoutDefinition); + const QString keyboardName = KeyboardLayoutMetadata::keyboardDisplayName(entry); + const QString displayName = layoutName.isEmpty() ? keyboardName : keyboardName + QStringLiteral(" - ") + layoutName; + + flatLayouts.append({ + .layoutId = entry.layoutId, + .name = displayName, + .description = KeyboardLayoutModel::descriptionForLocales(entry.locales), + .locales = entry.locales, + }); + + if (!groupIndexByPackageId.contains(entry.packageId)) { + const QString localeDescription = KeyboardLayoutModel::descriptionForLocales(entry.locales); + groupIndexByPackageId.insert(entry.packageId, m_groups.size()); + groupedLayouts.append(QList{}); + m_groups.append({ + .groupId = entry.packageId, + .name = entry.keyboardName.isEmpty() ? localeDescription : entry.keyboardName, + .description = localeDescription, + }); + } + + groupedLayouts[groupIndexByPackageId.value(entry.packageId)].append({ + .layoutId = entry.layoutId, + .name = layoutName.isEmpty() ? displayName : layoutName, + .description = entry.layoutId, + .locales = entry.locales, + }); + } + + for (int i = 0; i < m_groups.size(); ++i) { + QList layouts = std::move(groupedLayouts[i]); + std::sort(layouts.begin(), layouts.end(), [](const auto &left, const auto &right) { + return left.name.localeAwareCompare(right.name) < 0; + }); + auto *layoutModel = new KeyboardLayoutModel(this); + layoutModel->setLayouts(std::move(layouts)); + m_groups[i].layouts = layoutModel; + } + std::sort(m_groups.begin(), m_groups.end(), [](const auto &left, const auto &right) { + return left.name.localeAwareCompare(right.name) < 0; + }); + + std::sort(flatLayouts.begin(), flatLayouts.end(), [](const auto &left, const auto &right) { + return left.name.localeAwareCompare(right.name) < 0; + }); + m_flatLayouts->setLayouts(std::move(flatLayouts)); + refreshChildModels(); + endResetModel(); +} + +void KeyboardLayoutGroupModel::clearGroups() +{ + for (const auto &group : std::as_const(m_groups)) { + delete group.layouts; + } + m_groups.clear(); +} + +bool KeyboardLayoutGroupModel::matchesFormFactor(const QStringList &formFactors) const +{ + if (m_formFactorFilter.isEmpty() || formFactors.isEmpty()) { + return true; + } + + for (const QString &formFactor : m_formFactorFilter) { + if (formFactors.contains(formFactor)) { + return true; + } + } + + return false; +} + +bool KeyboardLayoutGroupModel::groupNameMatches(const Group &group) const +{ + return m_filterText.isEmpty() || group.name.toLower().contains(m_filterText) || group.description.toLower().contains(m_filterText); +} + +void KeyboardLayoutGroupModel::refreshChildModels() +{ + m_flatLayouts->setEnabledLayoutIds(m_enabledLayoutIds); + m_flatLayouts->setFilterText(m_filterText); + for (const auto &group : std::as_const(m_groups)) { + if (!group.layouts) { + continue; + } + group.layouts->setEnabledLayoutIds(m_enabledLayoutIds); + group.layouts->setFilterText(groupNameMatches(group) ? QString() : m_filterText); + } +} + +void KeyboardLayoutGroupModel::emitDataChanged() +{ + if (m_groups.isEmpty()) { + return; + } + + Q_EMIT dataChanged(index(0), index(m_groups.size() - 1), {VisibleRole, DisplayExpandedRole, SelectedCountRole, VisibleLayoutCountRole}); +} diff --git a/kcm/keyboardlayoutgroupmodel.h b/kcm/keyboardlayoutgroupmodel.h new file mode 100644 index 0000000..ec9eca4 --- /dev/null +++ b/kcm/keyboardlayoutgroupmodel.h @@ -0,0 +1,74 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include "keyboardlayoutmodel.h" + +#include +#include + +/** + * Groups installed keyboard layouts by package for display in the KCM. + */ +class KeyboardLayoutGroupModel : public QAbstractListModel +{ + Q_OBJECT + Q_PROPERTY(QString filterText READ filterText WRITE setFilterText NOTIFY filterTextChanged) + +public: + enum Role { + GroupIdRole = Qt::UserRole + 1, + NameRole, + DescriptionRole, + LayoutsRole, + VisibleRole, + DisplayExpandedRole, + SelectedCountRole, + VisibleLayoutCountRole, + }; + Q_ENUM(Role) + + struct Group { + QString groupId; + QString name; + QString description; + KeyboardLayoutModel *layouts = nullptr; + }; + + explicit KeyboardLayoutGroupModel(QObject *parent = nullptr); + + int rowCount(const QModelIndex &parent = {}) const override; + QVariant data(const QModelIndex &index, int role) const override; + QHash roleNames() const override; + + KeyboardLayoutModel *layouts() const; + QString layoutForLocale(const QString &locale) const; + QString filterText() const; + void setFilterText(const QString &filterText); + void setEnabledLayoutIds(const QStringList &enabledLayoutIds); + Q_INVOKABLE void toggleExpanded(const QString &groupId); + + void loadInstalledGroups(); + void setFormFactorFilter(const QStringList &formFactorFilter); + +Q_SIGNALS: + void filterTextChanged(); + +private: + bool matchesFormFactor(const QStringList &formFactors) const; + bool groupNameMatches(const Group &group) const; + void clearGroups(); + void refreshChildModels(); + void emitDataChanged(); + + QList m_groups; + KeyboardLayoutModel *m_flatLayouts = nullptr; + QStringList m_formFactorFilter; + QString m_filterText; + QStringList m_enabledLayoutIds; + QStringList m_expandedGroupIds; +}; diff --git a/kcm/keyboardlayoutmodel.cpp b/kcm/keyboardlayoutmodel.cpp new file mode 100644 index 0000000..136506e --- /dev/null +++ b/kcm/keyboardlayoutmodel.cpp @@ -0,0 +1,156 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "keyboardlayoutmodel.h" + +#include + +KeyboardLayoutModel::KeyboardLayoutModel(QObject *parent) + : QAbstractListModel(parent) +{ +} + +int KeyboardLayoutModel::rowCount(const QModelIndex &parent) const +{ + if (parent.isValid()) { + return 0; + } + return m_layouts.size(); +} + +QVariant KeyboardLayoutModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid() || index.row() < 0 || index.row() >= m_layouts.size()) { + return {}; + } + + const Layout &layout = m_layouts.at(index.row()); + switch (role) { + case LayoutIdRole: + return layout.layoutId; + case NameRole: + return layout.name; + case DescriptionRole: + return layout.description; + case VisibleRole: + return matchesFilter(layout, m_filterText); + case EnabledRole: + return m_enabledLayoutIds.contains(layout.layoutId); + default: + return {}; + } +} + +QHash KeyboardLayoutModel::roleNames() const +{ + return { + {LayoutIdRole, "layoutId"}, + {NameRole, "name"}, + {DescriptionRole, "description"}, + {VisibleRole, "matchesFilter"}, + {EnabledRole, "enabled"}, + }; +} + +void KeyboardLayoutModel::setFilterText(const QString &filterText) +{ + const QString normalizedFilter = filterText.toLower(); + if (m_filterText == normalizedFilter) { + return; + } + + m_filterText = normalizedFilter; + emitDataChanged(); +} + +void KeyboardLayoutModel::setEnabledLayoutIds(const QStringList &enabledLayoutIds) +{ + if (m_enabledLayoutIds == enabledLayoutIds) { + return; + } + + m_enabledLayoutIds = enabledLayoutIds; + emitDataChanged(); +} + +int KeyboardLayoutModel::visibleLayoutCount() const +{ + int count = 0; + for (const auto &layout : m_layouts) { + if (matchesFilter(layout, m_filterText)) { + ++count; + } + } + return count; +} + +int KeyboardLayoutModel::enabledVisibleLayoutCount() const +{ + int count = 0; + for (const auto &layout : m_layouts) { + if (matchesFilter(layout, m_filterText) && m_enabledLayoutIds.contains(layout.layoutId)) { + ++count; + } + } + return count; +} + +QString KeyboardLayoutModel::layoutForLocale(const QString &locale) const +{ + const QString languageCode = locale.section(QLatin1Char('_'), 0, 0); + + for (const auto &layout : m_layouts) { + if (layout.locales.contains(locale)) { + return layout.layoutId; + } + } + + for (const auto &layout : m_layouts) { + for (const auto &candidateLocale : layout.locales) { + if (candidateLocale.section(QLatin1Char('_'), 0, 0) == languageCode) { + return layout.layoutId; + } + } + } + + return QStringLiteral("org.kde.plasma.keyboard.en/qwerty"); +} + +void KeyboardLayoutModel::emitDataChanged() +{ + if (m_layouts.isEmpty()) { + return; + } + + Q_EMIT dataChanged(index(0), index(m_layouts.size() - 1), {VisibleRole, EnabledRole}); +} + +void KeyboardLayoutModel::setLayouts(QList layouts) +{ + beginResetModel(); + m_layouts = std::move(layouts); + endResetModel(); +} + +bool KeyboardLayoutModel::matchesFilter(const Layout &layout, const QString &filterText) +{ + return filterText.isEmpty() || layout.name.toLower().contains(filterText) || layout.description.toLower().contains(filterText); +} + +QString KeyboardLayoutModel::descriptionForLocales(const QStringList &locales) +{ + QStringList names; + names.reserve(locales.size()); + + for (const auto &locale : locales) { + const QLocale qlocale(locale); + const QString language = qlocale.nativeLanguageName(); + const QString territory = qlocale.nativeTerritoryName(); + names.append(territory.isEmpty() ? language : language + QStringLiteral(" (") + territory + QStringLiteral(")")); + } + + return names.join(QStringLiteral(", ")); +} diff --git a/kcm/keyboardlayoutmodel.h b/kcm/keyboardlayoutmodel.h new file mode 100644 index 0000000..9f1e59f --- /dev/null +++ b/kcm/keyboardlayoutmodel.h @@ -0,0 +1,57 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include +#include + +/** + * Provides filterable keyboard layout entries for the KCM. + */ +class KeyboardLayoutModel : public QAbstractListModel +{ + Q_OBJECT + +public: + enum Role { + LayoutIdRole = Qt::UserRole + 1, + NameRole, + DescriptionRole, + VisibleRole, + EnabledRole, + }; + Q_ENUM(Role) + + struct Layout { + QString layoutId; + QString name; + QString description; + QStringList locales; + }; + + explicit KeyboardLayoutModel(QObject *parent = nullptr); + + int rowCount(const QModelIndex &parent = {}) const override; + QVariant data(const QModelIndex &index, int role) const override; + QHash roleNames() const override; + + void setFilterText(const QString &filterText); + void setEnabledLayoutIds(const QStringList &enabledLayoutIds); + int visibleLayoutCount() const; + int enabledVisibleLayoutCount() const; + QString layoutForLocale(const QString &locale) const; + void setLayouts(QList layouts); + static QString descriptionForLocales(const QStringList &locales); + static bool matchesFilter(const Layout &layout, const QString &filterText); + +private: + void emitDataChanged(); + + QList m_layouts; + QString m_filterText; + QStringList m_enabledLayoutIds; +}; diff --git a/kcm/plasmakeyboardkcm.cpp b/kcm/plasmakeyboardkcm.cpp index 284c454..c2fc0bd 100644 --- a/kcm/plasmakeyboardkcm.cpp +++ b/kcm/plasmakeyboardkcm.cpp @@ -6,7 +6,10 @@ */ #include "plasmakeyboardkcm.h" -#include "../src/layoutpathhelper.h" + +#include "keyboardlayoutmetadata.h" + +#include #include @@ -15,34 +18,38 @@ K_PLUGIN_CLASS_WITH_JSON(PlasmaKeyboardKcm, "kcm_plasmakeyboard.json") PlasmaKeyboardKcm::PlasmaKeyboardKcm(QObject *parent, const KPluginMetaData &metaData) : KQuickManagedConfigModule(parent, metaData) , m_settings(new PlasmaKeyboardSettings(this)) + , m_availableKeyboardLayoutGroups(new KeyboardLayoutGroupModel(this)) { - initLayoutsPath(); - qmlRegisterAnonymousType("org.kde.plasma.keyboard.settings", 0); -} -void PlasmaKeyboardKcm::enableLocale(const QString &locale) -{ - auto enabledLocales = plasmaKeyboardSettings()->enabledLocales(); - - if (enabledLocales.contains(locale)) { - return; + m_keyboardLayoutFormFactorFilter = KRuntimePlatform::runtimePlatform(); + m_keyboardLayoutFormFactorFilter.removeAll(QString()); + if (m_keyboardLayoutFormFactorFilter.isEmpty()) { + m_keyboardLayoutFormFactorFilter = {QStringLiteral("desktop")}; } - enabledLocales.append(locale); - plasmaKeyboardSettings()->setEnabledLocales(enabledLocales); -} + refreshAvailableKeyboardLayoutFilter(); + m_hasHiddenKeyboardLayouts = m_availableKeyboardLayoutGroups->layouts()->rowCount() < KeyboardLayoutMetadata::keyboardLayouts().size(); -void PlasmaKeyboardKcm::disableLocale(const QString &locale) -{ - auto enabledLocales = plasmaKeyboardSettings()->enabledLocales(); - - if (!enabledLocales.contains(locale)) { - return; + QStringList enabledKeyboardLayoutIds = m_settings->enabledKeyboardLayoutIds(); + if (enabledKeyboardLayoutIds.isEmpty()) { + const QStringList enabledLocales = m_settings->enabledLocales(); + for (const QString &locale : enabledLocales) { + const QString layoutId = m_availableKeyboardLayoutGroups->layoutForLocale(locale); + if (!layoutId.isEmpty() && !enabledKeyboardLayoutIds.contains(layoutId)) { + enabledKeyboardLayoutIds.append(layoutId); + } + } + if (!enabledKeyboardLayoutIds.isEmpty()) { + m_settings->setEnabledKeyboardLayoutIds(enabledKeyboardLayoutIds); + m_settings->setEnabledLocales({}); + } } - enabledLocales.removeAll(locale); + m_availableKeyboardLayoutGroups->setEnabledLayoutIds(enabledKeyboardLayoutIds); - plasmaKeyboardSettings()->setEnabledLocales(enabledLocales); + connect(m_settings, &PlasmaKeyboardSettings::enabledKeyboardLayoutIdsChanged, this, [this]() { + m_availableKeyboardLayoutGroups->setEnabledLayoutIds(m_settings->enabledKeyboardLayoutIds()); + }); } PlasmaKeyboardSettings *PlasmaKeyboardKcm::plasmaKeyboardSettings() const @@ -50,6 +57,63 @@ PlasmaKeyboardSettings *PlasmaKeyboardKcm::plasmaKeyboardSettings() const return m_settings; } +QAbstractItemModel *PlasmaKeyboardKcm::availableKeyboardLayouts() const +{ + return m_availableKeyboardLayoutGroups->layouts(); +} + +QAbstractItemModel *PlasmaKeyboardKcm::availableKeyboardLayoutGroups() const +{ + return m_availableKeyboardLayoutGroups; +} + +bool PlasmaKeyboardKcm::hasHiddenKeyboardLayouts() const +{ + return m_hasHiddenKeyboardLayouts; +} + +bool PlasmaKeyboardKcm::keyboardLayoutFormFactorFilterEnabled() const +{ + return m_keyboardLayoutFormFactorFilterEnabled; +} + +void PlasmaKeyboardKcm::setKeyboardLayoutFormFactorFilterEnabled(bool enabled) +{ + if (enabled == m_keyboardLayoutFormFactorFilterEnabled) { + return; + } + + m_keyboardLayoutFormFactorFilterEnabled = enabled; + Q_EMIT keyboardLayoutFormFactorFilterEnabledChanged(); + refreshAvailableKeyboardLayoutFilter(); +} + +void PlasmaKeyboardKcm::enableKeyboardLayout(const QString &layoutId) +{ + QStringList enabledKeyboardLayoutIds = m_settings->enabledKeyboardLayoutIds(); + if (enabledKeyboardLayoutIds.contains(layoutId)) { + return; + } + + enabledKeyboardLayoutIds.append(layoutId); + m_settings->setEnabledKeyboardLayoutIds(enabledKeyboardLayoutIds); +} + +void PlasmaKeyboardKcm::disableKeyboardLayout(const QString &layoutId) +{ + QStringList enabledKeyboardLayoutIds = m_settings->enabledKeyboardLayoutIds(); + if (!enabledKeyboardLayoutIds.removeAll(layoutId)) { + return; + } + + m_settings->setEnabledKeyboardLayoutIds(enabledKeyboardLayoutIds); +} + +void PlasmaKeyboardKcm::refreshAvailableKeyboardLayoutFilter() +{ + m_availableKeyboardLayoutGroups->setFormFactorFilter(keyboardLayoutFormFactorFilterEnabled() ? m_keyboardLayoutFormFactorFilter : QStringList{}); +} + #include "plasmakeyboardkcm.moc" #include "moc_plasmakeyboardkcm.cpp" diff --git a/kcm/plasmakeyboardkcm.h b/kcm/plasmakeyboardkcm.h index d918a0e..8208a33 100644 --- a/kcm/plasmakeyboardkcm.h +++ b/kcm/plasmakeyboardkcm.h @@ -9,21 +9,44 @@ #include +#include "keyboardlayoutgroupmodel.h" #include "plasmakeyboardsettings.h" +class QAbstractItemModel; + class PlasmaKeyboardKcm : public KQuickManagedConfigModule { Q_OBJECT Q_PROPERTY(PlasmaKeyboardSettings *plasmaKeyboardSettings READ plasmaKeyboardSettings CONSTANT) + Q_PROPERTY(QAbstractItemModel *availableKeyboardLayouts READ availableKeyboardLayouts CONSTANT) + Q_PROPERTY(QAbstractItemModel *availableKeyboardLayoutGroups READ availableKeyboardLayoutGroups CONSTANT) + Q_PROPERTY(bool hasHiddenKeyboardLayouts READ hasHiddenKeyboardLayouts CONSTANT) + Q_PROPERTY(bool keyboardLayoutFormFactorFilterEnabled READ keyboardLayoutFormFactorFilterEnabled WRITE setKeyboardLayoutFormFactorFilterEnabled NOTIFY + keyboardLayoutFormFactorFilterEnabledChanged) public: PlasmaKeyboardKcm(QObject *parent, const KPluginMetaData &metaData); PlasmaKeyboardSettings *plasmaKeyboardSettings() const; + QAbstractItemModel *availableKeyboardLayouts() const; + QAbstractItemModel *availableKeyboardLayoutGroups() const; + bool hasHiddenKeyboardLayouts() const; - Q_INVOKABLE void enableLocale(const QString &locale); - Q_INVOKABLE void disableLocale(const QString &locale); + bool keyboardLayoutFormFactorFilterEnabled() const; + void setKeyboardLayoutFormFactorFilterEnabled(bool enabled); + + Q_INVOKABLE void enableKeyboardLayout(const QString &layoutId); + Q_INVOKABLE void disableKeyboardLayout(const QString &layoutId); + +Q_SIGNALS: + void keyboardLayoutFormFactorFilterEnabledChanged(); private: + void refreshAvailableKeyboardLayoutFilter(); + PlasmaKeyboardSettings *m_settings = nullptr; + KeyboardLayoutGroupModel *m_availableKeyboardLayoutGroups = nullptr; + QStringList m_keyboardLayoutFormFactorFilter; + bool m_hasHiddenKeyboardLayouts = false; + bool m_keyboardLayoutFormFactorFilterEnabled = true; }; diff --git a/kcm/ui/KeyboardLayoutSelectorListView.qml b/kcm/ui/KeyboardLayoutSelectorListView.qml new file mode 100644 index 0000000..89610e3 --- /dev/null +++ b/kcm/ui/KeyboardLayoutSelectorListView.qml @@ -0,0 +1,183 @@ +/* + SPDX-FileCopyrightText: 2025 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +import QtQuick +import QtQuick.Controls as QQC2 +import QtQuick.Layouts + +import org.kde.kirigami as Kirigami + +ListView { + id: root + + model: kcm.availableKeyboardLayoutGroups + + headerPositioning: ListView.OverlayHeader + header: QQC2.ToolBar { + width: parent.width + z: 999 + position: QQC2.ToolBar.Header + + topPadding: Kirigami.Units.largeSpacing + bottomPadding: Kirigami.Units.largeSpacing + leftPadding: Kirigami.Units.largeSpacing + rightPadding: Kirigami.Units.largeSpacing + + Kirigami.Theme.inherit: false + Kirigami.Theme.colorSet: Kirigami.Theme.Window + + contentItem: ColumnLayout { + spacing: 0 + + Kirigami.SearchField { + id: searchField + placeholderText: i18n("Filter languages…") + Accessible.name: i18n("Filter languages") + + Layout.fillWidth: true + + onTextChanged: { + kcm.availableKeyboardLayoutGroups.filterText = text; + searchField.forceActiveFocus(); + } + } + + QQC2.CheckBox { + Layout.topMargin: Kirigami.Units.smallSpacing + + text: i18nc("@option:check", "Show all layouts") + visible: kcm.hasHiddenKeyboardLayouts + checked: !kcm.keyboardLayoutFormFactorFilterEnabled + + Layout.fillWidth: true + + onCheckedChanged: { + kcm.keyboardLayoutFormFactorFilterEnabled = !checked; + checked = Qt.binding(() => !kcm.keyboardLayoutFormFactorFilterEnabled); + } + } + + Kirigami.InlineMessage { + Layout.topMargin: Kirigami.Units.smallSpacing + Layout.fillWidth: true + text: i18n("No keyboard layouts selected. The default keyboard layout for the system will be used.") + type: Kirigami.MessageType.Information + visible: kcm.plasmaKeyboardSettings.enabledKeyboardLayoutIds.length === 0 + } + } + } + + delegate: ColumnLayout { + id: groupDelegate + + required property string groupId + required property string name + required property string description + required property var layouts + required property bool matchesFilter + required property bool displayExpanded + required property int selectedCount + required property int visibleLayoutCount + + width: root.width + height: matchesFilter ? implicitHeight : 0 + visible: matchesFilter + spacing: 0 + + QQC2.ItemDelegate { + Layout.fillWidth: true + text: groupDelegate.name + onClicked: kcm.availableKeyboardLayoutGroups.toggleExpanded(groupDelegate.groupId) + + contentItem: RowLayout { + spacing: Kirigami.Units.smallSpacing + + Kirigami.Icon { + source: displayExpanded ? "go-down-symbolic" : "go-next-symbolic" + implicitWidth: Kirigami.Units.iconSizes.small + implicitHeight: implicitWidth + } + + ColumnLayout { + Layout.fillWidth: true + spacing: Kirigami.Units.smallSpacing + + QQC2.Label { + Layout.fillWidth: true + text: groupDelegate.name + elide: Text.ElideRight + } + + QQC2.Label { + Layout.fillWidth: true + text: { + const selectionText = selectedCount === 0 + ? i18np("%1 layout", "%1 layouts", visibleLayoutCount) + : i18n("%1 of %2 selected", selectedCount, visibleLayoutCount); + return selectionText; + } + elide: Text.ElideRight + opacity: 0.7 + font: Kirigami.Theme.smallFont + } + } + } + } + + ColumnLayout { + visible: displayExpanded + Layout.fillWidth: true + spacing: 0 + + Repeater { + model: groupDelegate.layouts + + delegate: QQC2.CheckDelegate { + id: layoutDelegate + + required property string layoutId + required property string name + required property string description + required property bool matchesFilter + required property bool enabled + Layout.fillWidth: true + visible: matchesFilter + height: matchesFilter ? implicitHeight : 0 + leftPadding: Kirigami.Units.gridUnit * 2 + text: layoutDelegate.name + checked: layoutDelegate.enabled + + contentItem: ColumnLayout { + spacing: Kirigami.Units.smallSpacing + + QQC2.Label { + Layout.fillWidth: true + text: layoutDelegate.name + elide: Text.ElideRight + } + + QQC2.Label { + Layout.fillWidth: true + text: layoutDelegate.description + visible: text.length > 0 + elide: Text.ElideRight + opacity: 0.7 + font: Kirigami.Theme.smallFont + } + } + + onCheckedChanged: { + if (checked) { + kcm.enableKeyboardLayout(layoutDelegate.layoutId); + } else { + kcm.disableKeyboardLayout(layoutDelegate.layoutId); + } + } + } + } + } + } +} diff --git a/kcm/ui/KeyboardLayoutSelectorSidebar.qml b/kcm/ui/KeyboardLayoutSelectorSidebar.qml new file mode 100644 index 0000000..e502687 --- /dev/null +++ b/kcm/ui/KeyboardLayoutSelectorSidebar.qml @@ -0,0 +1,51 @@ +/* + SPDX-FileCopyrightText: 2025 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC2 + +import org.kde.bigscreen as Bigscreen + +Bigscreen.SidebarOverlay { + id: root + + openFocusItem: layoutList + header: Bigscreen.SidebarOverlayHeader { + title: i18n("Keyboard Layouts") + } + + content: QQC2.ScrollView { + ListView { + id: layoutList + Layout.fillWidth: true + implicitHeight: contentHeight + clip: true + model: kcm.availableKeyboardLayouts + + delegate: Bigscreen.SwitchDelegate { + id: layoutDelegate + + required property string layoutId + required property string name + required property string description + + width: layoutList.width + text: layoutDelegate.name + description: layoutDelegate.description + checked: kcm.plasmaKeyboardSettings.enabledKeyboardLayoutIds.includes(layoutDelegate.layoutId) + + onCheckedChanged: { + if (checked) { + kcm.enableKeyboardLayout(layoutDelegate.layoutId); + } else { + kcm.disableKeyboardLayout(layoutDelegate.layoutId); + } + } + } + } + } +} diff --git a/kcm/ui/LocaleSelectorListView.qml b/kcm/ui/LocaleSelectorListView.qml deleted file mode 100644 index def6ebb..0000000 --- a/kcm/ui/LocaleSelectorListView.qml +++ /dev/null @@ -1,101 +0,0 @@ -/* - SPDX-FileCopyrightText: 2025 Devin Lin - - SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL -*/ - -import QtQuick -import QtQuick.Controls as QQC2 -import QtQuick.Layouts - -import QtQuick.VirtualKeyboard -import QtQuick.VirtualKeyboard.Settings - -import org.kde.kitemmodels -import org.kde.kirigami as Kirigami - -ListView { - id: root - - property var sourceModel: [] - property string searchText: '' - - model: sourceModel - - function updateModel() { - let list = []; - for (let locale of sourceModel) { - const localeText = Qt.locale(locale).nativeLanguageName; - if (searchText.length === 0 || localeText.toLowerCase().indexOf(searchText.toLowerCase()) !== -1) { - list.push(locale) - } - } - model = list; - } - onSearchTextChanged: updateModel() - onSourceModelChanged: updateModel() - - Connections { - target: VirtualKeyboardSettings - - function onAvailableLocalesChanged() { - root.sourceModel = VirtualKeyboardSettings.availableLocales; - } - } - - // HACK: needed to populate VirtualKeyboardSettings.availableLocales - InputPanel {} - - headerPositioning: ListView.OverlayHeader - header: QQC2.ToolBar { - width: parent.width - z: 999 // On top of content - position: QQC2.ToolBar.Header - - topPadding: Kirigami.Units.largeSpacing - bottomPadding: Kirigami.Units.largeSpacing - leftPadding: Kirigami.Units.largeSpacing - rightPadding: Kirigami.Units.largeSpacing - - Kirigami.Theme.inherit: false - Kirigami.Theme.colorSet: Kirigami.Theme.Window - - contentItem: ColumnLayout { - spacing: 0 - - Kirigami.SearchField { - id: searchField - placeholderText: i18n("Filter languages…") - Accessible.name: i18n("Filter languages") - - Layout.fillWidth: true - - onTextChanged: { - root.searchText = text; - searchField.forceActiveFocus(); - } - } - - Kirigami.InlineMessage { - Layout.topMargin: Kirigami.Units.smallSpacing - Layout.fillWidth: true - text: i18n("No languages selected. The default keyboard layout for the system will be used.") - type: Kirigami.MessageType.Information - visible: kcm.plasmaKeyboardSettings.enabledLocales.length === 0 - } - } - } - - delegate: QQC2.CheckDelegate { - width: root.width - text: Qt.locale(modelData).nativeLanguageName - checked: kcm.plasmaKeyboardSettings.enabledLocales.includes(modelData) - onCheckedChanged: { - if (checked) { - kcm.enableLocale(modelData); - } else { - kcm.disableLocale(modelData); - } - } - } -} diff --git a/kcm/ui/LocaleSelectorSidebar.qml b/kcm/ui/LocaleSelectorSidebar.qml deleted file mode 100644 index 6f6c7b3..0000000 --- a/kcm/ui/LocaleSelectorSidebar.qml +++ /dev/null @@ -1,77 +0,0 @@ -/* - SPDX-FileCopyrightText: 2025 Devin Lin - - SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL -*/ - -import QtQuick -import QtQuick.Layouts -import QtQuick.Controls as QQC2 - -import org.kde.kirigami as Kirigami -import org.kde.bigscreen as Bigscreen - -import org.kde.kitemmodels -import QtQuick.VirtualKeyboard -import QtQuick.VirtualKeyboard.Settings - -Bigscreen.SidebarOverlay { - id: root - - property alias model: langs.model - - openFocusItem: langs - header: Bigscreen.SidebarOverlayHeader { - title: i18n("Languages") - iconSource: "language-chooser" - } - - function updateModel() { - let list = []; - for (let locale of sourceModel) { - const localeText = Qt.locale(locale).nativeLanguageName; - if (searchText.length === 0 || localeText.toLowerCase().indexOf(searchText.toLowerCase()) !== -1) { - list.push(locale); - } - } - model = list; - } - - onModelChanged: updateModel() - - Connections { - target: VirtualKeyboardSettings - - function onAvailableLocalesChanged() { - langs.model = VirtualKeyboardSettings.availableLocales; - } - } - - // HACK: needed to populate VirtualKeyboardSettings.availableLocales - InputPanel {} - - content: QQC2.ScrollView { - ListView { - id: langs - Layout.fillWidth: true - implicitHeight: contentHeight - clip: true - - delegate: Bigscreen.SwitchDelegate { - id: delegate - width: langs.width - text: Qt.locale(modelData).nativeLanguageName - onClicked: checked = !checked - Keys.onReturnPressed: checked = !checked - checked: kcm.plasmaKeyboardSettings.enabledLocales.includes(modelData) - onCheckedChanged: { - if (checked) { - kcm.enableLocale(modelData); - } else { - kcm.disableLocale(modelData); - } - } - } - } - } -} diff --git a/kcm/ui/main.qml b/kcm/ui/main.qml index b03ff57..d48724f 100644 --- a/kcm/ui/main.qml +++ b/kcm/ui/main.qml @@ -12,22 +12,28 @@ import QtQuick.Controls as QQC2 import org.kde.kirigami as Kirigami import org.kde.kcmutils as KCM -KCM.ScrollViewKCM { +KCM.SimpleKCM { id: root - view: LocaleSelectorListView { - id: list - - Kirigami.Separator { - anchors.bottom: parent.bottom - anchors.left: parent.left - anchors.right: parent.right - } - } - - footer: Kirigami.FormLayout { + Kirigami.FormLayout { id: formLayout + width: flickable.width + + QQC2.Button { + Kirigami.FormData.label: i18n("Keyboard layouts:") + text: i18n("Configure…") + icon.name: "languages" + onClicked: kcm.push(layoutPage); + + Kirigami.ScrollablePage { + id: layoutPage + title: i18n("Keyboard Layouts") + + KeyboardLayoutSelectorListView {} + } + } + QQC2.CheckBox { id: soundsEnabled Kirigami.FormData.label: i18n("Key press feedback:") @@ -45,6 +51,14 @@ KCM.ScrollViewKCM { onCheckedChanged: kcm.plasmaKeyboardSettings.vibrationEnabled = checked } + QQC2.CheckBox { + id: characterPopupEnabled + text: i18n("Character popup") + + checked: kcm.plasmaKeyboardSettings.characterPopupEnabled + onCheckedChanged: kcm.plasmaKeyboardSettings.characterPopupEnabled = checked + } + QQC2.CheckBox { id: keyboardNavigationEnabled Kirigami.FormData.label: i18n("General:") diff --git a/kcm/ui/main_handset.qml b/kcm/ui/main_handset.qml index 4c625c3..52d9999 100644 --- a/kcm/ui/main_handset.qml +++ b/kcm/ui/main_handset.qml @@ -54,22 +54,33 @@ KCM.SimpleKCM { checked: kcm.plasmaKeyboardSettings.vibrationEnabled onCheckedChanged: kcm.plasmaKeyboardSettings.vibrationEnabled = checked } + + FormCard.FormDelegateSeparator {} + + FormCard.FormSwitchDelegate { + id: characterPopupEnabled + text: i18n("Character popup") + description: i18n("Show a character popup when pressing text keys") + + checked: kcm.plasmaKeyboardSettings.characterPopupEnabled + onCheckedChanged: kcm.plasmaKeyboardSettings.characterPopupEnabled = checked + } } FormCard.FormCard { Layout.topMargin: Kirigami.Units.largeSpacing FormCard.FormButtonDelegate { - id: languageList - text: i18n("Languages") + id: layoutList + text: i18n("Keyboard Layouts") icon.name: 'languages' - onClicked: kcm.push(localePage) + onClicked: kcm.push(layoutPage) Kirigami.ScrollablePage { - id: localePage - title: i18n("Keyboard Languages") + id: layoutPage + title: i18n("Keyboard Layouts") - LocaleSelectorListView {} + KeyboardLayoutSelectorListView {} } } } diff --git a/kcm/ui/main_mediacenter.qml b/kcm/ui/main_mediacenter.qml index 25d583d..44a41bc 100644 --- a/kcm/ui/main_mediacenter.qml +++ b/kcm/ui/main_mediacenter.qml @@ -26,7 +26,7 @@ KCM.SimpleKCM { onActiveFocusChanged: { if (activeFocus) { - changeLanguagesButton.forceActiveFocus() + changeLayoutsButton.forceActiveFocus() } } @@ -36,16 +36,17 @@ KCM.SimpleKCM { spacing: 0 Bigscreen.ButtonDelegate { - id: changeLanguagesButton - text: i18n("Languages") + id: changeLayoutsButton + text: i18n("Keyboard Layouts") description: { - if (kcm.enabledLocales.length == 0) { - return i18n("No languages selected, the default keyboard layout for the system will be used") + const layoutCount = kcm.plasmaKeyboardSettings.enabledKeyboardLayoutIds.length; + if (layoutCount === 0) { + return i18n("No keyboard layouts selected, the default keyboard layout for the system will be used"); } - return i18ncp("%1 is the number of enabled locales", "%1 language selected", "%1 languages selected", kcm.enabledLocales.length) + return i18ncp("%1 is the number of enabled keyboard layouts", "%1 keyboard layout selected", "%1 keyboard layouts selected", layoutCount); } font.pixelSize: Bigscreen.Units.headingFontPixelSize - onClicked: localeSelectorSidebar.open() + onClicked: layoutSelectorSidebar.open() KeyNavigation.down: soundOnKeypressButton } @@ -62,6 +63,7 @@ KCM.SimpleKCM { id: soundOnKeypressButton text: i18nc("This is a noun", "Sound") description: i18n("A sound will play when a key is pressed") + KeyNavigation.up: changeLayoutsButton KeyNavigation.down: vibrationOnKeypressButton checked: kcm.plasmaKeyboardSettings.soundEnabled @@ -72,6 +74,7 @@ KCM.SimpleKCM { id: vibrationOnKeypressButton text: i18n("Vibration") description: i18n("If supported, the device will vibrate when a key is pressed") + KeyNavigation.up: soundOnKeypressButton KeyNavigation.down: autoCapitalizationButton checked: kcm.plasmaKeyboardSettings.vibrationEnabled @@ -90,7 +93,8 @@ KCM.SimpleKCM { Bigscreen.SwitchDelegate { id: autoCapitalizationButton text: i18n("Auto-capitalization") - description: i18n("Automatically capitalize the beginning of sentences and proper nouns") + description: i18n("Automatically capitalize the first letter of sentences") + KeyNavigation.up: vibrationOnKeypressButton KeyNavigation.down: altCharsPopupButton checked: kcm.plasmaKeyboardSettings.autoCapitalizationEnabled @@ -110,13 +114,11 @@ KCM.SimpleKCM { id: altCharsPopupButton text: i18n("Show overlay when holding a key") description: i18n("Long-pressing a key on a physical keyboard will show an overlay with alternate versions of the selected character, if available") + KeyNavigation.up: autoCapitalizationButton KeyNavigation.down: altCharsHoldDelayButton - checked: kcm.diacriticsPopupEnabled - onCheckedChanged: { - kcm.diacriticsPopupEnabled = checked; - checked = Qt.binding(() => kcm.diacriticsPopupEnabled); - } + checked: kcm.plasmaKeyboardSettings.diacriticsPopupEnabled + onCheckedChanged: kcm.plasmaKeyboardSettings.diacriticsPopupEnabled = checked } Bigscreen.ButtonDelegate { @@ -124,8 +126,9 @@ KCM.SimpleKCM { text: i18nc("How long a key must be held before triggering an action", "Hold delay") description: i18n("How long a key must be held before the overlay shows") enabled: altCharsPopupButton.checked + KeyNavigation.up: altCharsPopupButton trailing: QQC2.Label { - text: i18np("%1 millisecond", "%1 milliseconds", kcm.diacriticsHoldThresholdMs) + text: i18np("%1 millisecond", "%1 milliseconds", kcm.plasmaKeyboardSettings.diacriticsHoldThresholdMs) font.pixelSize: Bigscreen.Units.defaultFontPixelSize bottomPadding: Kirigami.Units.largeSpacing rightPadding: Kirigami.Units.largeSpacing @@ -137,35 +140,30 @@ KCM.SimpleKCM { title: i18nc("How long a key must be held before triggering an action", "Hold delay") standardButtons: Bigscreen.Dialog.Save | Bigscreen.Dialog.Cancel - onOpened: altCharsHoldDelayField.forceActiveFocus() + onOpened: scaleSlider.forceActiveFocus() onClosed: altCharsHoldDelayButton.forceActiveFocus() - onAccepted: kcm.diacriticsHoldThresholdMs = newValue + onAccepted: kcm.plasmaKeyboardSettings.diacriticsHoldThresholdMs = newValue property real newValue contentItem: Bigscreen.ButtonDelegate { - Keys.onRightPressed: { - scaleSlider.increase(); - } - - Keys.onLeftPressed: { - scaleSlider.decrease() - } + Keys.onRightPressed: scaleSlider.increase() + Keys.onLeftPressed: scaleSlider.decrease() KeyNavigation.down: altCharsHoldDelayDialog.footer contentItem: RowLayout { spacing: Kirigami.Units.smallSpacing QQC2.Slider { - Layout.fillWidth: true id: scaleSlider + Layout.fillWidth: true from: 100 to: 1500 stepSize: 100 - value: kcm.diacriticsHoldThresholdMs + value: kcm.plasmaKeyboardSettings.diacriticsHoldThresholdMs snapMode: QQC2.Slider.SnapAlways - onValueChanged: altCharsHoldDelayDialog.newValue = value; + onValueChanged: altCharsHoldDelayDialog.newValue = value } QQC2.Label { @@ -176,12 +174,11 @@ KCM.SimpleKCM { } } } - } - LocaleSelectorSidebar { - id: localeSelectorSidebar - onClosed: changeLanguagesButton.forceActiveFocus() + KeyboardLayoutSelectorSidebar { + id: layoutSelectorSidebar + onClosed: changeLayoutsButton.forceActiveFocus() } } } diff --git a/layouts/CMakeLists.txt b/layouts/CMakeLists.txt new file mode 100644 index 0000000..96094c9 --- /dev/null +++ b/layouts/CMakeLists.txt @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: 2026 Devin Lin +# SPDX-License-Identifier: BSD-2-Clause + +add_subdirectory(defaultplugin) + +plasma_install_package(en org.kde.plasma.keyboard.en keyboard/keyboardpackages) diff --git a/layouts/defaultplugin/CMakeLists.txt b/layouts/defaultplugin/CMakeLists.txt new file mode 100644 index 0000000..7a90713 --- /dev/null +++ b/layouts/defaultplugin/CMakeLists.txt @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: 2026 Devin Lin +# SPDX-License-Identifier: BSD-2-Clause + +ecm_add_qml_module(plasma-keyboard-layouts-defaultplugin + URI org.kde.plasma.keyboard.layouts.defaultplugin + GENERATE_PLUGIN_SOURCE + DEPENDENCIES + QtQuick + QtQuick.Layouts + org.kde.plasma.keyboard + org.kde.plasma.keyboard.virtualkeyboard + org.kde.plasma.keyboard.virtualkeyboard.components +) + +ecm_target_qml_sources(plasma-keyboard-layouts-defaultplugin SOURCES + Dialpad.qml + Digits.qml + Desktop.qml + Dvorak.qml + FullDesktop.qml + Numbers.qml + Qwerty.qml + Symbols.qml +) + +target_link_libraries(plasma-keyboard-layouts-defaultplugin + PRIVATE + Qt::Qml + Qt::Quick +) + +ecm_finalize_qml_module(plasma-keyboard-layouts-defaultplugin) diff --git a/layouts/defaultplugin/Desktop.qml b/layouts/defaultplugin/Desktop.qml new file mode 100644 index 0000000..1e86010 --- /dev/null +++ b/layouts/defaultplugin/Desktop.qml @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import QtQuick.Layouts + +import org.kde.plasma.keyboard.virtualkeyboard +import org.kde.plasma.keyboard.virtualkeyboard.components + +KeyboardLayout { + id: root + + readonly property int rowCount: 4 + readonly property int fullRowWeight: 1300 + property var inputModeKeyModes: [] + readonly property bool inputModeKeyVisible: inputModeKeyModes.length > 0 + property var keyTextMap: ({}) + property var shiftedKeyTextMap: ({}) + function keyText(text) { + const shifted = inputEngine && inputEngine.uppercase; + const map = shifted ? shiftedKeyTextMap : keyTextMap; + return map[text] ?? keyTextMap[text] ?? text; + } + + function keyAlternativeKeys(text, alternativeKeys, numberIndex) { + const mappedText = keyText(text); + if (mappedText === text) { + return alternativeKeys; + } + return alternativeKeys.slice(0, numberIndex) + mappedText + alternativeKeys.slice(numberIndex); + } + + // Keep normal key slots square: 13 key width units across / 4 key height units tall + maxWidthToHeightRatio: (fullRowWeight / defaultKeyWeight) / rowCount + + KeyboardRow { + KeysymKey { key: Qt.Key_Escape; displayText: "Esc"; } + Key { key: Qt.Key_Q; text: root.keyText("q"); alternativeKeys: root.keyAlternativeKeys("q", "q1", 1); smallText: "1"} + Key { key: Qt.Key_W; text: root.keyText("w"); alternativeKeys: root.keyAlternativeKeys("w", "w2", 1); smallText: "2"} + Key { key: Qt.Key_E; text: root.keyText("e"); alternativeKeys: root.keyAlternativeKeys("e", "êe3ëèé", 2); smallText: "3"} + Key { key: Qt.Key_R; text: root.keyText("r"); alternativeKeys: root.keyAlternativeKeys("r", "ŕr4ř", 2); smallText: "4"} + Key { key: Qt.Key_T; text: root.keyText("t"); alternativeKeys: root.keyAlternativeKeys("t", "ţt5ŧť", 2); smallText: "5"} + Key { key: Qt.Key_Y; text: root.keyText("y"); alternativeKeys: root.keyAlternativeKeys("y", "ÿy6ýŷ", 2); smallText: "6"} + Key { key: Qt.Key_U; text: root.keyText("u"); alternativeKeys: root.keyAlternativeKeys("u", "űūũûüu7ùú", 6); smallText: "7"} + Key { key: Qt.Key_I; text: root.keyText("i"); alternativeKeys: root.keyAlternativeKeys("i", "îïīĩi8ìí", 5); smallText: "8"} + Key { key: Qt.Key_O; text: root.keyText("o"); alternativeKeys: root.keyAlternativeKeys("o", "œøõôöòóo9", 8); smallText: "9"} + Key { key: Qt.Key_P; text: root.keyText("p"); alternativeKeys: root.keyAlternativeKeys("p", "p0", 1); smallText: "0"} + BackspaceKey { weight: root.defaultKeyWeight * 2 } + } + + KeyboardRow { + KeysymKey { weight: defaultKeyWeight * 1.5; key: Qt.Key_Tab; displayText: "Tab" } + Key { key: Qt.Key_A; text: root.keyText("a"); alternativeKeys: "aäåãâàá" } + Key { key: Qt.Key_S; text: root.keyText("s"); alternativeKeys: "šsşś" } + Key { key: Qt.Key_D; text: root.keyText("d"); alternativeKeys: "dđď" } + Key { key: Qt.Key_F; text: root.keyText("f") } + Key { key: Qt.Key_G; text: root.keyText("g"); alternativeKeys: "ġgģĝğ" } + Key { key: Qt.Key_H; text: root.keyText("h") } + Key { key: Qt.Key_J; text: root.keyText("j") } + Key { key: Qt.Key_K; text: root.keyText("k") } + Key { key: Qt.Key_L; text: root.keyText("l"); alternativeKeys: "ĺŀłļľl" } + Key { key: Qt.Key_Apostrophe; text: root.keyText("'"); alternativeKeys: "\""; smallText: "\""} + EnterKey { weight: root.defaultKeyWeight * 1.5 } + } + + KeyboardRow { + ShiftKey { weight: root.defaultKeyWeight * 2; sendDirectKeyEvents: true } + Key { key: Qt.Key_Z; text: root.keyText("z"); alternativeKeys: "zžż" } + Key { key: Qt.Key_X; text: root.keyText("x") } + Key { key: Qt.Key_C; text: root.keyText("c"); alternativeKeys: "çcċčć" } + Key { key: Qt.Key_V; text: root.keyText("v") } + Key { key: Qt.Key_B; text: root.keyText("b") } + Key { key: Qt.Key_N; text: root.keyText("n"); alternativeKeys: "ņńnň" } + Key { key: Qt.Key_M; text: root.keyText("m") } + Key { key: Qt.Key_Comma; text: root.keyText(","); alternativeKeys: ";"; smallText: ";"} + Key { key: Qt.Key_Period; text: root.keyText("."); alternativeKeys: ":"; smallText: ":"} + Key { key: Qt.Key_Question; text: root.keyText("?"); alternativeKeys: "!"; smallText: "!"} + ShiftKey { sendDirectKeyEvents: true } + } + + KeyboardRow { + SymbolModeKey { } + KeysymKey { key: Qt.Key_Control; displayText: "Ctrl"; sticky: true } + KeysymKey { key: Qt.Key_Meta; iconName: "start-here-symbolic"; displayText: ""; sticky: true } + KeysymKey { key: Qt.Key_Alt; displayText: "Alt"; sticky: true } + InputModeKey { + visible: root.inputModeKeyVisible + height: visible ? implicitHeight : 0 + weight: visible ? root.defaultKeyWeight : 0 + textComposer: root.textComposer + modes: root.inputModeKeyModes + } + SpaceKey { weight: root.defaultKeyWeight * (root.inputModeKeyVisible ? 4 : 5) } + KeysymKey { key: Qt.Key_Left; iconName: "go-previous-symbolic"; displayText: ""; repeat: true } + KeyboardColumn { + weight: root.defaultKeyWeight + KeysymKey { implicitHeight: -1; key: Qt.Key_Up; iconName: "go-up-symbolic"; displayText: ""; repeat: true } + KeysymKey { implicitHeight: -1; key: Qt.Key_Down; iconName: "go-down-symbolic"; displayText: ""; repeat: true } + } + KeysymKey { key: Qt.Key_Right; iconName: "go-next-symbolic"; displayText: ""; repeat: true } + ChangeLanguageKey { weight: root.defaultKeyWeight / 2 } + HideKeyboardKey { weight: root.defaultKeyWeight / 2 } + } +} diff --git a/layouts/defaultplugin/Dialpad.qml b/layouts/defaultplugin/Dialpad.qml new file mode 100644 index 0000000..b2193d9 --- /dev/null +++ b/layouts/defaultplugin/Dialpad.qml @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import QtQuick.Layouts + +import org.kde.plasma.keyboard.virtualkeyboard +import org.kde.plasma.keyboard.virtualkeyboard.components + +KeyboardLayout { + textComposer: DirectTextComposer {} + maxWidthToHeightRatio: 1 + + KeyboardColumn { + Layout.fillHeight: true + Layout.alignment: Qt.AlignHCenter + KeyboardRow { Key { key: Qt.Key_1; text: "1" } Key { key: Qt.Key_2; text: "2" } Key { key: Qt.Key_3; text: "3" } BackspaceKey {} } + KeyboardRow { Key { key: Qt.Key_4; text: "4" } Key { key: Qt.Key_5; text: "5" } Key { key: Qt.Key_6; text: "6" } Key { text: " "; displayText: "\u2423"; repeat: true; showPreview: false; key: Qt.Key_Space; secondaryStyle: true } } + KeyboardRow { Key { key: Qt.Key_7; text: "7" } Key { key: Qt.Key_8; text: "8" } Key { key: Qt.Key_9; text: "9" } HideKeyboardKey { visible: true } } + KeyboardRow { Key { key: Qt.Key_Asterisk; text: "*"; alternativeKeys: "*+" } Key { key: Qt.Key_0; text: "0" } Key { text: "#"; key: Qt.Key_NumberSign } EnterKey {} } + } +} diff --git a/layouts/defaultplugin/Digits.qml b/layouts/defaultplugin/Digits.qml new file mode 100644 index 0000000..aed984c --- /dev/null +++ b/layouts/defaultplugin/Digits.qml @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import QtQuick.Layouts + +import org.kde.plasma.keyboard.virtualkeyboard +import org.kde.plasma.keyboard.virtualkeyboard.components + +KeyboardLayout { + textComposer: DirectTextComposer {} + maxWidthToHeightRatio: 1 + + KeyboardColumn { + Layout.fillHeight: true + Layout.alignment: Qt.AlignHCenter + KeyboardRow { Key { key: Qt.Key_7; text: "7" } Key { key: Qt.Key_8; text: "8" } Key { key: Qt.Key_9; text: "9" } BackspaceKey {} } + KeyboardRow { Key { key: Qt.Key_4; text: "4" } Key { key: Qt.Key_5; text: "5" } Key { key: Qt.Key_6; text: "6" } Key { text: " "; displayText: "\u2423"; repeat: true; showPreview: false; key: Qt.Key_Space; secondaryStyle: true } } + KeyboardRow { Key { key: Qt.Key_1; text: "1" } Key { key: Qt.Key_2; text: "2" } Key { key: Qt.Key_3; text: "3" } HideKeyboardKey { visible: true } } + KeyboardRow { + ChangeLanguageKey { visible: true } + Key { key: Qt.Key_0; text: "0" } + Key { + key: text === "," ? Qt.Key_Comma : Qt.Key_Period + text: inputEngine ? Qt.locale(inputEngine.locale).decimalPoint : "." + } + EnterKey {} + } + } +} diff --git a/layouts/defaultplugin/Dvorak.qml b/layouts/defaultplugin/Dvorak.qml new file mode 100644 index 0000000..2bf7e2a --- /dev/null +++ b/layouts/defaultplugin/Dvorak.qml @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import QtQuick.Layouts + +import org.kde.plasma.keyboard.virtualkeyboard +import org.kde.plasma.keyboard.virtualkeyboard.components + +KeyboardLayout { + readonly property real functionKeyWeight: defaultKeyWeight * 1.5 + + KeyboardRow { + Key { key: Qt.Key_Apostrophe; text: "'" } + Key { key: Qt.Key_Comma; text: "," } + Key { key: Qt.Key_Period; text: "." } + Key { key: Qt.Key_P; text: "p" } + Key { key: Qt.Key_Y; text: "y" } + Key { key: Qt.Key_F; text: "f" } + Key { key: Qt.Key_G; text: "g" } + Key { key: Qt.Key_C; text: "c" } + Key { key: Qt.Key_R; text: "r" } + Key { key: Qt.Key_L; text: "l" } + } + + KeyboardRow { + Key { key: Qt.Key_A; text: "a" } + Key { key: Qt.Key_O; text: "o" } + Key { key: Qt.Key_E; text: "e" } + Key { key: Qt.Key_U; text: "u" } + Key { key: Qt.Key_I; text: "i" } + Key { key: Qt.Key_D; text: "d" } + Key { key: Qt.Key_H; text: "h" } + Key { key: Qt.Key_T; text: "t" } + Key { key: Qt.Key_N; text: "n" } + Key { key: Qt.Key_S; text: "s" } + } + + KeyboardRow { + ShiftKey { weight: functionKeyWeight } + Key { key: Qt.Key_J; text: "j" } + Key { key: Qt.Key_K; text: "k" } + Key { key: Qt.Key_X; text: "x" } + Key { key: Qt.Key_B; text: "b" } + Key { key: Qt.Key_M; text: "m" } + Key { key: Qt.Key_W; text: "w" } + Key { key: Qt.Key_V; text: "v" } + BackspaceKey { weight: functionKeyWeight } + } + + KeyboardRow { + SymbolModeKey { weight: functionKeyWeight } + ChangeLanguageKey { weight: defaultKeyWeight } + Key { + key: Qt.Key_Q + text: "q" + weight: defaultKeyWeight + } + SpaceKey { weight: 300 } + Key { + key: Qt.Key_Z + text: "z" + weight: defaultKeyWeight + } + HideKeyboardKey { weight: defaultKeyWeight } + EnterKey { weight: functionKeyWeight } + } +} diff --git a/layouts/defaultplugin/FullDesktop.qml b/layouts/defaultplugin/FullDesktop.qml new file mode 100644 index 0000000..2d517c3 --- /dev/null +++ b/layouts/defaultplugin/FullDesktop.qml @@ -0,0 +1,206 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import QtQuick.Layouts + +import org.kde.plasma.keyboard +import org.kde.plasma.keyboard.virtualkeyboard +import org.kde.plasma.keyboard.virtualkeyboard.components + +KeyboardLayout { + id: root + + readonly property int rowCount: 5 + readonly property int fullRowWeight: 1550 + readonly property bool fnActive: inputEngine && inputEngine.pressedKeys.indexOf(KeyCodes.KeyFn) !== -1 + property var inputModeKeyModes: [] + readonly property bool inputModeKeyVisible: inputModeKeyModes.length > 0 + property var keyTextMap: ({}) + property var shiftedKeyTextMap: ({}) + function keyText(text) { + const shifted = inputEngine && inputEngine.uppercase; + const map = shifted ? shiftedKeyTextMap : keyTextMap; + return map[text] ?? keyTextMap[text] ?? text; + } + + // Make panel higher than normal to accomodate 5 rows instead of 4, and the top row is 75% of a typical row height + panelHeightFactor: 1.1875 + + // Keep normal key slots square: 15.5 key-width units across / 5 key-height units tall + maxWidthToHeightRatio: (fullRowWeight / defaultKeyWeight) / rowCount + + KeyboardRow { + heightWeight: defaultRowHeightWeight * 0.75 + + KeysymKey { key: Qt.Key_Escape; displayText: "Esc" } + Key { key: Qt.Key_QuoteLeft; text: "`"; alternativeKeys: "`~"; smallText: "~" } + Key { + key: root.fnActive ? Qt.Key_F1 : Qt.Key_1 + text: root.fnActive ? "" : root.keyText("1") + displayText: root.fnActive ? "F1" : root.keyText("1") + alternativeKeys: root.fnActive ? [] : "1!" + smallText: root.fnActive ? "" : "!" + } + Key { + key: root.fnActive ? Qt.Key_F2 : Qt.Key_2 + text: root.fnActive ? "" : root.keyText("2") + displayText: root.fnActive ? "F2" : root.keyText("2") + alternativeKeys: root.fnActive ? [] : "2@" + smallText: root.fnActive ? "" : "@" + } + Key { + key: root.fnActive ? Qt.Key_F3 : Qt.Key_3 + text: root.fnActive ? "" : root.keyText("3") + displayText: root.fnActive ? "F3" : root.keyText("3") + alternativeKeys: root.fnActive ? [] : "3#" + smallText: root.fnActive ? "" : "#" + } + Key { + key: root.fnActive ? Qt.Key_F4 : Qt.Key_4 + text: root.fnActive ? "" : root.keyText("4") + displayText: root.fnActive ? "F4" : root.keyText("4") + alternativeKeys: root.fnActive ? [] : "4$" + smallText: root.fnActive ? "" : "$" + } + Key { + key: root.fnActive ? Qt.Key_F5 : Qt.Key_5 + text: root.fnActive ? "" : root.keyText("5") + displayText: root.fnActive ? "F5" : root.keyText("5") + alternativeKeys: root.fnActive ? [] : "5%" + smallText: root.fnActive ? "" : "%" + } + Key { + key: root.fnActive ? Qt.Key_F6 : Qt.Key_6 + text: root.fnActive ? "" : root.keyText("6") + displayText: root.fnActive ? "F6" : root.keyText("6") + alternativeKeys: root.fnActive ? [] : "6^" + smallText: root.fnActive ? "" : "^" + } + Key { + key: root.fnActive ? Qt.Key_F7 : Qt.Key_7 + text: root.fnActive ? "" : root.keyText("7") + displayText: root.fnActive ? "F7" : root.keyText("7") + alternativeKeys: root.fnActive ? [] : "7&" + smallText: root.fnActive ? "" : "&" + } + Key { + key: root.fnActive ? Qt.Key_F8 : Qt.Key_8 + text: root.fnActive ? "" : root.keyText("8") + displayText: root.fnActive ? "F8" : root.keyText("8") + alternativeKeys: root.fnActive ? [] : "8*" + smallText: root.fnActive ? "" : "*" + } + Key { + key: root.fnActive ? Qt.Key_F9 : Qt.Key_9 + text: root.fnActive ? "" : root.keyText("9") + displayText: root.fnActive ? "F9" : root.keyText("9") + alternativeKeys: root.fnActive ? [] : "9(" + smallText: root.fnActive ? "" : "(" + } + Key { + key: root.fnActive ? Qt.Key_F10 : Qt.Key_0 + text: root.fnActive ? "" : root.keyText("0") + displayText: root.fnActive ? "F10" : root.keyText("0") + alternativeKeys: root.fnActive ? [] : "0)" + smallText: root.fnActive ? "" : ")" + } + Key { + key: root.fnActive ? Qt.Key_F11 : Qt.Key_Minus + text: root.fnActive ? "" : root.keyText("-") + displayText: root.fnActive ? "F11" : root.keyText("-") + alternativeKeys: root.fnActive ? [] : "-_" + smallText: root.fnActive ? "" : "_" + } + Key { + key: root.fnActive ? Qt.Key_F12 : Qt.Key_Equal + text: root.fnActive ? "" : root.keyText("=") + displayText: root.fnActive ? "F12" : root.keyText("=") + alternativeKeys: root.fnActive ? [] : "=+" + smallText: root.fnActive ? "" : "+" + } + BackspaceKey { weight: root.defaultKeyWeight * 1.5 } + } + + KeyboardRow { + KeysymKey { key: Qt.Key_Tab; displayText: "Tab"; weight: root.defaultKeyWeight * 1.5 } + Key { key: Qt.Key_Q; text: root.keyText("q") } + Key { key: Qt.Key_W; text: root.keyText("w") } + Key { key: Qt.Key_E; text: root.keyText("e") } + Key { key: Qt.Key_R; text: root.keyText("r") } + Key { key: Qt.Key_T; text: root.keyText("t") } + Key { key: Qt.Key_Y; text: root.keyText("y") } + Key { key: Qt.Key_U; text: root.keyText("u") } + Key { key: Qt.Key_I; text: root.keyText("i") } + Key { key: Qt.Key_O; text: root.keyText("o") } + Key { key: Qt.Key_P; text: root.keyText("p") } + Key { key: Qt.Key_BracketLeft; text: "["; alternativeKeys: "[{"; smallText: "{" } + Key { key: Qt.Key_BracketRight; text: "]"; alternativeKeys: "]}"; smallText: "}" } + Key { key: Qt.Key_Backslash; text: "\\"; alternativeKeys: "\\|"; smallText: "|" } + KeysymKey { key: Qt.Key_Delete; displayText: "Del" } + } + + KeyboardRow { + KeysymKey { + key: Qt.Key_CapsLock + displayText: "Caps" + weight: root.defaultKeyWeight * 1.75 + highlighted: inputEngine && inputEngine.capsLockActive + onClicked: { + if (!inputEngine) { + return; + } + inputEngine.capsLockActive = !inputEngine.capsLockActive; + inputEngine.shiftActive = false; + } + } + Key { key: Qt.Key_A; text: root.keyText("a") } + Key { key: Qt.Key_S; text: root.keyText("s") } + Key { key: Qt.Key_D; text: root.keyText("d") } + Key { key: Qt.Key_F; text: root.keyText("f") } + Key { key: Qt.Key_G; text: root.keyText("g") } + Key { key: Qt.Key_H; text: root.keyText("h") } + Key { key: Qt.Key_J; text: root.keyText("j") } + Key { key: Qt.Key_K; text: root.keyText("k") } + Key { key: Qt.Key_L; text: root.keyText("l") } + Key { key: Qt.Key_Semicolon; text: root.keyText(";"); alternativeKeys: ";:"; smallText: ":" } + Key { key: Qt.Key_Apostrophe; text: root.keyText("'"); alternativeKeys: "'\""; smallText: "\"" } + EnterKey { weight: root.defaultKeyWeight * 2.75 } + } + + KeyboardRow { + ShiftKey { weight: root.defaultKeyWeight * 2.5; sendDirectKeyEvents: true } + Key { key: Qt.Key_Z; text: root.keyText("z") } + Key { key: Qt.Key_X; text: root.keyText("x") } + Key { key: Qt.Key_C; text: root.keyText("c") } + Key { key: Qt.Key_V; text: root.keyText("v") } + Key { key: Qt.Key_B; text: root.keyText("b") } + Key { key: Qt.Key_N; text: root.keyText("n") } + Key { key: Qt.Key_M; text: root.keyText("m") } + Key { key: Qt.Key_Comma; text: root.keyText(","); alternativeKeys: ",<"; smallText: "<" } + Key { key: Qt.Key_Period; text: root.keyText("."); alternativeKeys: ".>"; smallText: ">" } + Key { key: Qt.Key_Slash; text: root.keyText("/"); alternativeKeys: "/?"; smallText: "?" } + KeysymKey { key: Qt.Key_Up; iconName: "go-up-symbolic"; displayText: ""; repeat: true } + ShiftKey { weight: root.defaultKeyWeight * 2; sendDirectKeyEvents: true } + } + + KeyboardRow { + KeysymKey { key: Qt.Key_Control; displayText: "Ctrl"; sticky: true } + KeysymKey { key: KeyCodes.KeyFn; displayText: "Fn"; sticky: true } + KeysymKey { key: Qt.Key_Meta; iconName: "start-here-symbolic"; displayText: ""; sticky: true } + KeysymKey { key: Qt.Key_Alt; displayText: "Alt"; sticky: true } + InputModeKey { + visible: root.inputModeKeyVisible + height: visible ? implicitHeight : 0 + weight: visible ? root.defaultKeyWeight : 0 + textComposer: root.textComposer + modes: root.inputModeKeyModes + } + SpaceKey { weight: root.defaultKeyWeight * (root.inputModeKeyVisible ? 6.5 : 7.5) } + KeysymKey { key: Qt.Key_Left; iconName: "go-previous-symbolic"; displayText: ""; repeat: true } + KeysymKey { key: Qt.Key_Down; iconName: "go-down-symbolic"; displayText: ""; repeat: true } + KeysymKey { key: Qt.Key_Right; iconName: "go-next-symbolic"; displayText: ""; repeat: true } + ChangeLanguageKey { weight: root.defaultKeyWeight / 2 } + HideKeyboardKey { weight: root.defaultKeyWeight / 2 } + } +} diff --git a/layouts/defaultplugin/Numbers.qml b/layouts/defaultplugin/Numbers.qml new file mode 100644 index 0000000..8add9ec --- /dev/null +++ b/layouts/defaultplugin/Numbers.qml @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import QtQuick.Layouts + +import org.kde.plasma.keyboard.virtualkeyboard +import org.kde.plasma.keyboard.virtualkeyboard.components + +KeyboardLayout { + textComposer: DirectTextComposer {} + maxWidthToHeightRatio: 15 / 8 + + KeyboardRow { + KeyboardColumn { + weight: 300 + KeyboardRow { Key { key: Qt.Key_ParenLeft; text: "(" } Key { key: Qt.Key_ParenRight; text: ")" } Key { key: Qt.Key_Comma; text: "," } } + KeyboardRow { Key { key: Qt.Key_division; text: "\u00F7" } Key { key: Qt.Key_multiply; text: "\u00D7" } Key { key: Qt.Key_Plus; text: "+" } } + KeyboardRow { Key { key: Qt.Key_AsciiCircum; text: "^" } Key { key: Qt.Key_Slash; text: "/" } Key { key: Qt.Key_Minus; text: "-" } } + KeyboardRow { Key { key: 0x221A; text: "√" } Key { key: Qt.Key_Percent; text: "%" } Key { key: Qt.Key_Asterisk; text: "*" } } + } + KeyboardColumn { + weight: 50 + KeyboardRow { FillerKey {} } + } + KeyboardColumn { + weight: 400 + KeyboardRow { Key { key: Qt.Key_7; text: "7" } Key { key: Qt.Key_8; text: "8" } Key { key: Qt.Key_9; text: "9" } BackspaceKey {} } + KeyboardRow { Key { key: Qt.Key_4; text: "4" } Key { key: Qt.Key_5; text: "5" } Key { key: Qt.Key_6; text: "6" } Key { text: " "; displayText: "\u2423"; repeat: true; showPreview: false; key: Qt.Key_Space; secondaryStyle: true } } + KeyboardRow { Key { key: Qt.Key_1; text: "1" } Key { key: Qt.Key_2; text: "2" } Key { key: Qt.Key_3; text: "3" } HideKeyboardKey { visible: true } } + KeyboardRow { + ChangeLanguageKey { visible: true } + Key { key: Qt.Key_0; text: "0" } + Key { key: Qt.Key_Period; text: "."; alternativeKeys: "., " } + EnterKey {} + } + } + } +} diff --git a/layouts/defaultplugin/Qwerty.qml b/layouts/defaultplugin/Qwerty.qml new file mode 100644 index 0000000..19af7af --- /dev/null +++ b/layouts/defaultplugin/Qwerty.qml @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import QtQuick.Layouts + +import org.kde.plasma.keyboard.virtualkeyboard +import org.kde.plasma.keyboard.virtualkeyboard.components + +KeyboardLayout { + KeyboardRow { + Key { key: Qt.Key_Q; text: "q"; alternativeKeys: "q1"; smallText: "1"} + Key { key: Qt.Key_W; text: "w"; alternativeKeys: "w2"; smallText: "2"} + Key { key: Qt.Key_E; text: "e"; alternativeKeys: "êe3ëèé"; smallText: "3"} + Key { key: Qt.Key_R; text: "r"; alternativeKeys: "ŕr4ř"; smallText: "4"} + Key { key: Qt.Key_T; text: "t"; alternativeKeys: "ţt5ŧť"; smallText: "5"} + Key { key: Qt.Key_Y; text: "y"; alternativeKeys: "ÿy6ýŷ"; smallText: "6"} + Key { key: Qt.Key_U; text: "u"; alternativeKeys: "űūũûüu7ùú"; smallText: "7"} + Key { key: Qt.Key_I; text: "i"; alternativeKeys: "îïīĩi8ìí"; smallText: "8"} + Key { key: Qt.Key_O; text: "o"; alternativeKeys: "œøõôöòóo9"; smallText: "9"} + Key { key: Qt.Key_P; text: "p"; alternativeKeys: "p0"; smallText: "0"} + } + KeyboardRow { + FillerKey { weight: defaultKeyWeight / 2 } + Key { key: Qt.Key_A; text: "a"; alternativeKeys: "aäåãâàá" } + Key { key: Qt.Key_S; text: "s"; alternativeKeys: "šsşś" } + Key { key: Qt.Key_D; text: "d"; alternativeKeys: "dđď" } + Key { key: Qt.Key_F; text: "f" } + Key { key: Qt.Key_G; text: "g"; alternativeKeys: "ġgģĝğ" } + Key { key: Qt.Key_H; text: "h" } + Key { key: Qt.Key_J; text: "j" } + Key { key: Qt.Key_K; text: "k" } + Key { key: Qt.Key_L; text: "l"; alternativeKeys: "ĺŀłļľl" } + FillerKey { weight: defaultKeyWeight / 2 } + } + KeyboardRow { + ShiftKey { weight: 150 } + Key { key: Qt.Key_Z; text: "z"; alternativeKeys: "zžż" } + Key { key: Qt.Key_X; text: "x" } + Key { key: Qt.Key_C; text: "c"; alternativeKeys: "çcċčć" } + Key { key: Qt.Key_V; text: "v" } + Key { key: Qt.Key_B; text: "b" } + Key { key: Qt.Key_N; text: "n"; alternativeKeys: "ņńnň" } + Key { key: Qt.Key_M; text: "m" } + BackspaceKey { weight: 150 } + } + KeyboardRow { + SymbolModeKey { weight: 150 } + ChangeLanguageKey {} + Key { key: Qt.Key_Comma; text: ","; secondaryStyle: true } + SpaceKey { weight: 300 } + Key { key: Qt.Key_Period; text: "."; alternativeKeys: "!.?"; smallText: "!?"; secondaryStyle: true } + HideKeyboardKey {} + EnterKey { weight: 150 } + } +} diff --git a/layouts/defaultplugin/Symbols.qml b/layouts/defaultplugin/Symbols.qml new file mode 100644 index 0000000..a1842ab --- /dev/null +++ b/layouts/defaultplugin/Symbols.qml @@ -0,0 +1,120 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import QtQuick.Layouts + +import org.kde.plasma.keyboard.virtualkeyboard +import org.kde.plasma.keyboard.virtualkeyboard.components + +KeyboardLayoutLoader { + property bool secondPage + onVisibleChanged: if (!visible) secondPage = false + sourceComponent: secondPage ? page2 : page1 + + Component { + id: page1 + KeyboardLayout { + textComposer: DirectTextComposer {} + readonly property real functionKeyWeight: defaultKeyWeight * 1.5 + KeyboardRow { + Key { key: Qt.Key_1; text: "1" } + Key { key: Qt.Key_2; text: "2" } + Key { key: Qt.Key_3; text: "3" } + Key { key: Qt.Key_4; text: "4" } + Key { key: Qt.Key_5; text: "5" } + Key { key: Qt.Key_6; text: "6" } + Key { key: Qt.Key_7; text: "7" } + Key { key: Qt.Key_8; text: "8" } + Key { key: Qt.Key_9; text: "9" } + Key { key: Qt.Key_0; text: "0" } + } + KeyboardRow { + Key { key: Qt.Key_At; text: "@" } + Key { key: Qt.Key_NumberSign; text: "#" } + Key { key: Qt.Key_Percent; text: "%" } + Key { key: Qt.Key_Ampersand; text: "&" } + Key { key: Qt.Key_Asterisk; text: "*" } + Key { key: Qt.Key_Underscore; text: "_" } + Key { key: Qt.Key_Minus; text: "-" } + Key { key: Qt.Key_Plus; text: "+" } + Key { key: Qt.Key_ParenLeft; text: "(" } + Key { key: Qt.Key_ParenRight; text: ")" } + } + KeyboardRow { + Key { displayText: "1/2"; functionKey: true; noKeyEvent: true; onClicked: secondPage = !secondPage; secondaryStyle: true } + Key { key: Qt.Key_QuoteDbl; text: "\"" } + Key { key: Qt.Key_Less; text: "<" } + Key { key: Qt.Key_Greater; text: ">" } + Key { key: Qt.Key_Apostrophe; text: "'" } + Key { key: Qt.Key_Colon; text: ":" } + Key { key: Qt.Key_Slash; text: "/" } + Key { key: Qt.Key_Exclam; text: "!" } + Key { key: Qt.Key_Question; text: "?" } + BackspaceKey {} + } + KeyboardRow { + SymbolModeKey { weight: functionKeyWeight; displayText: "ABC" } + ChangeLanguageKey { weight: defaultKeyWeight } + Key { key: Qt.Key_Comma; weight: defaultKeyWeight; text: ","; secondaryStyle: true } + SpaceKey { weight: defaultKeyWeight * 3 } + Key { key: Qt.Key_Period; weight: defaultKeyWeight; text: "."; secondaryStyle: true } + HideKeyboardKey { weight: defaultKeyWeight } + EnterKey { weight: functionKeyWeight } + } + } + } + + Component { + id: page2 + KeyboardLayout { + textComposer: DirectTextComposer {} + readonly property real functionKeyWeight: defaultKeyWeight * 1.5 + KeyboardRow { + Key { key: Qt.Key_AsciiTilde; text: "~" } + Key { key: Qt.Key_Agrave; text: "`" } + Key { key: Qt.Key_Bar; text: "|" } + Key { key: 0x7B; text: "·" } + Key { key: 0x221A; text: "√" } + Key { key: Qt.Key_division; text: "÷" } + Key { key: Qt.Key_multiply; text: "×" } + Key { key: Qt.Key_onehalf; text: "½"; alternativeKeys: "¼⅓½¾⅞" } + Key { key: Qt.Key_BraceLeft; text: "{" } + Key { key: Qt.Key_BraceRight; text: "}" } + } + KeyboardRow { + Key { key: Qt.Key_Dollar; text: "$" } + Key { key: 0x20AC; text: "€" } + Key { key: 0xC2; text: "£" } + Key { key: 0xA2; text: "¢" } + Key { key: 0xA5; text: "¥" } + Key { key: Qt.Key_AsciiCircum; text: "^" } + Key { key: Qt.Key_Equal; text: "=" } + Key { key: Qt.Key_section; text: "§" } + Key { key: Qt.Key_BracketLeft; text: "[" } + Key { key: Qt.Key_BracketRight; text: "]" } + } + KeyboardRow { + Key { displayText: "2/2"; functionKey: true; noKeyEvent: true; onClicked: secondPage = !secondPage; secondaryStyle: true } + Key { key: 0x2122; text: "™" } + Key { key: 0x00AE; text: "®" } + Key { key: Qt.Key_guillemotleft; text: "«" } + Key { key: Qt.Key_guillemotright; text: "»" } + Key { key: Qt.Key_semicolon; text: ";" } + Key { key: 0x201C; text: "“" } + Key { key: 0x201D; text: "”" } + Key { key: Qt.Key_Backslash; text: "\\" } + BackspaceKey {} + } + KeyboardRow { + SymbolModeKey { weight: functionKeyWeight; displayText: "ABC" } + ChangeLanguageKey { weight: defaultKeyWeight } + Key { key: Qt.Key_Comma; weight: defaultKeyWeight; text: ","; secondaryStyle: true } + SpaceKey { weight: defaultKeyWeight * 3 } + Key { key: 0x2026; weight: defaultKeyWeight; text: "\u2026"; secondaryStyle: true } + HideKeyboardKey { weight: defaultKeyWeight } + EnterKey { weight: functionKeyWeight } + } + } + } +} diff --git a/layouts/en/contents/layouts/DesktopQwerty.qml b/layouts/en/contents/layouts/DesktopQwerty.qml new file mode 100644 index 0000000..9f5010d --- /dev/null +++ b/layouts/en/contents/layouts/DesktopQwerty.qml @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import org.kde.plasma.keyboard.layouts.defaultplugin as SharedLayouts + +SharedLayouts.Desktop {} diff --git a/layouts/en/contents/layouts/FullQwerty.qml b/layouts/en/contents/layouts/FullQwerty.qml new file mode 100644 index 0000000..c39c03c --- /dev/null +++ b/layouts/en/contents/layouts/FullQwerty.qml @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import org.kde.plasma.keyboard.layouts.defaultplugin as SharedLayouts + +SharedLayouts.FullDesktop {} diff --git a/layouts/en/contents/layouts/MobileDvorak.qml b/layouts/en/contents/layouts/MobileDvorak.qml new file mode 100644 index 0000000..2857c0f --- /dev/null +++ b/layouts/en/contents/layouts/MobileDvorak.qml @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import org.kde.plasma.keyboard.layouts.defaultplugin as SharedLayouts + +SharedLayouts.Dvorak {} diff --git a/layouts/en/contents/layouts/MobileQwerty.qml b/layouts/en/contents/layouts/MobileQwerty.qml new file mode 100644 index 0000000..0ecaffc --- /dev/null +++ b/layouts/en/contents/layouts/MobileQwerty.qml @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import org.kde.plasma.keyboard.layouts.defaultplugin as SharedLayouts + +SharedLayouts.Qwerty {} diff --git a/layouts/en/contents/layouts/shared/Dialpad.qml b/layouts/en/contents/layouts/shared/Dialpad.qml new file mode 100644 index 0000000..d9a6b90 --- /dev/null +++ b/layouts/en/contents/layouts/shared/Dialpad.qml @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import org.kde.plasma.keyboard.layouts.defaultplugin as SharedLayouts + +SharedLayouts.Dialpad {} diff --git a/layouts/en/contents/layouts/shared/Digits.qml b/layouts/en/contents/layouts/shared/Digits.qml new file mode 100644 index 0000000..7f99c0d --- /dev/null +++ b/layouts/en/contents/layouts/shared/Digits.qml @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import org.kde.plasma.keyboard.layouts.defaultplugin as SharedLayouts + +SharedLayouts.Digits {} diff --git a/layouts/en/contents/layouts/shared/Numbers.qml b/layouts/en/contents/layouts/shared/Numbers.qml new file mode 100644 index 0000000..8b664c2 --- /dev/null +++ b/layouts/en/contents/layouts/shared/Numbers.qml @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import org.kde.plasma.keyboard.layouts.defaultplugin as SharedLayouts + +SharedLayouts.Numbers {} diff --git a/layouts/en/contents/layouts/shared/Symbols.qml b/layouts/en/contents/layouts/shared/Symbols.qml new file mode 100644 index 0000000..8b09d36 --- /dev/null +++ b/layouts/en/contents/layouts/shared/Symbols.qml @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import org.kde.plasma.keyboard.layouts.defaultplugin as SharedLayouts + +SharedLayouts.Symbols {} diff --git a/layouts/en/metadata.json b/layouts/en/metadata.json new file mode 100644 index 0000000..acee1ab --- /dev/null +++ b/layouts/en/metadata.json @@ -0,0 +1,74 @@ +{ + "KPlugin": { + "Id": "org.kde.plasma.keyboard.en", + "Name": "English" + }, + "X-Plasma-Keyboard": { + "Locales": [ + "en_US", + "en_GB" + ], + "KeyboardLayouts": [ + { + "Id": "mobile-qwerty", + "Name": "QWERTY", + "Files": { + "main": "MobileQwerty.qml", + "symbols": "shared/Symbols.qml", + "digits": "shared/Digits.qml", + "numbers": "shared/Numbers.qml", + "dialpad": "shared/Dialpad.qml" + }, + "FormFactors": [ + "phone", + "mediacenter", + "desktop" + ] + }, + { + "Id": "desktop-qwerty", + "Name": "QWERTY (Desktop)", + "Files": { + "main": "DesktopQwerty.qml", + "symbols": "shared/Symbols.qml", + "digits": "shared/Digits.qml", + "numbers": "shared/Numbers.qml", + "dialpad": "shared/Dialpad.qml" + }, + "FormFactors": [ + "desktop" + ] + }, + { + "Id": "desktop-full-qwerty", + "Name": "QWERTY (Full Desktop)", + "Files": { + "main": "FullQwerty.qml", + "symbols": "shared/Symbols.qml", + "digits": "shared/Digits.qml", + "numbers": "shared/Numbers.qml", + "dialpad": "shared/Dialpad.qml" + }, + "FormFactors": [ + "desktop" + ] + }, + { + "Id": "mobile-dvorak", + "Name": "Dvorak", + "Files": { + "main": "MobileDvorak.qml", + "symbols": "shared/Symbols.qml", + "digits": "shared/Digits.qml", + "numbers": "shared/Numbers.qml", + "dialpad": "shared/Dialpad.qml" + }, + "FormFactors": [ + "phone", + "mediacenter", + "desktop" + ] + } + ] + } +} diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 8114b89..1f31214 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -8,23 +8,37 @@ configure_file(config-plasma-keyboard.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config add_executable(plasma-keyboard) +if (Qt6_VERSION VERSION_GREATER_EQUAL "6.8.0") + set(private_code_option PRIVATE_CODE) +endif() + ecm_add_qtwayland_client_protocol(plasma-keyboard PROTOCOL ${WaylandProtocols_DATADIR}/unstable/input-method/input-method-unstable-v1.xml BASENAME input-method-unstable-v1) ecm_add_qtwayland_client_protocol(plasma-keyboard PROTOCOL ${WaylandProtocols_DATADIR}/unstable/text-input/text-input-unstable-v1.xml BASENAME text-input-unstable-v1) ecm_add_qtwayland_client_protocol(plasma-keyboard PROTOCOL "${Wayland_DATADIR}/wayland.xml" BASENAME wayland) +qt6_generate_wayland_protocol_client_sources(plasma-keyboard FILES ${PLASMA_WAYLAND_PROTOCOLS_DIR}/fake-input.xml ${private_code_option}) target_sources(plasma-keyboard PRIVATE + feedback.cpp + feedback.h + keycodes.h + kwinfakeinput.cpp + kwinfakeinput.h main.cpp inputpanelintegration.cpp inputpanelintegration.h inputpanelrole.h - inputlisteneritem.cpp - inputlisteneritem.h + inputmethodconnection.cpp + inputmethodconnection.h + inputmethodhints.cpp + inputmethodhints.h inputmethod.cpp inputmethod_p.h inputpanelwindow.cpp inputpanelwindow.h inputplugin.cpp inputplugin.h + vkbdwaylandinputbackend.cpp + vkbdwaylandinputbackend.h qwaylandinputpanelshellintegration.cpp qwaylandinputpanelshellintegration_p.h qwaylandinputpanelsurface.cpp @@ -52,14 +66,12 @@ if(PLASMA_KEYBOARD_VIBRATION_ENABLED) dbus/org.sigxcpu.Feedback.Haptic.xml) target_sources(plasma-keyboard PRIVATE - vibration.cpp - vibration.h vibrationevent.h ${dbusinterface_SRCS} ) endif() -if(PLASMA_KEYBOARD_SOUND_ENABLED) +if(PLASMA_KEYBOARD_SOUNDS_ENABLED) target_sources(plasma-keyboard PRIVATE soundresources.qrc ) @@ -82,8 +94,7 @@ ecm_add_qml_module(plasma-keyboard ecm_target_qml_sources(plasma-keyboard SOURCES qml/main.qml - qml/LanguagePopup.qml - qml/LanguagePopupDelegate.qml + qml/KeyboardPanel.qml qml/DiacriticsOverlay.qml qml/OverlayWindow.qml ) @@ -111,19 +122,22 @@ target_link_libraries(plasma-keyboard Qt::DBus Qt::Gui Qt::GuiPrivate - Qt::VirtualKeyboard Qt::WaylandClient Qt::WaylandClientPrivate Wayland::Client + plasma-keyboard-virtualkeyboard + plasma-keyboard-virtualkeyboardplugin ) +qt6_import_qml_plugins(plasma-keyboard) + +if(PLASMA_KEYBOARD_SOUNDS_ENABLED) + target_link_libraries(plasma-keyboard PRIVATE Qt::Multimedia) +endif() + install(TARGETS plasma-keyboard ${KDE_INSTALL_TARGETS_DEFAULT_ARGS}) install(PROGRAMS org.kde.plasma.keyboard.desktop DESTINATION ${KDE_INSTALL_APPDIR}) -add_subdirectory(styles) -add_subdirectory(qmlplugin) - -install(DIRECTORY layouts DESTINATION ${CMAKE_INSTALL_PREFIX}/share/plasma/keyboard) install(DIRECTORY overlay/diacritics DESTINATION ${CMAKE_INSTALL_PREFIX}/share/plasma/keyboard) install(FILES plasmakeyboardsettings.kcfg DESTINATION ${KDE_INSTALL_KCFGDIR}) diff --git a/src/config-plasma-keyboard.h.cmake b/src/config-plasma-keyboard.h.cmake index f2fe5d1..907e7d3 100644 --- a/src/config-plasma-keyboard.h.cmake +++ b/src/config-plasma-keyboard.h.cmake @@ -6,5 +6,5 @@ #pragma once -#cmakedefine01 PLASMA_KEYBOARD_SOUND_ENABLED +#cmakedefine01 PLASMA_KEYBOARD_SOUNDS_ENABLED #cmakedefine01 PLASMA_KEYBOARD_VIBRATION_ENABLED diff --git a/src/feedback.cpp b/src/feedback.cpp new file mode 100644 index 0000000..ddc1e1a --- /dev/null +++ b/src/feedback.cpp @@ -0,0 +1,73 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "feedback.h" + +#include "config-plasma-keyboard.h" +#include "plasmakeyboardsettings.h" + +#include +#include +#include + +using namespace Qt::StringLiterals; + +Feedback::Feedback(QObject *parent) + : QObject(parent) +{ +#if PLASMA_KEYBOARD_VIBRATION_ENABLED + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); +#endif + +#if PLASMA_KEYBOARD_SOUNDS_ENABLED + m_soundEffect.setSource(QUrl(u"qrc:/sounds/keyboard_tick2_quiet.wav"_s)); + m_soundEffect.setVolume(0.6F); +#endif +} + +void Feedback::play(Event event) +{ +#if PLASMA_KEYBOARD_SOUNDS_ENABLED + if (PlasmaKeyboardSettings::soundEnabled()) { + playSound(); + } +#else + Q_UNUSED(event) +#endif + +#if PLASMA_KEYBOARD_VIBRATION_ENABLED + if (PlasmaKeyboardSettings::vibrationEnabled()) { + playVibration(event); + } +#endif +} + +#if PLASMA_KEYBOARD_SOUNDS_ENABLED +void Feedback::playSound() +{ + m_soundEffect.stop(); + m_soundEffect.play(); +} +#endif + +#if PLASMA_KEYBOARD_VIBRATION_ENABLED +void Feedback::playVibration(Event event) +{ + if (!m_hapticInterface) { + m_hapticInterface = new OrgSigxcpuFeedbackHapticInterface(u"org.sigxcpu.Feedback"_s, u"/org/sigxcpu/Feedback"_s, QDBusConnection::sessionBus(), this); + } + + int durationMs = PlasmaKeyboardSettings::vibrationMs(); + if (event == SelectionChange) { + durationMs = qMax(1, durationMs / 2); + } + + const VibrationEvent vibrationEvent{1.0, static_cast(durationMs)}; + const VibrationEventList pattern = {vibrationEvent}; + m_hapticInterface->Vibrate(u"org.kde.plasma.keyboard"_s, pattern); +} +#endif diff --git a/src/feedback.h b/src/feedback.h new file mode 100644 index 0000000..59c63db --- /dev/null +++ b/src/feedback.h @@ -0,0 +1,54 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include "config-plasma-keyboard.h" + +#include +#include + +#if PLASMA_KEYBOARD_SOUNDS_ENABLED +#include +#endif + +#if PLASMA_KEYBOARD_VIBRATION_ENABLED +#include "hapticinterface.h" +#include "vibrationevent.h" +#endif + +/** + * Plays the configured sound and haptic feedback for keyboard interactions. + */ +class Feedback : public QObject +{ + Q_OBJECT + QML_ELEMENT + QML_SINGLETON + +public: + enum Event { + Press, + SelectionChange, + SelectionCommit, + }; + Q_ENUM(Event) + + explicit Feedback(QObject *parent = nullptr); + + Q_INVOKABLE void play(Event event = Press); + +private: +#if PLASMA_KEYBOARD_SOUNDS_ENABLED + void playSound(); + QSoundEffect m_soundEffect; +#endif + +#if PLASMA_KEYBOARD_VIBRATION_ENABLED + void playVibration(Event event); + OrgSigxcpuFeedbackHapticInterface *m_hapticInterface = nullptr; +#endif +}; diff --git a/src/inputlisteneritem.cpp b/src/inputlisteneritem.cpp deleted file mode 100644 index ca6bb6a..0000000 --- a/src/inputlisteneritem.cpp +++ /dev/null @@ -1,432 +0,0 @@ -/* - SPDX-FileCopyrightText: 2024 Aleix Pol i Gonzalez - SPDX-FileCopyrightText: 2025 Devin Lin - SPDX-FileCopyrightText: 2026 Kristen McWilliam - - SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL -*/ - -#include "inputlisteneritem.h" -#include "inputmethod_p.h" -#include "logging.h" -#include "plasmakeyboardsettings.h" - -#include "overlay/longpresstrigger.h" -#include "overlay/overlaycontroller.h" -#include "overlay/prefixquerytrigger.h" -#include "overlay/textexpansiontrigger.h" - -#include -#include - -#include - -#include -#include - -Q_GLOBAL_STATIC(InputMethod, s_im) - -Q_GLOBAL_STATIC_WITH_ARGS(const std::set, - IGNORED_KEYS, - { - Qt::Key_Context1 // Triggered by "special keys" button - }); -// Keys to always capture for keyboard navigation -QList initCapture() -{ - return { - Qt::Key_Left, - Qt::Key_Right, - Qt::Key_Up, - Qt::Key_Down, - }; -} -Q_GLOBAL_STATIC_WITH_ARGS(const QList, KEYBOARD_NAVIGATION_CAPTURE_KEYS, (initCapture())); - -// Keys to capture when keyboard navigation is active -Q_GLOBAL_STATIC_WITH_ARGS(const QList, KEYBOARD_NAVIGATION_ACTIVE_CAPTURE_KEYS, (initCapture() + QList{Qt::Key_Return})); - -InputListenerItem::InputListenerItem() - : m_input(&(*s_im)) - , m_overlayController(new OverlayController(&m_input, this)) -{ - // Grab and listen to physical keyboard input - m_input.setGrabbing(true); - - // Register overlay triggers - m_overlayController->registerTrigger(new LongPressTrigger(m_overlayController)); - m_overlayController->registerTrigger(new PrefixQueryTrigger(m_overlayController)); - m_overlayController->registerTrigger(new TextExpansionTrigger(m_overlayController)); - - connect(&m_input, &InputPlugin::contextChanged, this, [this] { - const bool hasContext = m_input.hasContext(); - - // Cancel any pending overlay state when the input context changes (focus loss or target swap) - if (m_overlayController) { - m_overlayController->cancelOverlay(); - } - - if (hasContext) { - QGuiApplication::inputMethod()->update(Qt::ImQueryAll); - QGuiApplication::inputMethod()->show(); - } else { - QGuiApplication::inputMethod()->setVisible(false); - } - }); - connect(&m_input, &InputPlugin::surroundingTextChanged, this, [this] { - // Notify the overlay controller first so it can cancel the overlay if an - // external cursor movement is detected (e.g. user tapped elsewhere in the - // text field while the diacritics overlay was open or the hold timer was - // still running). The controller uses an internal counter to distinguish - // its own commit_string echoes from external cursor moves. - if (m_overlayController) { - m_overlayController->handleSurroundingTextChanged(); - } - - if (m_input.hasContext()) { - // Re-activate when text input activates, and there is context - if (!window()->isVisible()) { - QGuiApplication::inputMethod()->setVisible(true); - } - - // Update vkbd input method only if the virtual keyboard panel is shown - if (window()->isExposed()) { - QGuiApplication::inputMethod()->update(Qt::ImSurroundingText); - } - } - }); - connect(&m_input, &InputPlugin::deactivate, this, [this] { - QGuiApplication::inputMethod()->setVisible(false); - QGuiApplication::inputMethod()->reset(); - }); - connect(&m_input, &InputPlugin::resetRequested, this, [] { - QGuiApplication::inputMethod()->reset(); - }); - connect(QGuiApplication::inputMethod(), &QInputMethod::visibleChanged, this, [this] { - window()->setVisible(QGuiApplication::inputMethod()->isVisible()); - }); - - connect(&m_input, &InputPlugin::keyPressed, this, [this](QKeyEvent *keyEvent) { - // qCDebug(PlasmaKeyboard) << "keyPressed. keycode:" << keyEvent->key() << "text:" << keyEvent->text() << "modifiers:" << keyEvent->modifiers(); - - // Delegate to overlay controller for diacritics/emoji/text expansion - if (m_overlayController && m_overlayController->processKeyPress(keyEvent)) { - keyEvent->accept(); - return; - } - // The window can have isVisible() = true, but not be shown by the compositor if the input panel is suppressed - if (!window()->isExposed()) { - return; - } - - if (PlasmaKeyboardSettings::self()->keyboardNavigationEnabled()) { - // Keys to capture for keyboard navigation - const auto keys = m_keyboardNavigationActive ? *KEYBOARD_NAVIGATION_ACTIVE_CAPTURE_KEYS : *KEYBOARD_NAVIGATION_CAPTURE_KEYS; - - // Forward and accept keyboard navigation events - for (const auto key : keys) { - if (keyEvent->key() == key) { - keyEvent->accept(); - Q_EMIT keyNavigationPressed(key); - break; - } - } - } - }); - connect(&m_input, &InputPlugin::keyReleased, this, [this](QKeyEvent *keyEvent) { - // qCDebug(PlasmaKeyboard) << "keyReleased. keycode:" << keyEvent->key() << "text:" << keyEvent->text(); - - // Let the overlay controller handle release events (e.g. diacritics, emoji) - if (m_overlayController && m_overlayController->processKeyRelease(keyEvent)) { - keyEvent->accept(); - return; - } - // The window can have isVisible() = true, but not be shown by the compositor if the input panel is suppressed - if (!window()->isExposed()) { - return; - } - - if (PlasmaKeyboardSettings::self()->keyboardNavigationEnabled()) { - // Keys to capture for keyboard navigation - const auto keys = m_keyboardNavigationActive ? *KEYBOARD_NAVIGATION_ACTIVE_CAPTURE_KEYS : *KEYBOARD_NAVIGATION_CAPTURE_KEYS; - - // Forward and accept keyboard navigation events - for (const auto key : keys) { - if (keyEvent->key() == key) { - keyEvent->accept(); - Q_EMIT keyNavigationReleased(key); - break; - } - } - } - }); - - // Don't hook into the &InputPlugin::receivedCommit signal and call setVisible(true) - // -> it can cause a race condition as receivedCommit is emitted when the text field loses focus. - // - // If the virtual keyboard (vkbd) is manually closed and then the text field loses focus, - // setVisible(true/false) calls in quick succession may reopen the vkbd in a broken state. - // - // Series of events: - // - vkbd is manually closed (by user), but text field still focused -> setVisible(false) - // - User unfocuses the text field - // - receivedCommit() emitted -> setVisible(true) - // - contextChanged() (m_input.hasContext() = false) -> setVisible(false) - // - keyboard gets reopened by KWin because the input context gets from setVisible(true) finishes initializing! - // - // This happens because of a delay in InputPanelV1Window initialization, which confuses KWin - // into creating a new input context even when no text field is focused. - // - // TODO: Investigate other places this might happen and how to fix it. - - QGuiApplication::inputMethod()->update(Qt::ImQueryAll); -} - -OverlayController *InputListenerItem::overlayController() const -{ - return m_overlayController; -} - -void InputListenerItem::setEngine(QVirtualKeyboardInputEngine * /*engine*/) -{ - // TODO: hook into engine events if necessary? -} - -QVariant InputListenerItem::inputMethodQuery(Qt::InputMethodQuery query) const -{ - if (!m_input.hasContext()) { - if (query == Qt::ImEnabled) { - return false; - } - return {}; - } - - switch (query) { - case Qt::ImEnabled: - return true; - case Qt::ImSurroundingText: - return m_input.surroundingText(); - case Qt::ImHints: { - const auto imHints = m_input.contentHint(); - Qt::InputMethodHints qtHints; - - // Disable Qt VirtualKeyboard's hunspell plugin - // It deals poorly with current external cursor position change - // logic, and causes problems when selecting text with a mouse. - qtHints |= Qt::ImhNoPredictiveText; - - // if (imHints & InputPlugin::content_hint_default) { } - if (imHints & InputPlugin::content_hint_password) { - qtHints |= Qt::ImhSensitiveData; - } - if ((imHints & InputPlugin::content_hint_auto_capitalization) == 0 || !PlasmaKeyboardSettings::self()->autoCapitalizationEnabled()) { - qtHints |= Qt::ImhNoAutoUppercase; - } - // if (imHints & InputPlugin::content_hint_titlecase) { } - if (imHints & InputPlugin::content_hint_lowercase) { - qtHints |= Qt::ImhPreferLowercase; - } - if (imHints & InputPlugin::content_hint_uppercase) { - qtHints |= Qt::ImhPreferUppercase; - } - if (imHints & InputPlugin::content_hint_hidden_text) { - qtHints |= Qt::ImhSensitiveData; - } - if (imHints & InputPlugin::content_hint_sensitive_data) { - qtHints |= Qt::ImhSensitiveData; - } - if (imHints & InputPlugin::content_hint_latin) { - qtHints |= Qt::ImhPreferLatin; - } - if (imHints & InputPlugin::content_hint_multiline) { - qtHints |= Qt::ImhMultiLine; - } - const auto imPurpose = m_input.contentPurpose(); - switch (imPurpose) { - case InputPlugin::content_purpose_normal: - case InputPlugin::content_purpose_alpha: - case InputPlugin::content_purpose_name: - break; - case InputPlugin::content_purpose_digits: - qtHints |= Qt::ImhDigitsOnly; - break; - case InputPlugin::content_purpose_number: - qtHints |= Qt::ImhPreferNumbers; - break; - case InputPlugin::content_purpose_phone: - qtHints |= Qt::ImhDialableCharactersOnly; - break; - case InputPlugin::content_purpose_url: - qtHints |= Qt::ImhUrlCharactersOnly; - break; - case InputPlugin::content_purpose_email: - qtHints |= Qt::ImhEmailCharactersOnly; - break; - case InputPlugin::content_purpose_password: - qtHints |= Qt::ImhSensitiveData; - break; - case InputPlugin::content_purpose_date: - qtHints |= Qt::ImhDate; - break; - case InputPlugin::content_purpose_time: - qtHints |= Qt::ImhTime; - break; - case InputPlugin::content_purpose_datetime: - qtHints |= Qt::ImhDate; - qtHints |= Qt::ImhTime; - break; - case InputPlugin::content_purpose_terminal: - qtHints |= Qt::ImhPreferLatin; - break; - } - return QVariant::fromValue(qtHints); - } - case Qt::ImCurrentSelection: { - // cursorPos and anchorPos are in bytes, we need to convert QString to QByteArray for index operations - QByteArray surroundingText = m_input.surroundingText().toUtf8(); - int start = qMin(m_input.cursorPos(), m_input.anchorPos()); - int end = qMax(m_input.cursorPos(), m_input.anchorPos()); - return QString::fromUtf8(surroundingText.mid(start, end - start)); - } - case Qt::ImAnchorPosition: { - // anchorPos is in bytes, we need to convert QString to QByteArray for index operations - QByteArray surroundingText = m_input.surroundingText().toUtf8(); - int anchorBytes = qBound(0, int(m_input.anchorPos()), surroundingText.size()); - return QString::fromUtf8(surroundingText.first(anchorBytes)).length(); - } - case Qt::ImCursorPosition: { - // cursorPos is in bytes, we need to convert QString to QByteArray for index operations - QByteArray surroundingText = m_input.surroundingText().toUtf8(); - int cursorBytes = qBound(0, int(m_input.cursorPos()), surroundingText.size()); - return QString::fromUtf8(surroundingText.first(cursorBytes)).length(); - } - case Qt::ImTextBeforeCursor: { - // cursorPos is in bytes, we need to convert QString to QByteArray for index operations - QByteArray surroundingText = m_input.surroundingText().toUtf8(); - int cursorBytes = qBound(0, int(m_input.cursorPos()), surroundingText.size()); - return QString::fromUtf8(surroundingText.first(cursorBytes)); - } - case Qt::ImTextAfterCursor: { - // cursorPos is in bytes, we need to convert QString to QByteArray for index operations - QByteArray surroundingText = m_input.surroundingText().toUtf8(); - return QString::fromUtf8(surroundingText.mid(m_input.cursorPos())); - } - case Qt::ImCursorRectangle: - case Qt::ImFont: - case Qt::ImMaximumTextLength: - case Qt::ImPreferredLanguage: - case Qt::ImPlatformData: - case Qt::ImAbsolutePosition: - case Qt::ImEnterKeyType: - case Qt::ImAnchorRectangle: - case Qt::ImInputItemClipRectangle: - case Qt::ImReadOnly: - // We don't do that - break; - default: - qWarning() << "Unhandled query" << query; - break; - } - return {}; -} - -void InputListenerItem::keyPressEvent(QKeyEvent *event) -{ - if (IGNORED_KEYS->find(event->key()) != IGNORED_KEYS->end()) { - return; - } - - const QList keys = QXkbCommon::toKeysym(event); - for (auto key : keys) { - // Simulate key press only if it's not textual - if (event->text().isEmpty() || key == XKB_KEY_Return) { // (return is technically "\n") - m_input.keysym(QDateTime::currentMSecsSinceEpoch(), key, InputPlugin::Pressed, 0); - } - } -} - -void InputListenerItem::keyReleaseEvent(QKeyEvent *event) -{ - if (IGNORED_KEYS->find(event->key()) != IGNORED_KEYS->end()) { - return; - } - - const QList keys = QXkbCommon::toKeysym(event); - for (auto key : keys) { - if (event->text().isEmpty() || key == XKB_KEY_Return) { // (return is technically "\n") - // Simulate the keyboard press for non textual keys - m_input.keysym(QDateTime::currentMSecsSinceEpoch(), key, InputPlugin::Released, 0); - } else { - // If we have text coming as a key event, use it to commit the string - m_input.commit(event->text()); - } - } -} - -void InputListenerItem::inputMethodEvent(QInputMethodEvent *event) -{ - // Don't forward events from Qt VKBD to KWin if the keyboard window isn't open - // This avoids the possibility of Qt VKBD causing text changes from receiving - // events (ex. cursor movement) done by its input engine (for features like text prediction). - if (!window()->isExposed()) { - return; - } - - QString commit = event->commitString(); - QString preedit = event->preeditString(); - bool needsReplacement = event->replacementStart() != 0 || event->replacementLength() != 0; - - // Delete characters that are supposed to be replaced - if (needsReplacement) { - // The positions we send to need to be in bytes (to support UTF8) - QString surroundingText = m_input.surroundingText(); - QByteArray surroundingUtf8 = surroundingText.toUtf8(); - int boundedCursorBytes = qBound(0, int(m_input.cursorPos()), surroundingUtf8.size()); - int cursorChars = QString::fromUtf8(surroundingUtf8.first(boundedCursorBytes)).size(); - int startChars = qBound(0, cursorChars + event->replacementStart(), surroundingText.size()); - int endChars = qBound(startChars, startChars + event->replacementLength(), surroundingText.size()); - - int startBytes = surroundingText.first(startChars).toUtf8().size(); - int endBytes = surroundingText.first(endChars).toUtf8().size(); - - if (endBytes > startBytes) { - m_input.deleteSurroundingText(startBytes - boundedCursorBytes, endBytes - startBytes); - } - } - - // Commit string if there is something to commit, or we did a replacement - if (needsReplacement || !commit.isEmpty()) { - m_input.commit(commit); - } - - // Set attributes for style (ex. needed for CJK) - for (const auto &x : event->attributes()) { - if (x.type == QInputMethodEvent::TextFormat) { - int startBytes = preedit.first(qBound(0, x.start, preedit.size())).toUtf8().size(); - int endBytes = preedit.first(qBound(0, x.start + x.length, preedit.size())).toUtf8().size(); - m_input.setPreEditStyle(startBytes, endBytes - startBytes, x.value.value().type()); - } - } - - // Send cursor position (must be before preedit string) - int preEditCursorPos = preedit.toUtf8().size(); - for (const auto &attribute : event->attributes()) { - if (attribute.type != QInputMethodEvent::Cursor) { - continue; - } - - // Set special attribute preedit cursor position (ex. needed for CJK) - if (!attribute.value.isValid() || !attribute.value.toBool()) { - preEditCursorPos = -1; - } else { - preEditCursorPos = preedit.first(qBound(0, attribute.start, preedit.size())).toUtf8().size(); - } - break; - } - m_input.setPreEditCursor(preEditCursorPos); - - // Send currently being edited string - m_input.setPreEditString(preedit); -} - -#include "moc_inputlisteneritem.cpp" diff --git a/src/inputlisteneritem.h b/src/inputlisteneritem.h deleted file mode 100644 index 1478c67..0000000 --- a/src/inputlisteneritem.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - SPDX-FileCopyrightText: 2024 Aleix Pol i Gonzalez - SPDX-FileCopyrightText: 2025 Devin Lin - SPDX-FileCopyrightText: 2025 Kristen McWilliam - - SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL -*/ - -#pragma once - -#include -#include -#include -#include - -#include - -#include "inputplugin.h" - -class OverlayController; - -class InputListenerItem : public QQuickItem -{ - Q_OBJECT - QML_ELEMENT - - Q_PROPERTY(QVirtualKeyboardInputEngine *engine WRITE setEngine) - Q_PROPERTY(bool keyboardNavigationActive MEMBER m_keyboardNavigationActive) - - /** - * Controller for overlay popups (diacritics, emoji, text expansion). - * - * Exposed to QML for connecting overlay windows. - */ - Q_PROPERTY(OverlayController *overlayController READ overlayController CONSTANT) - -public: - InputListenerItem(); - - void setEngine(QVirtualKeyboardInputEngine *engine); - - QVariant inputMethodQuery(Qt::InputMethodQuery query) const override; - - void keyPressEvent(QKeyEvent *event) override; - void keyReleaseEvent(QKeyEvent *event) override; - void inputMethodEvent(QInputMethodEvent *event) override; - - /** - * Get the overlay controller. - */ - OverlayController *overlayController() const; - -Q_SIGNALS: - void keyNavigationPressed(int key); - void keyNavigationReleased(int key); - -private: - InputPlugin m_input; - OverlayController *m_overlayController = nullptr; - bool m_keyboardNavigationActive = false; -}; diff --git a/src/inputmethodconnection.cpp b/src/inputmethodconnection.cpp new file mode 100644 index 0000000..e27e014 --- /dev/null +++ b/src/inputmethodconnection.cpp @@ -0,0 +1,346 @@ +/* + SPDX-FileCopyrightText: 2024 Aleix Pol i Gonzalez + SPDX-FileCopyrightText: 2025 Devin Lin + SPDX-FileCopyrightText: 2025 Kristen McWilliam + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "inputmethodconnection.h" + +#include "inputengine.h" +#include "inputmethod_p.h" +#include "inputmethodhints.h" +#include "kwinfakeinput.h" +#include "plasmakeyboardsettings.h" +#include "virtualkeyboardcontext.h" +#include "vkbdwaylandinputbackend.h" + +#include "overlay/longpresstrigger.h" +#include "overlay/overlaycontroller.h" +#include "overlay/prefixquerytrigger.h" +#include "overlay/textexpansiontrigger.h" + +#include +#include +#include + +Q_GLOBAL_STATIC(InputMethod, s_im) + +static QList initCapture() +{ + return { + Qt::Key_Left, + Qt::Key_Right, + Qt::Key_Up, + Qt::Key_Down, + }; +} + +Q_GLOBAL_STATIC_WITH_ARGS(const QList, KEYBOARD_NAVIGATION_CAPTURE_KEYS, (initCapture())); +Q_GLOBAL_STATIC_WITH_ARGS(const QList, + KEYBOARD_NAVIGATION_ACTIVE_CAPTURE_KEYS, + (initCapture() + QList{Qt::Key_Return, Qt::Key_Enter, Qt::Key_Escape})); + +static uint keysymForQtKey(int key) +{ + switch (key) { + case Qt::Key_Backspace: + return XKB_KEY_BackSpace; + case Qt::Key_Delete: + return XKB_KEY_Delete; + case Qt::Key_Return: + return XKB_KEY_Return; + case Qt::Key_Enter: + return XKB_KEY_KP_Enter; + case Qt::Key_Left: + return XKB_KEY_Left; + case Qt::Key_Right: + return XKB_KEY_Right; + case Qt::Key_Up: + return XKB_KEY_Up; + case Qt::Key_Down: + return XKB_KEY_Down; + case Qt::Key_Home: + return XKB_KEY_Home; + case Qt::Key_End: + return XKB_KEY_End; + case Qt::Key_Space: + return XKB_KEY_space; + default: + return XKB_KEY_NoSymbol; + } +} + +static uint currentTimestamp() +{ + static QElapsedTimer timer = [] { + QElapsedTimer value; + value.start(); + return value; + }(); + return uint(timer.elapsed()); +} + +InputMethodConnection::InputMethodConnection(QObject *parent) + : QObject(parent) + , m_input(&(*s_im)) + , m_vkbdInputBackend(new VkbdWaylandInputBackend(this)) + , m_virtualKeyboardContext(new VirtualKeyboardContext(m_vkbdInputBackend, this)) + , m_fakeInput(new KWinFakeInput(m_vkbdInputBackend, this)) + , m_overlayController(new OverlayController(&m_input, this)) +{ + m_input.setGrabbing(true); + + m_overlayController->registerTrigger(new LongPressTrigger(m_virtualKeyboardContext->inputEngine(), m_overlayController)); + m_overlayController->registerTrigger(new PrefixQueryTrigger(m_overlayController)); + m_overlayController->registerTrigger(new TextExpansionTrigger(m_overlayController)); + + const auto syncBackendState = [this] { + m_vkbdInputBackend->setActive(m_input.hasContext()); + m_vkbdInputBackend->setInputMethodHints( + mapInputMethodHints(m_input.contentHint(), m_input.contentPurpose(), PlasmaKeyboardSettings::self()->autoCapitalizationEnabled())); + m_vkbdInputBackend->setSurroundingState(m_input.surroundingText(), m_input.cursorPos(), m_input.anchorPos()); + }; + + // ** Wayland input-method-v1 (KWin) hooks ** + // Compositor -> plasma-keyboard events + + connect(&m_input, &InputPlugin::contextChanged, this, [this, syncBackendState] { + syncBackendState(); + + if (m_overlayController) { + m_overlayController->cancelOverlay(); + } + + if (!m_input.hasContext()) { + m_hidden = false; + m_vkbdInputBackend->reset(); + } + + updateWindowVisible(); + }); + + connect(&m_input, &InputPlugin::surroundingTextChanged, this, [this, syncBackendState] { + syncBackendState(); + + if (m_overlayController) { + m_overlayController->handleSurroundingTextChanged(); + } + + if (m_input.hasContext()) { + m_hidden = false; + updateWindowVisible(); + } + }); + + connect(&m_input, &InputPlugin::contentTypeChanged, this, [this, syncBackendState] { + syncBackendState(); + }); + + connect(&m_input, &InputPlugin::resetRequested, this, [this] { + m_vkbdInputBackend->reset(); + }); + + connect(&m_input, &InputPlugin::keyPressed, this, [this](QKeyEvent *keyEvent) { + if (m_overlayController && m_overlayController->processKeyPress(keyEvent)) { + keyEvent->accept(); + return; + } + + if (!m_window || !m_window->isExposed()) { + return; + } + + if (!PlasmaKeyboardSettings::self()->keyboardNavigationEnabled()) { + return; + } + + if (!m_keyboardNavigationAvailable) { + return; + } + + const auto keys = m_keyboardNavigationActive ? *KEYBOARD_NAVIGATION_ACTIVE_CAPTURE_KEYS : *KEYBOARD_NAVIGATION_CAPTURE_KEYS; + for (const auto key : keys) { + if (keyEvent->key() == key) { + keyEvent->accept(); + Q_EMIT keyNavigationPressed(key); + break; + } + } + }); + + connect(&m_input, &InputPlugin::keyReleased, this, [this](QKeyEvent *keyEvent) { + if (m_overlayController && m_overlayController->processKeyRelease(keyEvent)) { + keyEvent->accept(); + return; + } + + if (!m_window || !m_window->isExposed()) { + return; + } + + if (!PlasmaKeyboardSettings::self()->keyboardNavigationEnabled()) { + return; + } + + if (!m_keyboardNavigationAvailable) { + return; + } + + const auto keys = m_keyboardNavigationActive ? *KEYBOARD_NAVIGATION_ACTIVE_CAPTURE_KEYS : *KEYBOARD_NAVIGATION_CAPTURE_KEYS; + for (const auto key : keys) { + if (keyEvent->key() == key) { + keyEvent->accept(); + Q_EMIT keyNavigationReleased(key); + break; + } + } + }); + + connect(PlasmaKeyboardSettings::self(), &PlasmaKeyboardSettings::autoCapitalizationEnabledChanged, this, syncBackendState); + + // ** Virtual keyboard backend hooks ** + // plasma-keyboard (keyboard engine) -> compositor + + connect(m_vkbdInputBackend, &VkbdWaylandInputBackend::preeditTextRequested, this, [this](const QString &text) { + if (!m_window || !m_window->isExposed()) { + return; + } + + if (!text.isEmpty()) { + const int utf8Length = text.toUtf8().size(); + m_input.setPreEditStyle(0, utf8Length, QtWayland::zwp_text_input_v1::preedit_style_underline); + m_input.setPreEditCursor(utf8Length); + } + m_input.setPreEditString(text); + }); + + connect(m_vkbdInputBackend, &VkbdWaylandInputBackend::commitTextRequested, this, [this](const QString &text) { + if (!m_window || !m_window->isExposed()) { + return; + } + + m_input.commit(text); + }); + + connect(m_vkbdInputBackend, &VkbdWaylandInputBackend::deleteSurroundingTextRequested, this, [this](int index, int length) { + if (!m_window || !m_window->isExposed()) { + return; + } + + m_input.deleteSurroundingText(index, length); + }); + + const auto sendKeyPressed = [this](int key, bool pressed) { + if (!m_window || !m_window->isExposed()) { + return false; + } + + if (m_fakeInput->shouldUseFakeInput(key)) { + // Send this key over kwin-fake-input instead of input-method-v1 (true keyboard emulation) + return m_fakeInput->sendKeyPressed(key, pressed); + } + + const uint sym = keysymForQtKey(key); + if (sym == XKB_KEY_NoSymbol) { + return false; + } + + const uint timestamp = currentTimestamp(); + m_input.keysym(timestamp, sym, pressed ? InputPlugin::Pressed : InputPlugin::Released, 0); + return true; + }; + + connect(m_vkbdInputBackend, &VkbdWaylandInputBackend::keyClickRequested, this, [sendKeyPressed](int key, bool *handled) { + if (!handled) { + return; + } + + *handled = sendKeyPressed(key, true) && sendKeyPressed(key, false); + }); + + connect(m_vkbdInputBackend, &VkbdWaylandInputBackend::keyPressedRequested, this, [sendKeyPressed](int key, bool pressed, bool *handled) { + if (!handled) { + return; + } + + *handled = sendKeyPressed(key, pressed); + }); + + syncBackendState(); +} + +QWindow *InputMethodConnection::window() const +{ + return m_window; +} + +void InputMethodConnection::setWindow(QWindow *window) +{ + if (m_window == window) { + return; + } + + m_window = window; + updateWindowVisible(); + Q_EMIT windowChanged(); +} + +bool InputMethodConnection::keyboardNavigationAvailable() const +{ + return m_keyboardNavigationAvailable; +} + +void InputMethodConnection::setKeyboardNavigationAvailable(bool available) +{ + if (m_keyboardNavigationAvailable == available) { + return; + } + + m_keyboardNavigationAvailable = available; + Q_EMIT keyboardNavigationAvailableChanged(); +} + +bool InputMethodConnection::keyboardNavigationActive() const +{ + return m_keyboardNavigationActive; +} + +void InputMethodConnection::setKeyboardNavigationActive(bool active) +{ + if (m_keyboardNavigationActive == active) { + return; + } + + m_keyboardNavigationActive = active; + Q_EMIT keyboardNavigationActiveChanged(); +} + +void InputMethodConnection::hide() +{ + m_hidden = true; + m_vkbdInputBackend->reset(); + updateWindowVisible(); +} + +VirtualKeyboardContext *InputMethodConnection::virtualKeyboardContext() const +{ + return m_virtualKeyboardContext; +} + +OverlayController *InputMethodConnection::overlayController() const +{ + return m_overlayController; +} + +void InputMethodConnection::updateWindowVisible() +{ + if (!m_window) { + return; + } + + m_window->setVisible(m_input.hasContext() && !m_hidden); +} + +#include "moc_inputmethodconnection.cpp" diff --git a/src/inputmethodconnection.h b/src/inputmethodconnection.h new file mode 100644 index 0000000..862ed49 --- /dev/null +++ b/src/inputmethodconnection.h @@ -0,0 +1,80 @@ +/* + SPDX-FileCopyrightText: 2024 Aleix Pol i Gonzalez + SPDX-FileCopyrightText: 2025 Devin Lin + SPDX-FileCopyrightText: 2025 Kristen McWilliam + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include +#include +#include +#include + +#include "inputplugin.h" + +class OverlayController; +class KWinFakeInput; +class VirtualKeyboardContext; +class VkbdWaylandInputBackend; + +/** + * Connects the virtual keyboard UI to the compositor's input method. + */ +class InputMethodConnection : public QObject +{ + Q_OBJECT + QML_NAMED_ELEMENT(InputMethodConnection) + + Q_PROPERTY(QWindow *window READ window WRITE setWindow NOTIFY windowChanged) + Q_PROPERTY(bool keyboardNavigationAvailable READ keyboardNavigationAvailable WRITE setKeyboardNavigationAvailable NOTIFY keyboardNavigationAvailableChanged) + Q_PROPERTY(bool keyboardNavigationActive READ keyboardNavigationActive WRITE setKeyboardNavigationActive NOTIFY keyboardNavigationActiveChanged) + Q_PROPERTY(VirtualKeyboardContext *virtualKeyboardContext READ virtualKeyboardContext CONSTANT) + + /** + * Controller for overlay popups (diacritics, emoji, text expansion). + * + * Exposed to QML for connecting overlay windows. + */ + Q_PROPERTY(OverlayController *overlayController READ overlayController CONSTANT) + +public: + explicit InputMethodConnection(QObject *parent = nullptr); + + QWindow *window() const; + void setWindow(QWindow *window); + bool keyboardNavigationAvailable() const; + void setKeyboardNavigationAvailable(bool available); + bool keyboardNavigationActive() const; + void setKeyboardNavigationActive(bool active); + Q_INVOKABLE void hide(); + + VirtualKeyboardContext *virtualKeyboardContext() const; + + /** + * Get the overlay controller. + */ + OverlayController *overlayController() const; + +Q_SIGNALS: + void windowChanged(); + void keyboardNavigationAvailableChanged(); + void keyboardNavigationActiveChanged(); + void keyNavigationPressed(int key); + void keyNavigationReleased(int key); + +private: + void updateWindowVisible(); + + InputPlugin m_input; + VkbdWaylandInputBackend *m_vkbdInputBackend = nullptr; + VirtualKeyboardContext *m_virtualKeyboardContext = nullptr; + KWinFakeInput *m_fakeInput = nullptr; + OverlayController *m_overlayController = nullptr; + QPointer m_window; + bool m_hidden = false; + bool m_keyboardNavigationAvailable = false; + bool m_keyboardNavigationActive = false; +}; diff --git a/src/inputmethodhints.cpp b/src/inputmethodhints.cpp new file mode 100644 index 0000000..a9a6acd --- /dev/null +++ b/src/inputmethodhints.cpp @@ -0,0 +1,77 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "inputmethodhints.h" + +Qt::InputMethodHints mapInputMethodHints(InputPlugin::ContentHint contentHints, InputPlugin::ContentPurpose contentPurpose, bool autoCapitalizationEnabled) +{ + Qt::InputMethodHints hints; + + if ((contentHints & InputPlugin::content_hint_auto_completion) == 0 || (contentHints & InputPlugin::content_hint_auto_correction) == 0) { + hints |= Qt::ImhNoPredictiveText; + } + if ((contentHints & InputPlugin::content_hint_auto_capitalization) == 0 || !autoCapitalizationEnabled) { + hints |= Qt::ImhNoAutoUppercase; + } + if (contentHints & InputPlugin::content_hint_lowercase) { + hints |= Qt::ImhPreferLowercase; + } + if (contentHints & InputPlugin::content_hint_uppercase) { + hints |= Qt::ImhPreferUppercase; + } + if (contentHints & InputPlugin::content_hint_hidden_text) { + hints |= Qt::ImhHiddenText; + hints |= Qt::ImhSensitiveData; + } + if (contentHints & InputPlugin::content_hint_sensitive_data) { + hints |= Qt::ImhSensitiveData; + } + if (contentHints & InputPlugin::content_hint_latin) { + hints |= Qt::ImhPreferLatin; + } + if (contentHints & InputPlugin::content_hint_multiline) { + hints |= Qt::ImhMultiLine; + } + + switch (contentPurpose) { + case InputPlugin::content_purpose_digits: + hints |= Qt::ImhDigitsOnly; + break; + case InputPlugin::content_purpose_number: + hints |= Qt::ImhPreferNumbers; + break; + case InputPlugin::content_purpose_phone: + hints |= Qt::ImhDialableCharactersOnly; + break; + case InputPlugin::content_purpose_url: + hints |= Qt::ImhUrlCharactersOnly; + break; + case InputPlugin::content_purpose_email: + hints |= Qt::ImhEmailCharactersOnly; + break; + case InputPlugin::content_purpose_password: + hints |= Qt::ImhSensitiveData; + break; + case InputPlugin::content_purpose_date: + hints |= Qt::ImhDate; + break; + case InputPlugin::content_purpose_time: + hints |= Qt::ImhTime; + break; + case InputPlugin::content_purpose_datetime: + hints |= Qt::ImhDate | Qt::ImhTime; + break; + case InputPlugin::content_purpose_terminal: + hints |= Qt::ImhPreferLatin; + break; + case InputPlugin::content_purpose_normal: + case InputPlugin::content_purpose_alpha: + case InputPlugin::content_purpose_name: + break; + } + + return hints; +} diff --git a/src/inputmethodhints.h b/src/inputmethodhints.h new file mode 100644 index 0000000..2ea943a --- /dev/null +++ b/src/inputmethodhints.h @@ -0,0 +1,16 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include "inputplugin.h" + +#include + +/** + * Converts compositor content metadata to Qt input method hints. + */ +Qt::InputMethodHints mapInputMethodHints(InputPlugin::ContentHint contentHints, InputPlugin::ContentPurpose contentPurpose, bool autoCapitalizationEnabled); diff --git a/src/keycodes.h b/src/keycodes.h new file mode 100644 index 0000000..9d0dd89 --- /dev/null +++ b/src/keycodes.h @@ -0,0 +1,29 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include +#include + +/** + * Exposes key codes missing from Qt to QML. + */ +class KeyCodes : public QObject +{ + Q_OBJECT + QML_ELEMENT + QML_SINGLETON + +public: + using QObject::QObject; + + enum Key { + // HACK: Qt does not have a Key_Fn, so invent our own constant for it + KeyFn = 0x01800000, + }; + Q_ENUM(Key) +}; diff --git a/src/kwinfakeinput.cpp b/src/kwinfakeinput.cpp new file mode 100644 index 0000000..275e4bc --- /dev/null +++ b/src/kwinfakeinput.cpp @@ -0,0 +1,219 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "kwinfakeinput.h" + +#include "keycodes.h" +#include "qwayland-fake-input.h" +#include "vkbdwaylandinputbackend.h" + +#include +#include +#include +#include +#include + +#include + +class FakeInput : public QWaylandClientExtensionTemplate, public QtWayland::org_kde_kwin_fake_input +{ +public: + FakeInput() + : QWaylandClientExtensionTemplate(ORG_KDE_KWIN_FAKE_INPUT_KEYBOARD_KEY_SINCE_VERSION) + { + initialize(); + } +}; + +static const QHash QT_KEY_TO_LINUX = { + {Qt::Key_Meta, KEY_LEFTMETA}, + {Qt::Key_Alt, KEY_LEFTALT}, + {Qt::Key_Control, KEY_LEFTCTRL}, + {Qt::Key_Shift, KEY_LEFTSHIFT}, + {Qt::Key_CapsLock, KEY_CAPSLOCK}, + {KeyCodes::KeyFn, KEY_FN}, + {Qt::Key_Tab, KEY_TAB}, + {Qt::Key_Backspace, KEY_BACKSPACE}, + {Qt::Key_Return, KEY_ENTER}, + {Qt::Key_Enter, KEY_ENTER}, + {Qt::Key_Escape, KEY_ESC}, + {Qt::Key_Space, KEY_SPACE}, + {Qt::Key_Left, KEY_LEFT}, + {Qt::Key_Right, KEY_RIGHT}, + {Qt::Key_Up, KEY_UP}, + {Qt::Key_Down, KEY_DOWN}, + {Qt::Key_Insert, KEY_INSERT}, + {Qt::Key_Delete, KEY_DELETE}, + {Qt::Key_Home, KEY_HOME}, + {Qt::Key_End, KEY_END}, + {Qt::Key_PageUp, KEY_PAGEUP}, + {Qt::Key_PageDown, KEY_PAGEDOWN}, + {Qt::Key_A, KEY_A}, + {Qt::Key_B, KEY_B}, + {Qt::Key_C, KEY_C}, + {Qt::Key_D, KEY_D}, + {Qt::Key_E, KEY_E}, + {Qt::Key_F, KEY_F}, + {Qt::Key_G, KEY_G}, + {Qt::Key_H, KEY_H}, + {Qt::Key_I, KEY_I}, + {Qt::Key_J, KEY_J}, + {Qt::Key_K, KEY_K}, + {Qt::Key_L, KEY_L}, + {Qt::Key_M, KEY_M}, + {Qt::Key_N, KEY_N}, + {Qt::Key_O, KEY_O}, + {Qt::Key_P, KEY_P}, + {Qt::Key_Q, KEY_Q}, + {Qt::Key_R, KEY_R}, + {Qt::Key_S, KEY_S}, + {Qt::Key_T, KEY_T}, + {Qt::Key_U, KEY_U}, + {Qt::Key_V, KEY_V}, + {Qt::Key_W, KEY_W}, + {Qt::Key_X, KEY_X}, + {Qt::Key_Y, KEY_Y}, + {Qt::Key_Z, KEY_Z}, + {Qt::Key_0, KEY_0}, + {Qt::Key_1, KEY_1}, + {Qt::Key_2, KEY_2}, + {Qt::Key_3, KEY_3}, + {Qt::Key_4, KEY_4}, + {Qt::Key_5, KEY_5}, + {Qt::Key_6, KEY_6}, + {Qt::Key_7, KEY_7}, + {Qt::Key_8, KEY_8}, + {Qt::Key_9, KEY_9}, + {Qt::Key_F1, KEY_F1}, + {Qt::Key_F2, KEY_F2}, + {Qt::Key_F3, KEY_F3}, + {Qt::Key_F4, KEY_F4}, + {Qt::Key_F5, KEY_F5}, + {Qt::Key_F6, KEY_F6}, + {Qt::Key_F7, KEY_F7}, + {Qt::Key_F8, KEY_F8}, + {Qt::Key_F9, KEY_F9}, + {Qt::Key_F10, KEY_F10}, + {Qt::Key_F11, KEY_F11}, + {Qt::Key_F12, KEY_F12}, + {Qt::Key_Minus, KEY_MINUS}, + {Qt::Key_Equal, KEY_EQUAL}, + {Qt::Key_Backslash, KEY_BACKSLASH}, + {Qt::Key_Slash, KEY_SLASH}, + {Qt::Key_Comma, KEY_COMMA}, + {Qt::Key_Period, KEY_DOT}, + {Qt::Key_Semicolon, KEY_SEMICOLON}, + {Qt::Key_Apostrophe, KEY_APOSTROPHE}, + {Qt::Key_BracketLeft, KEY_LEFTBRACE}, + {Qt::Key_BracketRight, KEY_RIGHTBRACE}, + {Qt::Key_QuoteLeft, KEY_GRAVE}, +}; + +// List of keys to forward through kwin-fake-input rather than input-method-v1 +static const QSet DIRECT_FAKE_INPUT_KEYS = { + Qt::Key_Meta, Qt::Key_Alt, Qt::Key_Control, Qt::Key_Shift, KeyCodes::KeyFn, Qt::Key_CapsLock, Qt::Key_Tab, Qt::Key_Escape, Qt::Key_Left, Qt::Key_Right, + Qt::Key_Up, Qt::Key_Down, Qt::Key_Home, Qt::Key_End, Qt::Key_PageUp, Qt::Key_PageDown, Qt::Key_F1, Qt::Key_F2, Qt::Key_F3, Qt::Key_F4, + Qt::Key_F5, Qt::Key_F6, Qt::Key_F7, Qt::Key_F8, Qt::Key_F9, Qt::Key_F10, Qt::Key_F11, Qt::Key_F12, +}; + +// List of keys that are modifiers (and keys entered after are captured as well, even if not in DIRECT_FAKE_INPUT_KEYS) +static const QSet MODIFIER_KEYS = { + Qt::Key_Meta, + Qt::Key_Alt, + Qt::Key_Control, + Qt::Key_Shift, + KeyCodes::KeyFn, +}; + +KWinFakeInput::KWinFakeInput(VkbdWaylandInputBackend *backend, QObject *parent) + : QObject(parent) + , m_backend(backend) +{ +} + +bool KWinFakeInput::shouldUseFakeInput(int key) const +{ + if (DIRECT_FAKE_INPUT_KEYS.contains(key)) { + return true; + } + if (!m_backend || !supportsKey(key)) { + return false; + } + + for (const int pressedKey : m_backend->pressedKeys()) { + if (isModifier(pressedKey)) { + return true; + } + } + return false; +} + +bool KWinFakeInput::sendKeyPressed(int key, bool pressed) +{ + if (!supportsKey(key) || !ensureInitialized()) { + return false; + } + + sendFakeKeyboardKey(key, pressed); + + // For a non-modifier key, clear the modifiers + if (!pressed && !isModifier(key) && m_backend && !m_backend->pressedKeys().isEmpty()) { + // HACK: clear modifiers after a delay, otherwise it might not be registered by the app + QTimer::singleShot(20, this, &KWinFakeInput::clearPressedModifiers); + } + return true; +} + +bool KWinFakeInput::ensureInitialized() +{ + if (m_fakeInput) { + return true; + } + + auto *fakeInput = new FakeInput(); + if (!fakeInput->isInitialized() || !fakeInput->isActive()) { + delete fakeInput; + return false; + } + + fakeInput->authenticate({}, {}); + fakeInput->setParent(this); + m_fakeInput = fakeInput; + return true; +} + +bool KWinFakeInput::isModifier(int key) const +{ + return MODIFIER_KEYS.contains(key); +} + +bool KWinFakeInput::supportsKey(int key) const +{ + return QT_KEY_TO_LINUX.contains(key); +} + +void KWinFakeInput::clearPressedModifiers() +{ + if (!m_backend) { + return; + } + + const QList keys = m_backend->pressedKeys(); + for (const int key : keys) { + if (isModifier(key)) { + m_backend->sendKeyPressed(key, false); + } + } +} + +void KWinFakeInput::sendFakeKeyboardKey(int key, bool pressed) +{ + if (!m_fakeInput) { + return; + } + + static_cast(m_fakeInput)->keyboard_key(QT_KEY_TO_LINUX.value(key), pressed); +} diff --git a/src/kwinfakeinput.h b/src/kwinfakeinput.h new file mode 100644 index 0000000..810c32a --- /dev/null +++ b/src/kwinfakeinput.h @@ -0,0 +1,37 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include + +class VkbdWaylandInputBackend; + +/** + * Sends keys unsupported by the input method protocol through KWin's fake input protocol. + * + * Keys sent here effectively emulate the keyboard. + */ +class KWinFakeInput : public QObject +{ + Q_OBJECT + +public: + explicit KWinFakeInput(VkbdWaylandInputBackend *backend, QObject *parent = nullptr); + + bool shouldUseFakeInput(int key) const; + bool sendKeyPressed(int key, bool pressed); + +private: + bool ensureInitialized(); + bool isModifier(int key) const; + bool supportsKey(int key) const; + void clearPressedModifiers(); + void sendFakeKeyboardKey(int key, bool pressed); + + QObject *m_fakeInput = nullptr; + VkbdWaylandInputBackend *m_backend = nullptr; +}; diff --git a/src/layoutpathhelper.h b/src/layoutpathhelper.h deleted file mode 100644 index ef9d1f5..0000000 --- a/src/layoutpathhelper.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - SPDX-FileCopyrightText: 2025 Devin Lin - SPDX-FileCopyrightText: 2026 Kristen McWilliam - - SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL -*/ - -#pragma once - -#include -#include - -/** - * Initializes the QT_VIRTUALKEYBOARD_LAYOUT_PATH environment variable to point to our own keyboard layouts - * provided in this repository, unless the PLASMA_KEYBOARD_USE_QT_LAYOUTS environment variable is set to "1" or "true". - * - * This allows us to provide our own custom layouts and override Qt's built-in ones, while still giving users - * the option to use the default Qt layouts if they prefer. - * - * Helper function used by both the main application and the KCM, to ensure they both use the same layouts path. - */ -inline void initLayoutsPath() -{ - // PLASMA_KEYBOARD_USE_QT_LAYOUTS - whether to use Qt's builtin keyboard layouts rather than our own. - const bool useQtLayouts = qEnvironmentVariableIntValue("PLASMA_KEYBOARD_USE_QT_LAYOUTS") != 0; - - if (!useQtLayouts) { - // Set QT_VIRTUALKEYBOARD_LAYOUT_PATH to our own keyboard layouts provided in this repository. - - // Loop over all "/usr/share" paths and check if layouts folder exists - const QStringList locations = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation); - for (const QString &basePath : locations) { - QString layoutsDir = basePath + QStringLiteral("/plasma/keyboard/layouts"); - - // Check if path exists - if (QDir(layoutsDir).exists()) { - // Set path for Qt to search for layouts - qputenv("QT_VIRTUALKEYBOARD_LAYOUT_PATH", layoutsDir.toUtf8()); - break; - } - } - } -} diff --git a/src/main.cpp b/src/main.cpp index 7f51c24..ca61939 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -7,7 +7,6 @@ #include "config-plasma-keyboard.h" #include "inputpanelintegration.h" -#include "layoutpathhelper.h" #include "logging.h" #include "plasmakeyboardsettings.h" #include @@ -19,7 +18,6 @@ #include #include -#include #include #include #include @@ -35,10 +33,6 @@ int main(int argc, char **argv) { - qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard")); - - initLayoutsPath(); - QGuiApplication application(argc, argv); KLocalizedString::setApplicationDomain("plasma-keyboard"); @@ -67,7 +61,7 @@ int main(int argc, char **argv) aboutData.processCommandLine(&parser); } - if (!PLASMA_KEYBOARD_SOUND_ENABLED) { + if (!PLASMA_KEYBOARD_SOUNDS_ENABLED) { PlasmaKeyboardSettings::self()->setSoundEnabled(false); } diff --git a/src/overlay/longpresstrigger.cpp b/src/overlay/longpresstrigger.cpp index a080e94..57761d6 100644 --- a/src/overlay/longpresstrigger.cpp +++ b/src/overlay/longpresstrigger.cpp @@ -7,6 +7,7 @@ #include "longpresstrigger.h" #include "diacriticsdataloader.h" +#include "inputengine.h" #include "logging.h" #include "plasmakeyboardsettings.h" @@ -14,15 +15,18 @@ using namespace Qt::StringLiterals; -LongPressTrigger::LongPressTrigger(QObject *parent) +LongPressTrigger::LongPressTrigger(InputEngine *inputEngine, QObject *parent) : OverlayTrigger(parent) + , m_inputEngine(inputEngine) { - m_diacriticsMap = DiacriticsDataLoader::loadMap(PlasmaKeyboardSettings::self()->enabledLocales()); + m_diacriticsMap = DiacriticsDataLoader::loadMap(currentLocales()); - // Reload the diacritics map whenever the user changes the enabled locales - // in the KCM, so the keyboard reflects the new locale ordering without - // requiring a restart. - connect(PlasmaKeyboardSettings::self(), &PlasmaKeyboardSettings::enabledLocalesChanged, this, &LongPressTrigger::reloadMap); + if (m_inputEngine) { + // Reload the diacritics map whenever the user changes the enabled locales + // in the KCM, so the keyboard reflects the new locale ordering without + // requiring a restart. + connect(m_inputEngine, &InputEngine::localeChanged, this, &LongPressTrigger::reloadMap); + } m_holdThresholdMs = PlasmaKeyboardSettings::self()->diacriticsHoldThresholdMs(); connect(PlasmaKeyboardSettings::self(), &PlasmaKeyboardSettings::diacriticsHoldThresholdMsChanged, this, [this]() { @@ -42,8 +46,8 @@ QString LongPressTrigger::displayName() const void LongPressTrigger::reloadMap() { - m_diacriticsMap = DiacriticsDataLoader::loadMap(PlasmaKeyboardSettings::self()->enabledLocales()); - qCDebug(PlasmaKeyboard) << "LongPressTrigger: Diacritics map reloaded for locales" << PlasmaKeyboardSettings::self()->enabledLocales(); + m_diacriticsMap = DiacriticsDataLoader::loadMap(currentLocales()); + qCDebug(PlasmaKeyboard) << "LongPressTrigger: Diacritics map reloaded for locales" << currentLocales(); } // clang-format off @@ -169,4 +173,13 @@ bool LongPressTrigger::shouldHandleKey(const QKeyEvent *event) const return m_diacriticsMap.contains(baseChar); } +QStringList LongPressTrigger::currentLocales() const +{ + if (!m_inputEngine || m_inputEngine->locale().isEmpty()) { + return {}; + } + + return {m_inputEngine->locale()}; +} + #include "moc_longpresstrigger.cpp" diff --git a/src/overlay/longpresstrigger.h b/src/overlay/longpresstrigger.h index 1f62283..7af775c 100644 --- a/src/overlay/longpresstrigger.h +++ b/src/overlay/longpresstrigger.h @@ -10,8 +10,11 @@ #include "overlaytrigger.h" #include +#include #include +class InputEngine; + /** * Trigger that activates an overlay after a long-press on a key. * @@ -23,7 +26,7 @@ class LongPressTrigger : public OverlayTrigger Q_OBJECT public: - explicit LongPressTrigger(QObject *parent = nullptr); + explicit LongPressTrigger(InputEngine *inputEngine, QObject *parent = nullptr); ~LongPressTrigger() override = default; QString triggerId() const override; @@ -54,6 +57,9 @@ private: * Checks if the key event should be considered for long-press diacritics. */ bool shouldHandleKey(const QKeyEvent *event) const; + QStringList currentLocales() const; + + InputEngine *m_inputEngine = nullptr; /** Map of base characters to their diacritic variants. */ QHash m_diacriticsMap; diff --git a/src/overlay/overlaycontroller.h b/src/overlay/overlaycontroller.h index 4fb2911..7f9ac79 100644 --- a/src/overlay/overlaycontroller.h +++ b/src/overlay/overlaycontroller.h @@ -144,7 +144,7 @@ public Q_SLOTS: * Notify the controller that the surrounding text (and therefore cursor position) has * changed. * - * Called from InputListenerItem whenever the compositor reports a surrounding-text + * Called from InputMethodConnection whenever the compositor reports a surrounding-text * update. The controller distinguishes changes caused by its own commit_string * operations from external cursor movements (e.g. the user tapping elsewhere in the * text field). If an external cursor movement is detected while an overlay or hold diff --git a/src/plasmakeyboardsettings.kcfg b/src/plasmakeyboardsettings.kcfg index 74a5b3b..08a203b 100644 --- a/src/plasmakeyboardsettings.kcfg +++ b/src/plasmakeyboardsettings.kcfg @@ -19,6 +19,13 @@ 10 + + + true + + + + diff --git a/src/qml/KeyboardPanel.qml b/src/qml/KeyboardPanel.qml new file mode 100644 index 0000000..e9fd470 --- /dev/null +++ b/src/qml/KeyboardPanel.qml @@ -0,0 +1,130 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +import QtQuick + +import org.kde.kirigami as Kirigami +import org.kde.plasma.keyboard +import org.kde.plasma.keyboard.virtualkeyboard +import org.kde.plasma.keyboard.virtualkeyboard.components + +Kirigami.ShadowedRectangle { + id: root + + property var hostWindow: null + property var virtualKeyboardContext: null + property alias inputPanel: inputPanel + property alias languagePopup: languagePopup + property alias alternativeKeysPopup: alternativeKeysPopup + property alias characterPopup: characterPopup + property alias flickPreviewPopup: flickPreviewPopup + readonly property var keyboardController: virtualKeyboardContext ? virtualKeyboardContext.keyboardController : null + + readonly property bool isFloating: false + readonly property bool isFullScreenWidth: !isFloating && PlasmaKeyboardSettings.panelFillScreenWidth + + signal showSettingsRequested() + + color: BreezeConstants.keyboardBackgroundColor + + corners { + bottomLeftRadius: isFloating ? Kirigami.Units.cornerRadius : 0 + bottomRightRadius: isFloating ? Kirigami.Units.cornerRadius : 0 + topLeftRadius: isFullScreenWidth ? 0 : Kirigami.Units.cornerRadius + topRightRadius: isFullScreenWidth ? 0 : Kirigami.Units.cornerRadius + } + + shadow { + size: isFullScreenWidth ? 0 : 16 + color: Qt.rgba(0, 0, 0, 0.3) + } + + x: hostWindow ? (hostWindow.width / 2) - (width / 2) : 0 + y: hostWindow ? (hostWindow.height - height) : 0 + width: inputPanel.width > 0 ? inputPanel.width : 100 + height: inputPanel.height > 0 ? inputPanel.height : 100 + + LanguagePopup { + id: languagePopup + keyboardPanel: inputPanel + keyboardController: root.keyboardController + onShowSettings: root.showSettingsRequested() + } + + AlternativeKeysPopup { + id: alternativeKeysPopup + keyboardPanel: inputPanel + } + + CharacterPopup { + id: characterPopup + enabled: PlasmaKeyboardSettings.characterPopupEnabled + } + + FlickPreviewPopup { + id: flickPreviewPopup + } + + PreeditBubble { + anchors.left: inputPanel.left + anchors.top: inputPanel.top + anchors.topMargin: -implicitHeight - Math.round(8 * BreezeConstants.scaleHint) + inputEngine: root.virtualKeyboardContext ? root.virtualKeyboardContext.inputEngine : null + z: 2 + } + + Rectangle { + id: topSeparator + height: 1 + anchors { + top: parent.top + left: parent.left + right: parent.right + } + opacity: 0.5 + color: BreezeConstants.keyboardTopSeparatorColor + visible: !isFloating && isFullScreenWidth + } + + Keyboard { + id: inputPanel + languagePopup: languagePopup + virtualKeyboardContext: root.virtualKeyboardContext + + padding: (!isFloating && isFullScreenWidth) ? Kirigami.Units.smallSpacing / 2 : Kirigami.Units.largeSpacing + + anchors { + top: parent.top + left: parent.left + } + + function updateKeyboardLayouts() { + if (!root.keyboardController) { + return; + } + + let layoutIds = PlasmaKeyboardSettings.enabledKeyboardLayoutIds; + if (layoutIds.length === 0 && PlasmaKeyboardSettings.enabledLocales.length > 0) { + layoutIds = root.keyboardController.layoutIdsForLocales(PlasmaKeyboardSettings.enabledLocales); + } + root.keyboardController.activeLayoutIds = layoutIds; + } + + Connections { + target: PlasmaKeyboardSettings + function onEnabledKeyboardLayoutIdsChanged() { + inputPanel.updateKeyboardLayouts(); + } + function onEnabledLocalesChanged() { + inputPanel.updateKeyboardLayouts(); + } + } + + Component.onCompleted: { + inputPanel.updateKeyboardLayouts(); + } + } +} diff --git a/src/qml/LanguagePopup.qml b/src/qml/LanguagePopup.qml deleted file mode 100644 index bd6dcd2..0000000 --- a/src/qml/LanguagePopup.qml +++ /dev/null @@ -1,124 +0,0 @@ -/* - SPDX-FileCopyrightText: 2025 Aleix Pol i Gonzalez - - SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL -*/ - -import QtQuick -import QtQuick.Controls as QQC2 -import QtQuick.Layouts -import QtQuick.VirtualKeyboard.Settings -import QtQuick.Templates as T - -import org.kde.kirigami as Kirigami -import org.kde.plasma.keyboard.lib as PlasmaKeyboard - -T.Popup { - id: root - property var style - property var keyboardPanel - - signal showSettings() - - width: languageListView.rowWidth + languageListView.margins * 2 - height: Math.min(languageListView.contentHeight + languageListView.spacing + settingsDelegate.implicitHeight + settingsDelegate.Layout.topMargin, languageListView.rowHeight * 6) - + languageListView.margins * 2 - modal: true - visible: false - - background: PlasmaKeyboard.BreezePopup { - theme: root.style.theme - } - - function show(parentItem, localeList, currentIndex) { - languageListModel.clear() - for (var i in localeList) { - languageListModel.append({localeName: localeList[i], displayName: Qt.locale(localeList[i]).nativeLanguageName}) - } - languageListView.currentIndex = currentIndex - languageListView.positionViewAtIndex(currentIndex, ListView.Center) - - root.x = Qt.binding(() => keyboardPanel.mapFromItem(parentItem, 0, 0).x); - root.y = Qt.binding(() => keyboardPanel.mapFromItem(parentItem, 0, -root.height).y); - - root.visible = true - } - - TextMetrics { - id: languageNameTextMetrics - font { - family: root.style.theme.fontFamily - weight: Font.Light - pixelSize: 44 * root.style.scaleHint - } - text: "X" - } - - contentItem: Item { - clip: true - - ColumnLayout { - anchors.leftMargin: languageListView.margins - anchors.rightMargin: languageListView.margins - anchors.bottomMargin: languageListView.margins - anchors.fill: parent - spacing: 0 - - ListView { - id: languageListView - clip: true - topMargin: languageListView.margins // so clip goes to the edge - bottomMargin: spacing - Layout.fillWidth: true - Layout.fillHeight: true - - readonly property real margins: 20 * style.scaleHint - - readonly property real rowWidth: languageNameTextMetrics.width * 17 - readonly property real rowHeight: languageNameTextMetrics.height + rowPadding * 2 - readonly property real rowPadding: languageNameTextMetrics.height / 4 - - QQC2.ScrollBar.vertical: QQC2.ScrollBar {} - model: ListModel { - id: languageListModel - } - - spacing: root.style.scaleHint * 4 - - delegate: LanguagePopupDelegate { - id: itemDelegate - style: root.style - text: displayName - width: languageListView.rowWidth - height: languageListView.rowHeight - padding: languageListView.rowPadding - - onClicked: { - languageListView.currentIndex = index; - VirtualKeyboardSettings.locale = languageListModel.get(index).localeName; - root.close(); - } - } - } - - Kirigami.Separator { Layout.fillWidth: true } - LanguagePopupDelegate { - id: settingsDelegate - Layout.topMargin: root.style.scaleHint * 4 - Layout.fillWidth: true - - style: root.style - implicitWidth: languageListView.rowWidth - implicitHeight: languageListView.rowHeight - padding: languageListView.rowPadding - - icon.name: "configure" - text: i18n("Settings") - onClicked: { - root.showSettings(); - root.close(); - } - } - } - } -} diff --git a/src/qml/LanguagePopupDelegate.qml b/src/qml/LanguagePopupDelegate.qml deleted file mode 100644 index 37997cd..0000000 --- a/src/qml/LanguagePopupDelegate.qml +++ /dev/null @@ -1,84 +0,0 @@ -/* - SPDX-FileCopyrightText: 2025 Devin Lin - - SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL -*/ - -import QtQuick -import QtQuick.Controls as QQC2 -import QtQuick.Layouts -import QtQuick.VirtualKeyboard -import QtQuick.Templates as T - -import org.kde.kirigami as Kirigami - -T.ItemDelegate { - id: itemDelegate - - property var style - - horizontalPadding: padding - verticalPadding: padding - leftPadding: horizontalPadding - rightPadding: horizontalPadding - topPadding: verticalPadding - bottomPadding: verticalPadding - - highlighted: ListView.isCurrentItem - hoverEnabled: true - - background: Rectangle { - color: { - if (itemDelegate.down) { - return border.color; - } - if (itemDelegate.highlighted || (itemDelegate.hovered && !Kirigami.Settings.tabletMode)) { - return style.theme.popupHighlightColor - } - return 'transparent'; - } - radius: style.theme.buttonRadius - border.color: { - if (itemDelegate.down || itemDelegate.highlighted || (itemDelegate.hovered && !Kirigami.Settings.tabletMode)) { - return style.theme.popupHighlightBorderColor; - } - return 'transparent'; - } - border.width: 1 - } - - contentItem: Item { - anchors.fill: parent - width: itemDelegate.width - - RowLayout { - id: row - anchors.fill: parent - anchors.leftMargin: itemDelegate.leftPadding - anchors.rightMargin: itemDelegate.rightPadding - spacing: 12 * style.scaleHint - - Kirigami.Icon { - id: icon - - visible: itemDelegate.icon.name - source: itemDelegate.icon.name - implicitWidth: 44 * style.scaleHint - implicitHeight: 44 * style.scaleHint - } - - QQC2.Label { - text: itemDelegate.text - font { - family: itemDelegate.style.theme.fontFamily - weight: Font.Light - pixelSize: Math.round(44 * itemDelegate.style.scaleHint) - } - Layout.alignment: Qt.AlignVCenter - Layout.fillWidth: true - Layout.maximumWidth: itemDelegate.width - itemDelegate.leftPadding - itemDelegate.rightPadding - (icon.visible ? icon.width + row.spacing : 0) - elide: Text.ElideRight - } - } - } -} diff --git a/src/qml/main.qml b/src/qml/main.qml index 703f675..04696e6 100644 --- a/src/qml/main.qml +++ b/src/qml/main.qml @@ -6,13 +6,10 @@ */ import QtQuick -import QtQuick.VirtualKeyboard -import QtQuick.VirtualKeyboard.Settings import org.kde.plasma.keyboard -import org.kde.plasma.keyboard.lib as PlasmaKeyboard - -import org.kde.kirigami as Kirigami +import org.kde.plasma.keyboard.virtualkeyboard +import org.kde.plasma.keyboard.virtualkeyboard.components InputPanelWindow { id: root @@ -20,136 +17,62 @@ InputPanelWindow { width: Screen.width color: 'transparent' - onVisibleChanged: { - if (!visible) { - // Reset keyboard navigation when hidden - // Note: keyboard property is internal Qt API - if (inputPanel.keyboard.navigationModeActive) { - inputPanel.keyboard.navigationModeActive = false; - } + interactiveRegion: Qt.rect(keyboardPanel.x, + keyboardPanel.y, + keyboardPanel.width, + keyboardPanel.height) - // Close language dialog - languageDialog.close(); + property alias inputMethodConnection: inputMethodConnection + property alias virtualKeyboardContext: inputMethodConnection.virtualKeyboardContext + + // Called by keys + property alias alternativeKeysPopupItem: keyboardPanel.alternativeKeysPopup + property alias characterPopupItem: keyboardPanel.characterPopup + property alias flickPreviewPopupItem: keyboardPanel.flickPreviewPopup + property alias languagePopupItem: keyboardPanel.languagePopup + + onVisibleChanged: { + keyboardPanel.inputPanel.resetNavigation(); + if (visible) { + keyboardPanel.keyboardController.symbolMode = false; + } else { + if (keyboardPanel.languagePopup) { + keyboardPanel.languagePopup.close(); + } } } - InputListenerItem { - id: thing - focus: true - engine: inputPanel.InputContext.inputEngine + InputMethodConnection { + id: inputMethodConnection + window: root + keyboardNavigationAvailable: keyboardPanel.inputPanel.navigationAvailable + keyboardNavigationActive: keyboardPanel.inputPanel.navigationModeActive + } - keyboardNavigationActive: inputPanel.keyboard.navigationModeActive - - onKeyNavigationPressed: (key) => { - // HACK: invoke the Qt VirtualKeyboard keyboard navigation feature ourselves - // See https://github.com/qt/qtvirtualkeyboard/blob/6d810ac41df96f1ad984f56e17f16860bec2abbf/src/virtualkeyboard/qvirtualkeyboardinputcontext_p.h#L110 - inputPanel.InputContext.priv.navigationKeyPressed(key, false); + Connections { + target: root.inputMethodConnection + function onKeyNavigationPressed(key) { + keyboardPanel.inputPanel.handleNavigationPressed(key); } - onKeyNavigationReleased: (key) => { - // HACK: invoke the Qt VirtualKeyboard keyboard navigation feature ourselves - inputPanel.InputContext.priv.navigationKeyReleased(key, false); + function onKeyNavigationReleased(key) { + keyboardPanel.inputPanel.handleNavigationReleased(key); } } // Unified overlay system for diacritics, emoji, text expansion, etc. OverlayWindow { id: overlayWindow - controller: thing.overlayController - onCandidateSelected: (index) => thing.overlayController.commitCandidate(index) + controller: root.inputMethodConnection.overlayController + onCandidateSelected: (index) => { + Feedback.play(Feedback.SelectionCommit); + root.inputMethodConnection.overlayController.commitCandidate(index); + } } - interactiveRegion: Qt.rect(panelWrapper.x, panelWrapper.y, panelWrapper.width, panelWrapper.height) - - Kirigami.ShadowedRectangle { - id: panelWrapper - - LanguagePopup { - id: languageDialog - style: inputPanel.keyboard.style - keyboardPanel: inputPanel - - onShowSettings: root.showSettings() - } - - // Whether the panel takes the full width of the screen - readonly property bool isFullScreenWidth: PlasmaKeyboardSettings.panelFillScreenWidth - - color: PlasmaKeyboard.BreezeConstants.keyboardBackgroundColor - - // Provide shadow and radius when the keyboard is detached from edges - corners { - // The window isn't floating, so only curve the top - bottomLeftRadius: Kirigami.Units.cornerRadius - bottomRightRadius: Kirigami.Units.cornerRadius - topLeftRadius: isFullScreenWidth ? 0 : Kirigami.Units.cornerRadius - topRightRadius: isFullScreenWidth ? 0 : Kirigami.Units.cornerRadius - } - shadow { - size: isFullScreenWidth ? 0 : 16 - color: Qt.rgba(0, 0, 0, 0.3) - } - - // Starting x and y centers the panel on the bottom - x: (root.width / 2) - (width / 2) - y: root.height - height - - // Padding for background corners and panel drag area - readonly property real padding: isFullScreenWidth ? 0 : Kirigami.Units.largeSpacing - - // Never let width & height to be 0, otherwise it can cause problems for setting interactiveRegion - width: inputPanel.width > 0 ? (inputPanel.width + padding * 2) : 100 - height: inputPanel.height > 0 ? (inputPanel.height + padding * 2) : 100 - - InputPanel { - id: inputPanel - anchors { - top: parent.top - topMargin: parent.padding - left: parent.left - leftMargin: parent.padding - } - - // height is calculated by InputPanel - width: inputPanel.keyboard.style ? inputPanel.keyboard.style.aspectRatio * inputPanel.keyboard.style.targetKeyboardHeight : 0 - - focusPolicy: Qt.NoFocus - externalLanguageSwitchEnabled: true - onExternalLanguageSwitch: (localeList, currentIndex) => { - languageDialog.show(inputPanel.keyboard.activeKey, localeList, currentIndex) - } - - function updateLocales() { - if (PlasmaKeyboardSettings.enabledLocales.length === 0) { - // If there are no enabled locales, set it to the current locale - // NOTE: If Qt.locale().name is not valid, then all keyboard layouts will be shown. - let locale = Qt.locale().name; - if (locale === "C") { - locale = "en_US"; - } - VirtualKeyboardSettings.activeLocales = [locale]; - } else { - VirtualKeyboardSettings.activeLocales = PlasmaKeyboardSettings.enabledLocales; - } - } - - Connections { - target: VirtualKeyboardSettings - function onAvailableLocalesChanged() { - inputPanel.updateLocales(); - } - } - - Connections { - target: PlasmaKeyboardSettings - function onEnabledLocalesChanged() { - inputPanel.updateLocales(); - } - } - - Component.onCompleted: { - VirtualKeyboardSettings.styleName = "Breeze"; - inputPanel.updateLocales(); - } - } + KeyboardPanel { + id: keyboardPanel + hostWindow: root + virtualKeyboardContext: root.virtualKeyboardContext + onShowSettingsRequested: root.showSettings(); } } diff --git a/src/qmlplugin/BreezeKeyPanel.qml b/src/qmlplugin/BreezeKeyPanel.qml deleted file mode 100644 index 0078f80..0000000 --- a/src/qmlplugin/BreezeKeyPanel.qml +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-FileCopyrightText: 2025 Devin Lin -// SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL - -import QtQuick -import QtQuick.Controls as QQC2 -import QtQuick.VirtualKeyboard -import QtQuick.VirtualKeyboard.Styles - -import org.kde.plasma.keyboard -import org.kde.kirigami as Kirigami - -KeyPanel { - id: root - - default property alias contentItem: visualContainer.contentItem - - property alias background: visualContainer.background - - property real padding: BreezeConstants.keyBackgroundMargin - - property real radius: BreezeConstants.buttonRadius - - property color color: { - if (control && control.pressed) { - return BreezeConstants.normalKeyPressedBackgroundColor; - } else if (control && control.highlighted) { - return BreezeConstants.highlightedKeyBackgroundColor; - } - return BreezeConstants.normalKeyBackgroundColor; - } - - soundEffect: PlasmaKeyboardSettings.soundEnabled ? Qt.resolvedUrl('qrc:///sounds/keyboard_tick2_quiet.wav') : '' - - QQC2.Control { - id: visualContainer - anchors.fill: parent - anchors.margins: root.padding - - background: Kirigami.ShadowedRectangle { - color: root.color - radius: root.radius - - // Shadow - shadow.color: Qt.rgba(0, 0, 0, 0.2) - shadow.size: 3 - shadow.yOffset: 1 - } - } - - // Implement key vibration - Connections { - target: root.control - function onPressedChanged() { - if (root.control.pressed && PlasmaKeyboardSettings.vibrationEnabled) { - Vibration.vibrate(PlasmaKeyboardSettings.vibrationMs); - } - } - } -} diff --git a/src/qmlplugin/CMakeLists.txt b/src/qmlplugin/CMakeLists.txt deleted file mode 100644 index 6196846..0000000 --- a/src/qmlplugin/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -# SPDX-FileCopyrightText: 2025 Devin Lin -# SPDX-License-Identifier: BSD-2-Clause - -ecm_add_qml_module(keyboardlib URI org.kde.plasma.keyboard.lib GENERATE_PLUGIN_SOURCE DEPENDENCIES QtQuick) - -set_source_files_properties( - BreezeConstants.qml - PROPERTIES - QT_QML_SINGLETON_TYPE TRUE -) - -ecm_target_qml_sources(keyboardlib SOURCES - BreezeKeyPanel.qml - BreezeConstants.qml - BreezePopup.qml -) - -target_link_libraries(keyboardlib - PUBLIC - Qt::Core - PRIVATE - Qt::Qml - Qt::Gui - Qt::Quick -) - -ecm_finalize_qml_module(keyboardlib) diff --git a/src/styles/CMakeLists.txt b/src/styles/CMakeLists.txt deleted file mode 100644 index 7a4258c..0000000 --- a/src/styles/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -# SPDX-FileCopyrightText: 2025 Devin Lin -# SPDX-License-Identifier: GPL-2.0-or-later - -ecm_add_qml_module(breezestyle URI QtQuick.VirtualKeyboard.Styles.Breeze GENERATE_PLUGIN_SOURCE DEPENDENCIES QtQuick) - -ecm_target_qml_sources(breezestyle SOURCES - breeze/style.qml -) - -target_link_libraries(breezestyle - PUBLIC - Qt::Core - PRIVATE - Qt::Qml - Qt::Quick -) - -ecm_finalize_qml_module(breezestyle) diff --git a/src/styles/breeze/style.qml b/src/styles/breeze/style.qml deleted file mode 100644 index 3c31aef..0000000 --- a/src/styles/breeze/style.qml +++ /dev/null @@ -1,1075 +0,0 @@ -// SPDX-FileCopyrightText: 2016 The Qt Company Ltd. -// SPDX-FileCopyrightText: 2025 Devin Lin -// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only - -import QtQuick -import QtQuick.Layouts -import QtQuick.VirtualKeyboard -import QtQuick.VirtualKeyboard.Styles -import QtQuick.Controls as QQC2 -import QtQuick.Window -import QtQuick.Effects - -import org.kde.kirigami as Kirigami - -import org.kde.plasma.keyboard -import org.kde.plasma.keyboard.lib as PlasmaKeyboard - -KeyboardStyle { - id: currentStyle - readonly property bool compactSelectionList: [InputEngine.InputMode.Pinyin, InputEngine.InputMode.Cangjie, InputEngine.InputMode.Zhuyin].indexOf(InputContext.inputEngine.inputMode) !== -1 - - property Binding scaleHintBinding: Binding { - target: PlasmaKeyboard.BreezeConstants - property: 'scaleHint' - value: currentStyle.scaleHint - } - - property var theme: PlasmaKeyboard.BreezeConstants - - Kirigami.Theme.inherit: false - Kirigami.Theme.colorSet: Kirigami.Theme.Window - - readonly property string inputLocale: InputContext.locale - - property real inputLocaleIndicatorOpacity: 1.0 - property Timer inputLocaleIndicatorHighlightTimer: Timer { - interval: 1000 - onTriggered: inputLocaleIndicatorOpacity = 0.5 - } - onInputLocaleChanged: { - inputLocaleIndicatorOpacity = 1.0 - inputLocaleIndicatorHighlightTimer.restart() - } - - property Component component_settingsIcon: Component { - Kirigami.Icon { - implicitWidth: 80 * theme.keyIconScale - implicitHeight: 80 * theme.keyIconScale - source: "settings-configure" - } - } - - // Always have the keyboard panel be 30% of the screen height, or 150px (whichever is larger) - readonly property real targetKeyboardHeight: Math.max(Screen.height * 0.3, 150) - - // The value to multiply the height by to get the width - readonly property real aspectRatio: { - // Ratio to just fill the screen width - const fillScreenWidth = Screen.width / targetKeyboardHeight; - if (PlasmaKeyboardSettings.panelFillScreenWidth) { - return fillScreenWidth; - } - - const targetAspectRatio = 3.0; // Target width = 3 * height - return Math.min(fillScreenWidth, targetAspectRatio); - } - - // Calculate width based on the height so that the keyboard height is always targetKeyboardHeight - keyboardDesignWidth: aspectRatio * keyboardDesignHeight; - keyboardDesignHeight: { - if (Screen.width < 500) { - // Phone mode - return 800; - } else if (Screen.width < 1200) { - // Wider - return 600; - } - // Widest - return 700; - } - - // The width should never be > 6 times height - readonly property real maxWidthToHeightRatio: 6 - - keyboardRelativeLeftMargin: { - if (keyboardDesignWidth > keyboardDesignHeight * maxWidthToHeightRatio) { - // Cap keyboard width if it's too wide - const extraWidth = keyboardDesignWidth - (keyboardDesignHeight * maxWidthToHeightRatio); - return (extraWidth / 2) / keyboardDesignWidth; - } - return 6 / keyboardDesignWidth; - } - keyboardRelativeRightMargin: keyboardRelativeLeftMargin - keyboardRelativeTopMargin: 6 / keyboardDesignHeight - keyboardRelativeBottomMargin: 6 / keyboardDesignHeight - - keyboardBackground: Rectangle { - color: theme.keyboardBackgroundColor - } - - keyPanel: PlasmaKeyboard.BreezeKeyPanel { - id: keyPanel - - Item { - id: keyContent - - QQC2.Label { - id: keySmallText - text: control.smallText - visible: control.smallTextVisible - color: theme.keySmallTextColor - anchors.right: parent.right - anchors.top: parent.top - anchors.margins: theme.keyContentMargin / 3 - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 30 * scaleHint - capitalization: control.uppercased ? Font.AllUppercase : Font.MixedCase - } - } - Loader { - id: loader_settingsIcon - anchors.right: parent.right - anchors.top: parent.top - anchors.margins: theme.keyContentMargin / 3 - } - QQC2.Label { - id: keyText - text: control.displayText - color: theme.keyTextColor - horizontalAlignment: Text.AlignHCenter - verticalAlignment: control.displayText.length > 1 ? Text.AlignVCenter : Text.AlignBottom - anchors.centerIn: parent - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 60 * scaleHint - capitalization: control.uppercased ? Font.AllUppercase : Font.MixedCase - } - } - states: [ - State { - when: control.smallText === "\u2699" && control.smallTextVisible - PropertyChanges { - target: keySmallText - visible: false - } - PropertyChanges { - target: loader_settingsIcon - sourceComponent: component_settingsIcon - } - } - ] - } - states: [ - State { - name: "disabled" - when: !control.enabled - PropertyChanges { - target: keyContent - opacity: 0.75 - } - PropertyChanges { - target: keyText - opacity: 0.05 - } - } - ] - } - - backspaceKeyPanel: PlasmaKeyboard.BreezeKeyPanel { - id: backspaceKeyPanel - - Item { - Kirigami.Icon { - id: backspaceKeyIcon - anchors.centerIn: parent - implicitHeight: 88 * theme.keyIconScale - implicitWidth: implicitHeight - source: "edit-clear-symbolic" - } - } - - states: [ - State { - name: "disabled" - when: !control.enabled - PropertyChanges { - target: backspaceKeyPanel.background - opacity: 0.8 - } - PropertyChanges { - target: backspaceKeyIcon - opacity: 0.2 - } - } - ] - } - - languageKeyPanel: PlasmaKeyboard.BreezeKeyPanel { - id: languageKeyPanel - - Item { - Kirigami.Icon { - id: languageKeyIcon - anchors.centerIn: parent - implicitHeight: 96 * theme.keyIconScale - source: "globe" - } - } - - states: [ - State { - name: "disabled" - when: !control.enabled - PropertyChanges { - target: languageKeyPanel.background - opacity: 0.8 - } - PropertyChanges { - target: languageKeyIcon - opacity: 0.2 - } - } - ] - } - - enterKeyPanel: PlasmaKeyboard.BreezeKeyPanel { - id: enterKeyPanel - - Item { - id: enterKeyBackground - Kirigami.Icon { - id: enterKeyIcon - visible: enterKeyText.text.length === 0 - anchors.centerIn: parent - readonly property size enterKeyIconSize: { - switch (control.actionId) { - case EnterKeyAction.Go: - case EnterKeyAction.Send: - case EnterKeyAction.Next: - case EnterKeyAction.Done: - return Qt.size(170, 119) - case EnterKeyAction.Search: - return Qt.size(148, 148) - default: - return Qt.size(211, 80) - } - } - implicitHeight: enterKeyIconSize.height * theme.keyIconScale - source: { - switch (control.actionId) { - case EnterKeyAction.Go: - case EnterKeyAction.Send: - case EnterKeyAction.Next: - case EnterKeyAction.Done: - return "checkmark" - case EnterKeyAction.Search: - return "search-symbolic" - default: - return "keyboard-enter-symbolic" - } - } - } - QQC2.Label { - id: enterKeyText - visible: text.length !== 0 - text: control.actionId !== EnterKeyAction.None ? control.displayText : "" - clip: true - fontSizeMode: Text.HorizontalFit - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - color: theme.keyTextColor - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 50 * scaleHint - capitalization: Font.AllUppercase - } - anchors.fill: parent - anchors.margins: Math.round(42 * scaleHint) - } - } - - states: [ - State { - name: "disabled" - when: !control.enabled - PropertyChanges { - target: enterKeyPanel.background - opacity: 0.8 - } - PropertyChanges { - target: enterKeyIcon - opacity: 0.2 - } - PropertyChanges { - target: enterKeyText - opacity: 0.2 - } - } - ] - } - - hideKeyPanel: PlasmaKeyboard.BreezeKeyPanel { - id: hideKeyPanel - - Item { - Kirigami.Icon { - id: hideKeyIcon - anchors.centerIn: parent - implicitHeight: 96 * theme.keyIconScale - source: "input-keyboard-virtual-hide-symbolic" - } - } - - states: [ - State { - name: "disabled" - when: !control.enabled - PropertyChanges { - target: hideKeyPanel.background - opacity: 0.8 - } - PropertyChanges { - target: hideKeyIcon - opacity: 0.2 - } - } - ] - } - - shiftKeyPanel: PlasmaKeyboard.BreezeKeyPanel { - id: shiftKeyPanel - - Item { - Kirigami.Icon { - id: shiftKeyIcon - anchors.centerIn: parent - implicitHeight: 134 * theme.keyIconScale - source: { - if (InputContext.capsLockActive) { - return "keyboard-caps-locked-symbolic"; - } else if (InputContext.shiftActive) { - return "keyboard-caps-enabled-symbolic"; - } - return "keyboard-caps-disabled-symbolic"; - } - } - } - - states: [ - State { - name: "capsLockActive" - when: InputContext.capsLockActive - PropertyChanges { - target: shiftKeyPanel - color: theme.capsLockKeyAccentColor - } - }, - State { - name: "disabled" - when: !control.enabled - PropertyChanges { - target: shiftKeyPanel.background - opacity: 0.8 - } - PropertyChanges { - target: shiftKeyIcon - opacity: 0.2 - } - } - ] - } - - spaceKeyPanel: PlasmaKeyboard.BreezeKeyPanel { - id: spaceKeyPanel - - Item { - QQC2.Label { - id: spaceKeyText - anchors.centerIn: parent - text: Qt.locale(InputContext.locale).nativeLanguageName - color: theme.keyTextColor - opacity: inputLocaleIndicatorOpacity - Behavior on opacity { PropertyAnimation { duration: 250 } } - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 35 * scaleHint - } - } - } - - states: [ - State { - name: "disabled" - when: !control.enabled - PropertyChanges { - target: spaceKeyBackground - opacity: 0.8 - } - } - ] - } - - symbolKeyPanel: PlasmaKeyboard.BreezeKeyPanel { - id: symbolKeyPanel - - Item { - QQC2.Label { - id: symbolKeyText - anchors.centerIn: parent - text: control.displayText - color: theme.keyTextColor - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 40 * scaleHint - capitalization: Font.AllUppercase - } - } - } - - states: [ - State { - name: "disabled" - when: !control.enabled - PropertyChanges { - target: symbolKeyPanel.background - opacity: 0.8 - } - PropertyChanges { - target: symbolKeyText - opacity: 0.2 - } - } - ] - } - - modeKeyPanel: PlasmaKeyboard.BreezeKeyPanel { - id: modeKeyPanel - - Item { - id: modeKeyBackground - QQC2.Label { - id: modeKeyText - text: control.displayText - color: theme.keyTextColor - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - anchors.fill: parent - anchors.margins: theme.keyContentMargin - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 40 * scaleHint - capitalization: Font.AllUppercase - } - } - Rectangle { - id: modeKeyIndicator - implicitHeight: parent.height * 0.1 - anchors.left: parent.left - anchors.right: parent.right - anchors.bottom: parent.bottom - anchors.leftMargin: parent.width * 0.4 - anchors.rightMargin: parent.width * 0.4 - anchors.bottomMargin: parent.height * 0.12 - color: theme.modeKeyAccentColor - radius: theme.buttonRadius - visible: control.mode - } - } - - states: [ - State { - name: "disabled" - when: !control.enabled - PropertyChanges { - target: modeKeyPanel.background - opacity: 0.8 - } - PropertyChanges { - target: modeKeyText - opacity: 0.2 - } - } - ] - } - - handwritingKeyPanel: PlasmaKeyboard.BreezeKeyPanel { - id: handwritingKeyPanel - - Item { - Kirigami.Icon { - id: hwrKeyIcon - anchors.centerIn: parent - implicitHeight: 127 * theme.keyIconScale - source: (keyboard.handwritingMode ? "edit-select-text-symbolic" : "draw-freehand-symbolic") - } - } - - states: [ - State { - name: "pressed" - when: control.pressed - PropertyChanges { - target: handwritingKeyPanel.background - opacity: 0.80 - } - PropertyChanges { - target: hwrKeyIcon - opacity: 0.6 - } - }, - State { - name: "disabled" - when: !control.enabled - PropertyChanges { - target: handwritingKeyPanel.background - opacity: 0.8 - } - PropertyChanges { - target: hwrKeyIcon - opacity: 0.2 - } - } - ] - } - - characterPreviewMargin: 0 - characterPreviewDelegate: Item { - property string text - property string flickLeft - property string flickTop - property string flickRight - property string flickBottom - readonly property bool flickKeysSet: flickLeft || flickTop || flickRight || flickBottom - readonly property bool flickKeysVisible: text && flickKeysSet && - text !== flickLeft && text !== flickTop && text !== flickRight && text !== flickBottom - id: characterPreview - PlasmaKeyboard.BreezePopup { - id: characterPreviewBackground - theme: currentStyle.theme - anchors.fill: parent - readonly property int largeTextHeight: Math.round(height / 3 * 2) - readonly property int smallTextHeight: Math.round(height / 3) - readonly property int smallTextMargin: Math.round(3 * scaleHint) - - QQC2.Label { - id: characterPreviewText - color: theme.popupTextColor - text: characterPreview.text - fontSizeMode: Text.VerticalFit - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - anchors.horizontalCenter: parent.horizontalCenter - anchors.verticalCenter: parent.verticalCenter - height: characterPreviewBackground.largeTextHeight - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 82 * scaleHint - } - } - QQC2.Label { - color: theme.popupTextColor - text: characterPreview.flickLeft - visible: characterPreview.flickKeysVisible - opacity: 0.8 - fontSizeMode: Text.VerticalFit - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - anchors.left: parent.left - anchors.leftMargin: characterPreviewBackground.smallTextMargin - anchors.verticalCenter: parent.verticalCenter - height: characterPreviewBackground.smallTextHeight - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 62 * scaleHint - } - } - QQC2.Label { - color: theme.popupTextColor - text: characterPreview.flickTop - visible: characterPreview.flickKeysVisible - opacity: 0.8 - fontSizeMode: Text.VerticalFit - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - anchors.top: parent.top - anchors.topMargin: characterPreviewBackground.smallTextMargin - anchors.horizontalCenter: parent.horizontalCenter - height: characterPreviewBackground.smallTextHeight - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 62 * scaleHint - } - } - QQC2.Label { - color: theme.popupTextColor - text: characterPreview.flickRight - visible: characterPreview.flickKeysVisible - opacity: 0.8 - fontSizeMode: Text.VerticalFit - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - anchors.right: parent.right - anchors.rightMargin: characterPreviewBackground.smallTextMargin - anchors.verticalCenter: parent.verticalCenter - height: characterPreviewBackground.smallTextHeight - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 62 * scaleHint - } - } - QQC2.Label { - color: theme.popupTextColor - text: characterPreview.flickBottom - visible: characterPreview.flickKeysVisible - opacity: 0.8 - fontSizeMode: Text.VerticalFit - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - anchors.bottom: parent.bottom - anchors.bottomMargin: characterPreviewBackground.smallTextMargin - anchors.horizontalCenter: parent.horizontalCenter - height: characterPreviewBackground.smallTextHeight - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 62 * scaleHint - } - } - states: State { - name: "flickKeysVisible" - when: characterPreview.flickKeysVisible - PropertyChanges { - target: characterPreviewText - height: characterPreviewBackground.smallTextHeight - } - } - } - } - - alternateKeysListItemWidth: 120 * scaleHint - alternateKeysListItemHeight: 170 * scaleHint - alternateKeysListDelegate: Item { - id: alternateKeysListItem - width: alternateKeysListItemWidth - height: alternateKeysListItemHeight - QQC2.Label { - id: listItemText - text: model.text - color: alternateKeysListItem.ListView.isCurrentItem ? theme.popupTextSelectedColor : theme.popupTextColor - opacity: 0.8 - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 60 * scaleHint - } - anchors.centerIn: parent - } - states: State { - name: "current" - when: alternateKeysListItem.ListView.isCurrentItem - PropertyChanges { - target: listItemText - opacity: 1 - } - } - } - alternateKeysListHighlight: Rectangle { - color: theme.popupHighlightColor - radius: theme.buttonRadius - border.color: theme.popupHighlightBorderColor - border.width: 1 - } - alternateKeysListBackground: Item { - PlasmaKeyboard.BreezePopup { - theme: currentStyle.theme - readonly property real margin: 20 * scaleHint - x: -margin - y: -margin - width: parent.width + 2 * margin - height: parent.height + 2 * margin - } - } - - selectionListHeight: 85 * scaleHint - selectionListDelegate: SelectionListItem { - id: selectionListItem - width: Math.round(selectionListLabel.width + selectionListLabel.anchors.leftMargin * 2) - QQC2.Label { - id: selectionListLabel - anchors.left: parent.left - anchors.leftMargin: Math.round((compactSelectionList ? 50 : 140) * scaleHint) - anchors.verticalCenter: parent.verticalCenter - text: decorateText(display, wordCompletionLength) - color: theme.selectionListTextColor - opacity: 0.9 - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 44 * scaleHint - } - function decorateText(text, wordCompletionLength) { - if (wordCompletionLength > 0) { - return text.slice(0, -wordCompletionLength) + '' + text.slice(-wordCompletionLength) + '' - } - return text - } - } - Rectangle { - id: selectionListSeparator - width: 4 * scaleHint - height: 36 * scaleHint - radius: 2 - color: theme.selectionListSeparatorColor - anchors.verticalCenter: parent.verticalCenter - anchors.right: parent.left - } - states: State { - name: "current" - when: selectionListItem.ListView.isCurrentItem - PropertyChanges { - target: selectionListLabel - opacity: 1 - } - } - } - selectionListBackground: Rectangle { - color: theme.selectionListBackgroundColor - } - selectionListAdd: Transition { - NumberAnimation { property: "y"; from: wordCandidateView.height; duration: 200 } - NumberAnimation { property: "opacity"; from: 0; to: 1; duration: 200 } - } - selectionListRemove: Transition { - NumberAnimation { property: "y"; to: -wordCandidateView.height; duration: 200 } - NumberAnimation { property: "opacity"; to: 0; duration: 200 } - } - - navigationHighlight: Rectangle { - color: theme.navigationHighlightColor - border.color: theme.navigationHighlightBorderColor - border.width: 3 - radius: theme.buttonRadius + border.width // Adjust due to border width - } - - traceInputKeyPanelDelegate: TraceInputKeyPanel { - id: traceInputKeyPanel - traceMargins: theme.keyBackgroundMargin - Rectangle { - id: traceInputKeyPanelBackground - radius: theme.buttonRadius - color: theme.normalKeyBackgroundColor - anchors.fill: traceInputKeyPanel - anchors.margins: theme.keyBackgroundMargin - QQC2.Label { - id: hwrInputModeIndicator - visible: control.patternRecognitionMode === InputEngine.PatternRecognitionMode.Handwriting - text: { - switch (InputContext.inputEngine.inputMode) { - case InputEngine.InputMode.Numeric: - if (["ar", "fa"].indexOf(InputContext.locale.substring(0, 2)) !== -1) - return "\u0660\u0661\u0662" - // Fallthrough - case InputEngine.InputMode.Dialable: - return "123" - case InputEngine.InputMode.Greek: - return "ΑΒΓ" - case InputEngine.InputMode.Cyrillic: - return "АБВ" - case InputEngine.InputMode.Arabic: - if (InputContext.locale.substring(0, 2) === "fa") - return "\u0627\u200C\u0628\u200C\u067E" - return "\u0623\u200C\u0628\u200C\u062C" - case InputEngine.InputMode.Hebrew: - return "\u05D0\u05D1\u05D2" - case InputEngine.InputMode.ChineseHandwriting: - return "中文" - case InputEngine.InputMode.JapaneseHandwriting: - return "日本語" - case InputEngine.InputMode.KoreanHandwriting: - return "한국어" - case InputEngine.InputMode.Thai: - return "กขค" - default: - return "Abc" - } - } - color: theme.keyTextColor - anchors.left: parent.left - anchors.top: parent.top - anchors.margins: theme.keyContentMargin - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 44 * scaleHint - capitalization: { - if (InputContext.capsLockActive) - return Font.AllUppercase - if (InputContext.shiftActive) - return Font.MixedCase - return Font.AllLowercase - } - } - } - } - Canvas { - id: traceInputKeyGuideLines - anchors.fill: traceInputKeyPanelBackground - opacity: 0.1 - onPaint: { - var ctx = getContext("2d") - ctx.lineWidth = 1 - ctx.strokeStyle = Qt.rgba(0xFF, 0xFF, 0xFF) - ctx.clearRect(0, 0, width, height) - var i - var margin = Math.round(30 * scaleHint) - if (control.horizontalRulers) { - for (i = 0; i < control.horizontalRulers.length; i++) { - ctx.beginPath() - var y = Math.round(control.horizontalRulers[i]) - var rightMargin = Math.round(width - margin) - if (i + 1 === control.horizontalRulers.length) { - ctx.moveTo(margin, y) - ctx.lineTo(rightMargin, y) - } else { - var dashLen = Math.round(20 * scaleHint) - for (var dash = margin, dashCount = 0; - dash < rightMargin; dash += dashLen, dashCount++) { - if ((dashCount & 1) === 0) { - ctx.moveTo(dash, y) - ctx.lineTo(Math.min(dash + dashLen, rightMargin), y) - } - } - } - ctx.stroke() - } - } - if (control.verticalRulers) { - for (i = 0; i < control.verticalRulers.length; i++) { - ctx.beginPath() - ctx.moveTo(control.verticalRulers[i], margin) - ctx.lineTo(control.verticalRulers[i], Math.round(height - margin)) - ctx.stroke() - } - } - } - Connections { - target: control - function onHorizontalRulersChanged() { traceInputKeyGuideLines.requestPaint() } - function onVerticalRulersChanged() { traceInputKeyGuideLines.requestPaint() } - } - } - } - - traceCanvasDelegate: TraceCanvas { - id: traceCanvas - onAvailableChanged: { - if (!available) - return - var ctx = getContext("2d") - if (parent.canvasType === "fullscreen") { - ctx.lineWidth = 10 - ctx.strokeStyle = Qt.rgba(0, 0, 0) - } else { - ctx.lineWidth = 10 * scaleHint - ctx.strokeStyle = Qt.rgba(0xFF, 0xFF, 0xFF) - } - ctx.lineCap = "round" - ctx.fillStyle = ctx.strokeStyle - } - autoDestroyDelay: 800 - onTraceChanged: if (trace === null) opacity = 0 - Behavior on opacity { PropertyAnimation { easing.type: Easing.OutCubic; duration: 150 } } - } - - popupListDelegate: SelectionListItem { - property real cursorAnchor: popupListLabel.x + popupListLabel.width - id: popupListItem - width: popupListLabel.width + popupListLabel.anchors.leftMargin * 2 - height: popupListLabel.height + popupListLabel.anchors.topMargin * 2 - QQC2.Label { - id: popupListLabel - anchors.left: parent.left - anchors.top: parent.top - anchors.leftMargin: popupListLabel.height / 2 - anchors.topMargin: popupListLabel.height / 3 - text: decorateText(display, wordCompletionLength) - color: theme.popupTextColor - opacity: 0.8 - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: Qt.inputMethod.cursorRectangle.height * 0.8 - } - function decorateText(text, wordCompletionLength) { - if (wordCompletionLength > 0) { - return text.slice(0, -wordCompletionLength) + '' + text.slice(-wordCompletionLength) + '' - } - return text - } - } - states: State { - name: "current" - when: popupListItem.ListView.isCurrentItem - PropertyChanges { - target: popupListLabel - opacity: 1.0 - } - } - } - - popupListBackground: PlasmaKeyboard.BreezePopup { - theme: currentStyle.theme - } - - popupListAdd: Transition {} - - popupListRemove: Transition {} - - languagePopupListEnabled: true - - languageListDelegate: SelectionListItem { - id: languageListItem - width: languageNameTextMetrics.width * 17 - height: languageNameTextMetrics.height + languageListLabel.anchors.topMargin + languageListLabel.anchors.bottomMargin - QQC2.Label { - id: languageListLabel - anchors.left: parent.left - anchors.top: parent.top - anchors.leftMargin: languageNameTextMetrics.height / 2 - anchors.rightMargin: anchors.leftMargin - anchors.topMargin: languageNameTextMetrics.height / 3 - anchors.bottomMargin: anchors.topMargin - text: languageNameFormatter.elidedText - color: theme.popupTextColor - opacity: 0.8 - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 44 * scaleHint - } - } - TextMetrics { - id: languageNameTextMetrics - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 44 * scaleHint - } - text: "X" - } - TextMetrics { - id: languageNameFormatter - font { - family: theme.fontFamily - weight: Font.Light - pixelSize: 44 * scaleHint - } - elide: Text.ElideRight - elideWidth: languageListItem.width - languageListLabel.anchors.leftMargin - languageListLabel.anchors.rightMargin - text: displayName - } - states: State { - name: "current" - when: languageListItem.ListView.isCurrentItem - PropertyChanges { - target: languageListLabel - opacity: 1 - } - } - } - - languageListHighlight: Rectangle { - color: theme.popupHighlightColor - radius: theme.buttonRadius - border.color: theme.popupHighlightBorderColor - border.width: 1 - } - - languageListBackground: Item { - PlasmaKeyboard.BreezePopup { - theme: currentStyle.theme - readonly property real backgroundMargin: 20 * scaleHint - x: -backgroundMargin - y: -backgroundMargin - width: parent.width + 2 * backgroundMargin - height: parent.height + 2 * backgroundMargin - } - } - - languageListAdd: Transition { - // NumberAnimation { property: "opacity"; from: 0; to: 1.0; duration: 200 } - } - - languageListRemove: Transition { - // NumberAnimation { property: "opacity"; to: 0; duration: 200 } - } - - selectionHandle: Kirigami.Icon { - implicitWidth: 20 - source: "selection-end-symbolic" // TODO: better icon? - } - - fullScreenInputContainerBackground: Rectangle { - color: "#FFF" - } - - fullScreenInputBackground: Rectangle { - color: "#FFF" - } - - fullScreenInputMargins: Math.round(15 * scaleHint) - - fullScreenInputPadding: Math.round(30 * scaleHint) - - fullScreenInputCursor: Rectangle { - width: 1 - color: "#000" - visible: parent.blinkStatus - } - - fullScreenInputFont.pixelSize: 58 * scaleHint - - functionPopupListDelegate: Item { - id: functionPopupListItem - readonly property real iconMargin: 40 * scaleHint - readonly property real iconWidth: 96 * theme.keyIconScale - readonly property real iconHeight: 96 * theme.keyIconScale - width: iconWidth + 2 * iconMargin - height: iconHeight + 2 * iconMargin - Kirigami.Icon { - id: functionIcon - anchors.centerIn: parent - implicitHeight: iconHeight - source: { - switch (keyboardFunction) { - case QtVirtualKeyboard.KeyboardFunction.HideInputPanel: - return "input-keyboard-virtual-hide-symbolic" - case QtVirtualKeyboard.KeyboardFunction.ChangeLanguage: - return "globe-symbolic" - case QtVirtualKeyboard.KeyboardFunction.ToggleHandwritingMode: - return (keyboard.handwritingMode ? "edit-select-text-symbolic" : "draw-freehand-symbolic") // TODO: better icons? - } - } - } - } - - functionPopupListBackground: Item { - PlasmaKeyboard.BreezePopup { - theme: currentStyle.theme - readonly property real backgroundMargin: 20 * scaleHint - x: -backgroundMargin - y: -backgroundMargin - width: parent.width + 2 * backgroundMargin - height: parent.height + 2 * backgroundMargin - } - } - - functionPopupListHighlight: Rectangle { - color: theme.popupHighlightColor - radius: theme.buttonRadius - } -} diff --git a/src/vibration.cpp b/src/vibration.cpp deleted file mode 100644 index 2b574bb..0000000 --- a/src/vibration.cpp +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-FileCopyrightText: 2025 Devin Lin -// SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL - -#include "vibration.h" - -Vibration::Vibration(QObject *parent) - : QObject{parent} -{ - qDBusRegisterMetaType(); - qDBusRegisterMetaType(); -} - -void Vibration::vibrate(int durationMs) -{ - // Only create interface when needed. - if (!m_interface) { - const auto objectPath = QStringLiteral("/org/sigxcpu/Feedback"); - m_interface = new OrgSigxcpuFeedbackHapticInterface(QStringLiteral("org.sigxcpu.Feedback"), objectPath, QDBusConnection::sessionBus(), this); - } - - const QString appId = QStringLiteral("org.kde.plasma.keyboard"); - const VibrationEvent event{1.0, static_cast(durationMs)}; - const VibrationEventList pattern = {event}; - - m_interface->Vibrate(appId, pattern); -} - -#include "moc_vibration.cpp" diff --git a/src/vibration.h b/src/vibration.h deleted file mode 100644 index 71a3016..0000000 --- a/src/vibration.h +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-FileCopyrightText: 2025 Devin Lin -// SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL - -#pragma once - -#include -#include -#include - -#include "hapticinterface.h" -#include "vibrationevent.h" - -class Vibration : public QObject -{ - Q_OBJECT - QML_ELEMENT - QML_SINGLETON - -public: - explicit Vibration(QObject *parent = nullptr); - - Q_INVOKABLE void vibrate(int durationMs); - -private: - OrgSigxcpuFeedbackHapticInterface *m_interface{nullptr}; -}; diff --git a/src/vkbdwaylandinputbackend.cpp b/src/vkbdwaylandinputbackend.cpp new file mode 100644 index 0000000..a76eec3 --- /dev/null +++ b/src/vkbdwaylandinputbackend.cpp @@ -0,0 +1,101 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "vkbdwaylandinputbackend.h" + +VkbdWaylandInputBackend::VkbdWaylandInputBackend(QObject *parent) + : InputBackend(parent) +{ +} + +bool VkbdWaylandInputBackend::isActive() const +{ + return m_active; +} + +Qt::InputMethodHints VkbdWaylandInputBackend::inputMethodHints() const +{ + return m_inputMethodHints; +} + +QString VkbdWaylandInputBackend::surroundingText() const +{ + return m_surroundingText; +} + +uint32_t VkbdWaylandInputBackend::cursorPositionUtf8() const +{ + return m_cursorPositionUtf8; +} + +uint32_t VkbdWaylandInputBackend::anchorPositionUtf8() const +{ + return m_anchorPositionUtf8; +} + +void VkbdWaylandInputBackend::setPreeditText(const QString &text) +{ + Q_EMIT preeditTextRequested(text); +} + +void VkbdWaylandInputBackend::commitText(const QString &text) +{ + Q_EMIT commitTextRequested(text); +} + +void VkbdWaylandInputBackend::deleteSurroundingText(int index, int length) +{ + Q_EMIT deleteSurroundingTextRequested(index, length); +} + +bool VkbdWaylandInputBackend::sendKeyClick(int key) +{ + bool handled = false; + Q_EMIT keyClickRequested(key, &handled); + return handled; +} + +bool VkbdWaylandInputBackend::sendKeyPressed(int key, bool pressed) +{ + bool handled = false; + Q_EMIT keyPressedRequested(key, pressed, &handled); + if (handled) { + setKeyPressed(key, pressed); + } + return handled; +} + +void VkbdWaylandInputBackend::setActive(bool active) +{ + if (m_active == active) { + return; + } + + m_active = active; + Q_EMIT activeChanged(); +} + +void VkbdWaylandInputBackend::setInputMethodHints(Qt::InputMethodHints hints) +{ + if (m_inputMethodHints == hints) { + return; + } + + m_inputMethodHints = hints; + Q_EMIT inputMethodHintsChanged(); +} + +void VkbdWaylandInputBackend::setSurroundingState(const QString &text, uint32_t cursorPositionUtf8, uint32_t anchorPositionUtf8) +{ + if (m_surroundingText == text && m_cursorPositionUtf8 == cursorPositionUtf8 && m_anchorPositionUtf8 == anchorPositionUtf8) { + return; + } + + m_surroundingText = text; + m_cursorPositionUtf8 = cursorPositionUtf8; + m_anchorPositionUtf8 = anchorPositionUtf8; + Q_EMIT surroundingTextChanged(); +} diff --git a/src/vkbdwaylandinputbackend.h b/src/vkbdwaylandinputbackend.h new file mode 100644 index 0000000..a1e80bf --- /dev/null +++ b/src/vkbdwaylandinputbackend.h @@ -0,0 +1,51 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include "inputbackend.h" + +/** + * Implements the input engine's InputBackend for KWin. + * + * Emits events from the input engine through signals, see InputMethodConnection for usage. + */ +class VkbdWaylandInputBackend : public InputBackend +{ + Q_OBJECT + +public: + explicit VkbdWaylandInputBackend(QObject *parent = nullptr); + + bool isActive() const override; + Qt::InputMethodHints inputMethodHints() const override; + QString surroundingText() const override; + uint32_t cursorPositionUtf8() const override; + uint32_t anchorPositionUtf8() const override; + + void setPreeditText(const QString &text) override; + void commitText(const QString &text) override; + void deleteSurroundingText(int index, int length) override; + bool sendKeyClick(int key) override; + bool sendKeyPressed(int key, bool pressed) override; + + void setActive(bool active); + void setInputMethodHints(Qt::InputMethodHints hints); + void setSurroundingState(const QString &text, uint32_t cursorPositionUtf8, uint32_t anchorPositionUtf8); +Q_SIGNALS: + void preeditTextRequested(const QString &text); + void commitTextRequested(const QString &text); + void deleteSurroundingTextRequested(int index, int length); + void keyClickRequested(int key, bool *handled); + void keyPressedRequested(int key, bool pressed, bool *handled); + +private: + bool m_active = false; + Qt::InputMethodHints m_inputMethodHints = Qt::ImhNone; + QString m_surroundingText; + uint32_t m_cursorPositionUtf8 = 0; + uint32_t m_anchorPositionUtf8 = 0; +}; diff --git a/virtualkeyboard/CMakeLists.txt b/virtualkeyboard/CMakeLists.txt new file mode 100644 index 0000000..9ebc22a --- /dev/null +++ b/virtualkeyboard/CMakeLists.txt @@ -0,0 +1,112 @@ +# SPDX-FileCopyrightText: 2026 Devin Lin +# SPDX-License-Identifier: BSD-2-Clause + +add_library(plasma-keyboard-virtualkeyboard STATIC + inputbackend.cpp + inputbackend.h + inputengine.cpp + inputengine.h + textcomposers/abstracttextcomposer.cpp + textcomposers/abstracttextcomposer.h + textcomposers/basictextcomposer.cpp + textcomposers/basictextcomposer.h + textcomposers/directtextcomposer.cpp + textcomposers/directtextcomposer.h + keyboardcontroller.cpp + keyboardcontroller.h + keyboardlayoutmetadata.cpp + keyboardpackageresolver.cpp + keyboardpackageresolver.h + virtualkeyboardattached.cpp + virtualkeyboardattached.h + virtualkeyboardcontext.cpp + virtualkeyboardcontext.h + wordcandidatelistmodel.cpp + wordcandidatelistmodel.h +) + +target_include_directories(plasma-keyboard-virtualkeyboard + PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/textcomposers + PRIVATE + ${CMAKE_BINARY_DIR} + ${CMAKE_BINARY_DIR}/src +) + +target_link_libraries(plasma-keyboard-virtualkeyboard + PUBLIC + Qt::Core + PRIVATE + KF6::Package + Qt::Gui + Qt::GuiPrivate + Qt::Qml + Qt::Quick +) + +ecm_add_qml_module(plasma-keyboard-virtualkeyboard + URI org.kde.plasma.keyboard.virtualkeyboard + GENERATE_PLUGIN_SOURCE + DEPENDENCIES + QtQuick +) + +ecm_add_qml_module(keyboardvirtualkeyboardcomponents + URI org.kde.plasma.keyboard.virtualkeyboard.components + GENERATE_PLUGIN_SOURCE + DEPENDENCIES + QtQuick + QtQuick.Controls + org.kde.kirigami + org.kde.plasma.keyboard.virtualkeyboard +) + +set_source_files_properties( + components/BreezeConstants.qml + components/keys/FlickKeyPrivate.qml + PROPERTIES + QT_QML_SINGLETON_TYPE TRUE +) + +ecm_target_qml_sources(keyboardvirtualkeyboardcomponents SOURCES + components/BreezeConstants.qml + components/PopupBackground.qml + components/AlternativeKeysPopup.qml + components/CharacterPopup.qml + components/FlickPreviewPopup.qml + components/Keyboard.qml + components/KeyboardNavigation.qml + components/KeyboardStrip.qml + components/KeyboardColumn.qml + components/KeyboardLayoutLoader.qml + components/KeyboardLayout.qml + components/LanguagePopup.qml + components/KeyboardRow.qml + components/PreeditBubble.qml + components/keys/ActionKey.qml + components/keys/AbstractKey.qml + components/keys/BackspaceKey.qml + components/keys/ChangeLanguageKey.qml + components/keys/EnterKey.qml + components/keys/FillerKey.qml + components/keys/FlickKey.qml + components/keys/FlickKeyPrivate.qml + components/keys/HideKeyboardKey.qml + components/keys/InputModeKey.qml + components/keys/Key.qml + components/keys/KeyMouseArea.qml + components/keys/KeysymKey.qml + components/keys/ShiftKey.qml + components/keys/SpaceKey.qml + components/keys/SymbolModeKey.qml +) + +target_link_libraries(keyboardvirtualkeyboardcomponents + PRIVATE + Qt::Qml + Qt::Quick +) + +ecm_finalize_qml_module(plasma-keyboard-virtualkeyboard) +ecm_finalize_qml_module(keyboardvirtualkeyboardcomponents) diff --git a/virtualkeyboard/Messages.sh b/virtualkeyboard/Messages.sh new file mode 100644 index 0000000..9f27186 --- /dev/null +++ b/virtualkeyboard/Messages.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# SPDX-License-Identifier: BSD-2-Clause +# SPDX-FileCopyrightText: 2020-2022 Harald Sitter + +# Ensure passing shellcheck: +# Our l10n scripting isn't working with spaces anywhere and we actively rely on word splitting in our Messages.sh. +# shellcheck disable=SC2046 +podir=${podir:?} # ensure it is defined + +# Extract JavaScripty files as what they are, otherwise for example template literals won't work correctly (by default we extract as C++). +# https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals +$XGETTEXT --language=JavaScript $(find . -name \*.qml -o -name \*.js) -o "$podir"/plasma-keyboard-virtualkeyboard.pot diff --git a/virtualkeyboard/components/AlternativeKeysPopup.qml b/virtualkeyboard/components/AlternativeKeysPopup.qml new file mode 100644 index 0000000..ce9535f --- /dev/null +++ b/virtualkeyboard/components/AlternativeKeysPopup.qml @@ -0,0 +1,180 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import QtQuick.Controls as QQC2 + +import org.kde.plasma.keyboard +import org.kde.plasma.keyboard.virtualkeyboard + +// Popup that shows when you hold a key, and then can swipe left/right to select an alt key. + +Item { + id: root + + property Item keyboardPanel + property var ownerKey: null + property var items: [] + property int currentIndex: -1 + readonly property bool active: ownerKey !== null && items.length > 0 + readonly property real itemWidth: Math.round(92 * BreezeConstants.scaleHint) + readonly property real itemHeight: Math.round(116 * BreezeConstants.scaleHint) + readonly property real popupMargin: Math.round(16 * BreezeConstants.scaleHint) + readonly property real bottomMargin: Math.round(10 * BreezeConstants.scaleHint) + + anchors.fill: parent + visible: active + z: 3 + + function openForKey(keyItem) { + if (!keyboardPanel || !keyItem) { + return false; + } + + const alternativeKeys = keyItem.effectiveAlternativeKeys || []; + const displayAlternativeKeys = keyItem.displayAlternativeKeys || alternativeKeys; + if (alternativeKeys.length === 0 || displayAlternativeKeys.length !== alternativeKeys.length) { + return false; + } + + const entries = []; + for (let i = 0; i < alternativeKeys.length; ++i) { + entries.push({ + text: keyItem.uppercased ? String(displayAlternativeKeys[i]).toUpperCase() : String(displayAlternativeKeys[i]), + data: keyItem.uppercased ? String(alternativeKeys[i]).toUpperCase() : String(alternativeKeys[i]) + }); + } + + ownerKey = keyItem; + items = entries; + currentIndex = Math.max(0, Math.min(entries.length - 1, keyItem.effectiveAlternativeKeysHighlightIndex)); + + const point = keyItem.mapToItem(root, keyItem.width / 2, 0); + const popupWidth = listRow.width + popupMargin * 2; + const maxX = Math.max(0, root.width - popupWidth); + const currentItemOffset = popupMargin + (currentIndex + 0.5) * itemWidth; + const desiredX = point.x - currentItemOffset; + popupContainer.x = Math.max(0, Math.min(maxX, desiredX)); + popupContainer.y = point.y - popupContainer.height - bottomMargin; + return true; + } + + function close() { + ownerKey = null; + items = []; + currentIndex = -1; + } + + function moveFromKey(keyItem, localX) { + if (!active || ownerKey !== keyItem) { + return; + } + + const point = keyItem.mapToItem(listRow, localX, 0); + updateCurrentIndex(point.x); + } + + function moveFromPanelPosition(panelX) { + if (!active) { + return; + } + + const point = root.mapToItem(listRow, panelX, 0); + updateCurrentIndex(point.x); + } + + function updateCurrentIndex(contentX) { + const clampedX = Math.max(1, Math.min(listRow.width - 1, contentX)); + const nextIndex = Math.max(0, Math.min(items.length - 1, Math.floor(clampedX / root.itemWidth))); + if (nextIndex === currentIndex) { + return; + } + + currentIndex = nextIndex; + Feedback.play(Feedback.SelectionChange); + } + + function moveSelection(delta) { + if (!active) { + return false; + } + + const nextIndex = Math.max(0, Math.min(items.length - 1, currentIndex + delta)); + if (nextIndex === currentIndex) { + return false; + } + + currentIndex = nextIndex; + Feedback.play(Feedback.SelectionChange); + return true; + } + + function commitCurrent() { + if (!active || currentIndex < 0 || currentIndex >= items.length || !ownerKey) { + close(); + return; + } + + const entry = items[currentIndex]; + Feedback.play(Feedback.SelectionCommit); + ownerKey.commitAlternativeText(entry.data); + close(); + } + + TapHandler { + acceptedButtons: Qt.LeftButton + onTapped: (eventPoint) => { + if (!popupContainer.contains(mapToItem(popupContainer, eventPoint.position.x, eventPoint.position.y))) { + root.close(); + } + } + } + + Item { + id: popupContainer + visible: root.active + width: listRow.width + root.popupMargin * 2 + height: root.itemHeight + root.popupMargin * 2 + + PopupBackground { + anchors.fill: parent + theme: BreezeConstants + } + + Row { + id: listRow + anchors.centerIn: parent + spacing: 0 + + Repeater { + model: root.items + + delegate: Item { + required property int index + required property var modelData + + width: root.itemWidth + height: root.itemHeight + + Rectangle { + anchors.fill: parent + anchors.margins: Math.round(4 * BreezeConstants.scaleHint) + radius: BreezeConstants.buttonRadius + color: root.currentIndex === index ? BreezeConstants.popupHighlightColor : "transparent" + border.width: root.currentIndex === index ? 1 : 0 + border.color: BreezeConstants.popupHighlightBorderColor + } + + QQC2.Label { + anchors.centerIn: parent + text: modelData.text + color: BreezeConstants.popupTextColor + font.family: BreezeConstants.fontFamily + font.weight: root.currentIndex === index ? Font.Medium : Font.Light + font.pixelSize: Math.round(52 * BreezeConstants.scaleHint) + } + } + } + } + } +} diff --git a/src/qmlplugin/BreezeConstants.qml b/virtualkeyboard/components/BreezeConstants.qml similarity index 57% rename from src/qmlplugin/BreezeConstants.qml rename to virtualkeyboard/components/BreezeConstants.qml index 5385d62..e62ee84 100644 --- a/src/qmlplugin/BreezeConstants.qml +++ b/virtualkeyboard/components/BreezeConstants.qml @@ -12,27 +12,30 @@ QtObject { property real scaleHint readonly property string fontFamily: Kirigami.Theme.defaultFont.family - readonly property real keyBackgroundMargin: Math.round(8 * scaleHint) + readonly property real keyBackgroundHorizontalMargin: Math.round(8 * scaleHint) + readonly property real keyBackgroundVerticalMargin: Math.round(12 * scaleHint) readonly property real keyContentMargin: Math.round(40 * scaleHint) - readonly property real keyIconScale: scaleHint * 0.8 + readonly property real keyIconScale: scaleHint * 0.55 + + readonly property bool isDark: Kirigami.ColorUtils.brightnessForColor(Kirigami.Theme.backgroundColor) === Kirigami.ColorUtils.Dark property color primaryColor: Kirigami.Theme.backgroundColor - property color primaryLightColor: Qt.lighter(primaryColor, 1.3) - property color primaryDarkColor: Qt.darker(primaryColor, 1.3) property color textOnPrimaryColor: Kirigami.Theme.textColor property color secondaryColor: Kirigami.Theme.backgroundColor - property color secondaryLightColor: Qt.lighter(secondaryColor, 1.3) - property color secondaryDarkColor: Qt.darker(secondaryColor, 1.3) property color textOnSecondaryColor: Kirigami.Theme.textColor property color keyboardBackgroundColor: primaryColor - property color normalKeyBackgroundColor: primaryLightColor - property color normalKeyPressedBackgroundColor: primaryDarkColor - property color highlightedKeyBackgroundColor: primaryLightColor - property color capsLockKeyAccentColor: secondaryColor - property color modeKeyAccentColor: textOnPrimaryColor + property color keyboardTopSeparatorColor: Qt.darker(primaryColor, 1.3) + property color normalKeyBackgroundColor: Kirigami.ColorUtils.tintWithAlpha(Kirigami.Theme.backgroundColor, "white", isDark ? 0.1 : 0.75) + property color normalKeyPressedBackgroundColor: isDark ? secondaryKeyBackgroundColor : Qt.darker(normalKeyBackgroundColor, 1.3) + property color secondaryKeyBackgroundColor: Kirigami.ColorUtils.tintWithAlpha(primaryColor, normalKeyBackgroundColor, isDark ? 0.4 : (0.6 - Math.abs(primaryColor.hslLightness - normalKeyBackgroundColor.hslLightness)) * -1) + property color secondaryKeyPressedBackgroundColor: Qt.darker(secondaryKeyBackgroundColor, 1.2) + property color highlightedKeyBackgroundColor: Kirigami.ColorUtils.tintWithAlpha(normalKeyBackgroundColor, "white", 0.2) property color keyTextColor: textOnPrimaryColor property color keySmallTextColor: textOnPrimaryColor + property color keyShadowColor: Qt.rgba(0, 0, 0, isDark ? 0.2 : 0.25) + property real keyShadowSize: 3 + property real keyShadowYOffset: 1 property color popupBackgroundColor: secondaryColor property color popupBorderColor: Kirigami.ColorUtils.tintWithAlpha(Kirigami.Theme.textColor, secondaryColor, 0.9) property color popupTextColor: textOnSecondaryColor @@ -40,7 +43,7 @@ QtObject { property color popupHighlightBorderColor: Kirigami.Theme.highlightColor property color popupHighlightColor: Qt.rgba(Kirigami.Theme.highlightColor.r, Kirigami.Theme.highlightColor.g, Kirigami.Theme.highlightColor.b, 0.3) property color selectionListTextColor: textOnPrimaryColor - property color selectionListSeparatorColor: primaryLightColor + property color selectionListSeparatorColor: Qt.lighter(primaryColor, 1.3) property color selectionListBackgroundColor: primaryColor property color navigationHighlightColor: Qt.rgba(navigationHighlightBorderColor.r, navigationHighlightBorderColor.g, navigationHighlightBorderColor.b, 0.3) property color navigationHighlightBorderColor: Kirigami.Theme.highlightColor diff --git a/virtualkeyboard/components/CharacterPopup.qml b/virtualkeyboard/components/CharacterPopup.qml new file mode 100644 index 0000000..b97c177 --- /dev/null +++ b/virtualkeyboard/components/CharacterPopup.qml @@ -0,0 +1,80 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import QtQuick.Controls as QQC2 + +// Character popup shown above a pressed text key. + +Item { + id: root + + property var ownerKey: null + + readonly property bool active: ownerKey !== null + readonly property string popupText: { + if (!ownerKey) { + return ""; + } + return ownerKey.uppercased ? ownerKey.displayText.toUpperCase() : ownerKey.displayText; + } + readonly property real popupMargin: Math.round(10 * BreezeConstants.scaleHint) + + visible: active + z: 6 + + width: ownerKey ? ownerKey.width : 0 + height: ownerKey ? ownerKey.height : 0 + + function openForKey(keyItem) { + if (!enabled || !keyItem || !keyItem.showPreview || keyItem.displayText.length === 0) { + return false; + } + + ownerKey = keyItem; + updateFromKey(keyItem); + return true; + } + + function updateFromKey(keyItem) { + if (!keyItem || ownerKey !== keyItem) { + return; + } + + const point = keyItem.mapToItem(root.parent, 0, 0); + x = point.x; + y = point.y - height - popupMargin; + } + + function closeForKey(keyItem) { + if (ownerKey === keyItem) { + ownerKey = null; + } + } + + function close() { + ownerKey = null; + } + + onEnabledChanged: { + if (!enabled) { + close(); + } + } + + PopupBackground { + anchors.fill: parent + theme: BreezeConstants + } + + QQC2.Label { + anchors.fill: parent + text: root.popupText + color: BreezeConstants.popupTextColor + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + font.family: BreezeConstants.fontFamily + font.weight: Font.Light + font.pixelSize: root.ownerKey ? Math.round(root.ownerKey.textPixelSize * 1.5) : 0 + } +} diff --git a/virtualkeyboard/components/FlickPreviewPopup.qml b/virtualkeyboard/components/FlickPreviewPopup.qml new file mode 100644 index 0000000..9668bfb --- /dev/null +++ b/virtualkeyboard/components/FlickPreviewPopup.qml @@ -0,0 +1,129 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import QtQuick.Controls as QQC2 + +// Popup that shows up when holding a flick key. + +Item { + id: root + + property Item ownerKey: null + readonly property bool active: !!ownerKey + readonly property string centerText: ownerKey ? ownerKey.currentText : "" + readonly property string flickLeft: ownerKey ? ownerKey.flickLeft : "" + readonly property string flickTop: ownerKey ? ownerKey.flickTop : "" + readonly property string flickRight: ownerKey ? ownerKey.flickRight : "" + readonly property string flickBottom: ownerKey ? ownerKey.flickBottom : "" + readonly property bool flickKeysVisible: centerText.length > 0 + && (flickLeft.length > 0 || flickTop.length > 0 || flickRight.length > 0 || flickBottom.length > 0) + && centerText !== flickLeft + && centerText !== flickTop + && centerText !== flickRight + && centerText !== flickBottom + readonly property real popupMargin: Math.round(10 * BreezeConstants.scaleHint) + readonly property real largeTextSize: Math.round((flickKeysVisible ? 66 : 82) * BreezeConstants.scaleHint) + readonly property real smallTextSize: Math.round((flickKeysVisible ? 50 : 62) * BreezeConstants.scaleHint) + readonly property real smallTextMargin: Math.round(6 * BreezeConstants.scaleHint) + + visible: active + z: 5 + + function openForKey(keyItem) { + if (!keyItem || !keyItem.showPreview) { + return false + } + + ownerKey = keyItem + updateFromKey(keyItem) + return true + } + + function updateFromKey(keyItem) { + if (!keyItem || ownerKey !== keyItem) { + return + } + + const point = keyItem.mapToItem(root.parent, 0, 0) + x = point.x + y = point.y - height - popupMargin + } + + function close() { + ownerKey = null + } + + width: ownerKey ? ownerKey.width : 0 + height: ownerKey ? ownerKey.height : 0 + + PopupBackground { + anchors.fill: parent + theme: BreezeConstants + } + + QQC2.Label { + id: centerLabel + anchors.horizontalCenter: parent.horizontalCenter + anchors.verticalCenter: parent.verticalCenter + text: root.centerText + color: BreezeConstants.popupTextColor + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + font.family: BreezeConstants.fontFamily + font.weight: Font.Light + font.pixelSize: root.flickKeysVisible ? root.smallTextSize : root.largeTextSize + } + + QQC2.Label { + anchors.left: parent.left + anchors.leftMargin: root.smallTextMargin + anchors.verticalCenter: parent.verticalCenter + visible: root.flickKeysVisible + text: root.flickLeft + color: BreezeConstants.popupTextColor + opacity: 0.8 + font.family: BreezeConstants.fontFamily + font.weight: Font.Light + font.pixelSize: root.smallTextSize + } + + QQC2.Label { + anchors.top: parent.top + anchors.topMargin: root.smallTextMargin + anchors.horizontalCenter: parent.horizontalCenter + visible: root.flickKeysVisible + text: root.flickTop + color: BreezeConstants.popupTextColor + opacity: 0.8 + font.family: BreezeConstants.fontFamily + font.weight: Font.Light + font.pixelSize: root.smallTextSize + } + + QQC2.Label { + anchors.right: parent.right + anchors.rightMargin: root.smallTextMargin + anchors.verticalCenter: parent.verticalCenter + visible: root.flickKeysVisible + text: root.flickRight + color: BreezeConstants.popupTextColor + opacity: 0.8 + font.family: BreezeConstants.fontFamily + font.weight: Font.Light + font.pixelSize: root.smallTextSize + } + + QQC2.Label { + anchors.bottom: parent.bottom + anchors.bottomMargin: root.smallTextMargin + anchors.horizontalCenter: parent.horizontalCenter + visible: root.flickKeysVisible + text: root.flickBottom + color: BreezeConstants.popupTextColor + opacity: 0.8 + font.family: BreezeConstants.fontFamily + font.weight: Font.Light + font.pixelSize: root.smallTextSize + } +} diff --git a/virtualkeyboard/components/Keyboard.qml b/virtualkeyboard/components/Keyboard.qml new file mode 100644 index 0000000..150dfa1 --- /dev/null +++ b/virtualkeyboard/components/Keyboard.qml @@ -0,0 +1,150 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +import QtQuick +import QtQuick.Layouts + +import org.kde.plasma.keyboard +import org.kde.plasma.keyboard.virtualkeyboard +import org.kde.plasma.keyboard.virtualkeyboard.components + +Item { + id: root + + property var languagePopup: null + property var virtualKeyboardContext: null + property real padding: 0 + property real leftPadding: padding + property real rightPadding: padding + property real topPadding: padding + property real bottomPadding: padding + + readonly property var inputEngine: virtualKeyboardContext ? virtualKeyboardContext.inputEngine : VirtualKeyboard.inputEngine + readonly property var keyboardController: virtualKeyboardContext ? virtualKeyboardContext.keyboardController : VirtualKeyboard.keyboardController + readonly property var keyboardPackageResolver: virtualKeyboardContext ? virtualKeyboardContext.keyboardPackageResolver : VirtualKeyboard.keyboardPackageResolver + readonly property bool navigationAvailable: keyboardNavigation.navigationAvailable + property alias navigationModeActive: keyboardNavigation.navigationModeActive + + readonly property string layoutId: keyboardController ? keyboardController.layoutId : "" + readonly property string packageId: keyboardPackageResolver ? keyboardPackageResolver.packageId(layoutId) : "" + readonly property string layoutType: keyboardController ? keyboardController.layoutType : "main" + + implicitHeight: __keyboardHeight + implicitWidth: __keyboardWidth + + // Always have the keyboard panel be 30% of the screen height, or 150px, whichever is larger + readonly property real __baseKeyboardInputAreaHeight: Math.max(Screen.height * 0.3, 150) + readonly property real __keyboardInputAreaHeight: __baseKeyboardInputAreaHeight * ((layoutLoader.item && layoutLoader.item.panelHeightFactor !== undefined) ? layoutLoader.item.panelHeightFactor : 1) + readonly property real __contentHeight: __keyboardInputAreaHeight + (candidateStrip.visible ? candidateStrip.implicitHeight : 0) + readonly property real __horizontalPadding: leftPadding + rightPadding + readonly property real __verticalPadding: topPadding + bottomPadding + readonly property real __keyboardHeight: __contentHeight + __verticalPadding + readonly property real __keyboardWidth: Math.round(__contentHeight * aspectRatio) + __horizontalPadding + + // The value to multiply the height by to get the width + readonly property real aspectRatio: { + // Ratio to just fill the screen width + const availableWidth = Math.max(0, Screen.width - __horizontalPadding); + const fillScreenWidthRatio = availableWidth / __contentHeight; + if (PlasmaKeyboardSettings.panelFillScreenWidth) { + return fillScreenWidthRatio; + } + + const targetAspectRatio = 3.0; // Target width ratio: 3 * height + return Math.min(fillScreenWidthRatio, targetAspectRatio); + } + + // The design ratios for the keyboard height + readonly property real __keyboardDesignHeight: { + if (Screen.width < 500) { + // Phone mode + return 800; + } + if (Screen.width < 1200) { + // Wider + return 600; + } + // Widest + return 700; + } + readonly property real panelScaleHint: Math.max(0.3, __keyboardInputAreaHeight / __keyboardDesignHeight) + + function resetNavigation() { + keyboardNavigation.resetNavigation(); + } + + function handleNavigationPressed(key) { + keyboardNavigation.handleNavigationPressed(key); + } + + function handleNavigationReleased(key) { + keyboardNavigation.handleNavigationReleased(key); + } + + function updateScaleHint() { + if (width <= 0) { + return; + } + BreezeConstants.scaleHint = panelScaleHint; + } + + onPanelScaleHintChanged: updateScaleHint() + Component.onCompleted: updateScaleHint() + + KeyboardNavigation { + id: keyboardNavigation + layoutLoader: layoutLoader + keyboardStrip: candidateStrip + languagePopup: root.languagePopup + } + + ColumnLayout { + anchors { + fill: parent + leftMargin: root.leftPadding + rightMargin: root.rightPadding + topMargin: root.topPadding + bottomMargin: root.bottomPadding + } + spacing: 0 + + KeyboardStrip { + id: candidateStrip + Layout.fillWidth: true + inputEngine: root.inputEngine + } + + Loader { + id: layoutLoader + + Layout.preferredWidth: parent.width + Layout.maximumWidth: (item && item.maxWidthToHeightRatio !== -1) ? (item.maxWidthToHeightRatio * height) : parent.width + Layout.preferredHeight: root.__keyboardInputAreaHeight + Layout.alignment: Qt.AlignHCenter + + source: root.keyboardPackageResolver ? root.keyboardPackageResolver.layoutUrl(root.layoutId, root.layoutType) : "" + + onLoaded: { + resetNavigation(); + if (item && item.virtualKeyboardContext !== undefined) { + item.virtualKeyboardContext = root.virtualKeyboardContext; + } + if (item && item.layoutId !== undefined) { + item.layoutId = root.layoutId; + } + if (item && item.packageId !== undefined) { + item.packageId = root.packageId; + } + } + + onStatusChanged: { + if (status === Loader.Error) { + console.warn("Failed to load keyboard layout", root.layoutId, root.layoutType, source); + } + } + } + } +} diff --git a/virtualkeyboard/components/KeyboardColumn.qml b/virtualkeyboard/components/KeyboardColumn.qml new file mode 100644 index 0000000..ba1f43e --- /dev/null +++ b/virtualkeyboard/components/KeyboardColumn.qml @@ -0,0 +1,33 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +import QtQuick +import QtQuick.Layouts + +ColumnLayout { + id: root + + /** + * Default width weight used by child keys that do not set their own + * weight. By default it is inherited from the parent. + */ + property real defaultKeyWeight: parent && parent.defaultKeyWeight !== undefined ? parent.defaultKeyWeight : 100 + + /** + * Width weight for this column when it is placed inside a KeyboardRow. + * This lets a vertical stack of keys occupy the same horizontal slot as a + * normal key. + */ + property real weight: parent && parent.defaultKeyWeight !== undefined ? parent.defaultKeyWeight : 100 + + // HACK: Layout.preferredWidth is used as a sort of size hint, not an exact size. + // If the weight is too large, preferredWidth gets capped out and stuff starts breaking. + Layout.preferredWidth: weight / Math.max(defaultKeyWeight, 1) + Layout.minimumWidth: 0 + Layout.fillWidth: true + Layout.fillHeight: true + spacing: 0 +} diff --git a/virtualkeyboard/components/KeyboardLayout.qml b/virtualkeyboard/components/KeyboardLayout.qml new file mode 100644 index 0000000..5e0a689 --- /dev/null +++ b/virtualkeyboard/components/KeyboardLayout.qml @@ -0,0 +1,76 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +import QtQuick +import QtQuick.Layouts + +import org.kde.plasma.keyboard.virtualkeyboard + +ColumnLayout { + id: root + + /** + * Default weight of keys. + */ + property real defaultKeyWeight: 100 + + /** + * Default height weight of keyboard rows. + */ + property real defaultRowHeightWeight: 100 + + /** + * Set a maximum width of the keyboard in relation to its height (so it doesn't stretch forever). + */ + property real maxWidthToHeightRatio: -1 + + /** + * Multiplier for the keyboard panel height. Use this for layouts with extra rows. + */ + property real panelHeightFactor: 1 + + property string packageId: "" + property string layoutId: "" + property var virtualKeyboardContext: null + readonly property var inputEngine: virtualKeyboardContext ? virtualKeyboardContext.inputEngine : VirtualKeyboard.inputEngine + property var textComposer + property var sharedLayouts: [] + + Layout.fillWidth: true + Layout.fillHeight: true + width: parent ? parent.width : implicitWidth + height: parent ? parent.height : implicitHeight + spacing: 0 + + function applyEngineBindings() { + let effectiveTextComposer = textComposer; + if (!effectiveTextComposer) { + effectiveTextComposer = createTextComposer(); + if (effectiveTextComposer) { + textComposer = effectiveTextComposer; + } + } + if (effectiveTextComposer && inputEngine) { + inputEngine.textComposer = effectiveTextComposer; + } + } + + Component.onCompleted: applyEngineBindings(); + onVirtualKeyboardContextChanged: if (visible) applyEngineBindings(); + onVisibleChanged: if (visible) applyEngineBindings(); + onPackageIdChanged: if (visible) applyEngineBindings(); + onLayoutIdChanged: if (visible) applyEngineBindings(); + onTextComposerChanged: if (visible) applyEngineBindings(); + function createTextComposer() { + return defaultTextComposerComponent.createObject(root); + } + + Component { + id: defaultTextComposerComponent + + BasicTextComposer {} + } +} diff --git a/virtualkeyboard/components/KeyboardLayoutLoader.qml b/virtualkeyboard/components/KeyboardLayoutLoader.qml new file mode 100644 index 0000000..e1717e2 --- /dev/null +++ b/virtualkeyboard/components/KeyboardLayoutLoader.qml @@ -0,0 +1,38 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +import QtQuick + +import org.kde.plasma.keyboard.virtualkeyboard + +Loader { + id: root + + property string packageId: "" + property string layoutId: "" + property var virtualKeyboardContext: null + readonly property var inputEngine: virtualKeyboardContext ? virtualKeyboardContext.inputEngine : VirtualKeyboard.inputEngine + + function applyLayoutProperties() { + if (!item) { + return; + } + if (item.virtualKeyboardContext !== undefined) { + item.virtualKeyboardContext = virtualKeyboardContext; + } + if (item.layoutId !== undefined) { + item.layoutId = layoutId; + } + if (item.packageId !== undefined) { + item.packageId = packageId; + } + } + + onLoaded: applyLayoutProperties() + onVirtualKeyboardContextChanged: applyLayoutProperties() + onPackageIdChanged: applyLayoutProperties() + onLayoutIdChanged: applyLayoutProperties() +} diff --git a/virtualkeyboard/components/KeyboardNavigation.qml b/virtualkeyboard/components/KeyboardNavigation.qml new file mode 100644 index 0000000..4bf308a --- /dev/null +++ b/virtualkeyboard/components/KeyboardNavigation.qml @@ -0,0 +1,349 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +import QtQuick + +import org.kde.plasma.keyboard.virtualkeyboard + +QtObject { + id: root + + enum ActivationState { + Idle, + KeyPressed, + PopupWaitingForRelease, + PopupOpen, + PopupConfirmPressed, + PopupEscapePressed + } + + required property Loader layoutLoader + required property var keyboardStrip + property var languagePopup: null + + readonly property bool navigationAvailable: layoutLoader.status === Loader.Ready && layoutLoader.item !== null && navigableKeys().length > 0 + property bool navigationModeActive: false + property var navigationKeyItem: null + property string navigationArea: "" + + // Track Enter and alternate popup state + property int __activationState: KeyboardNavigation.ActivationState.Idle + property var __activationKeyItem: null + readonly property Timer __activationHoldTimer: Timer { + interval: 500 + repeat: false + onTriggered: root.openAlternativePopup() + } + + function clearNavigationKey() { + if (navigationKeyItem) { + navigationKeyItem.navigationActive = false; + } + navigationKeyItem = null; + } + + function setNavigationKey(item) { + if (navigationKeyItem === item) { + return; + } + clearNavigationKey(); + navigationKeyItem = item; + if (navigationKeyItem) { + navigationKeyItem.navigationActive = true; + } + } + + function resetNavigation() { + cancelNavigationActivation(); + clearNavigationKey(); + navigationArea = ""; + navigationModeActive = false; + keyboardStrip.navigationModeActive = false; + keyboardStrip.resetNavigation(); + } + + function collectNavigableKeys(item, keys) { + if (!item || !item.visible) { + return; + } + + if (item.navigationActive !== undefined && item.triggerByNavigation !== undefined && item.enabled !== false) { + keys.push(item); + } + + for (let i = 0; i < item.children.length; ++i) { + collectNavigableKeys(item.children[i], keys); + } + } + + function navigableKeys() { + const keys = []; + if (layoutLoader.item) { + collectNavigableKeys(layoutLoader.item, keys); + } + return keys; + } + + function keyCenter(item) { + return item.mapToItem(layoutLoader, item.width / 2, item.height / 2); + } + + function findHorizontalKey(direction) { + // Move left and right in reading order + const keys = navigableKeys(); + if (keys.length === 0) { + return null; + } + + const currentIndex = keys.indexOf(navigationKeyItem); + if (currentIndex === -1) { + return keys[0]; + } + return keys[(currentIndex + direction + keys.length) % keys.length]; + } + + function findVerticalKey(direction) { + // Move to the closest key in the nearest row + const keys = navigableKeys(); + if (keys.length === 0) { + return null; + } + + if (!navigationKeyItem || direction === 0) { + return keys[0]; + } + + const currentCenter = keyCenter(navigationKeyItem); + let closestKey = null; + let closestVerticalDistance = Number.MAX_VALUE; + let closestHorizontalDistance = Number.MAX_VALUE; + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (key === navigationKeyItem) { + continue; + } + + const center = keyCenter(key); + const verticalDistance = (center.y - currentCenter.y) * direction; + const sameRowThreshold = Math.min(key.height, navigationKeyItem.height) / 2; + if (verticalDistance <= sameRowThreshold) { + continue; + } + + const horizontalDistance = Math.abs(center.x - currentCenter.x); + if (verticalDistance < closestVerticalDistance + || (verticalDistance === closestVerticalDistance && horizontalDistance < closestHorizontalDistance)) { + closestKey = key; + closestVerticalDistance = verticalDistance; + closestHorizontalDistance = horizontalDistance; + } + } + return closestKey; + } + + function moveKeyNavigation(dx, dy) { + const nextKey = dx !== 0 ? findHorizontalKey(dx) : findVerticalKey(dy); + if (!nextKey) { + return false; + } + + setNavigationKey(nextKey); + navigationArea = "keys"; + navigationModeActive = true; + keyboardStrip.navigationModeActive = false; + keyboardStrip.resetNavigation(); + return true; + } + + function startNavigationActivation() { + // Start Enter activation and long press detection + if (__activationState !== KeyboardNavigation.ActivationState.Idle) { + return; + } + + __activationState = KeyboardNavigation.ActivationState.KeyPressed; + __activationKeyItem = navigationArea === "keys" ? navigationKeyItem : null; + if (!__activationKeyItem) { + return; + } + + __activationKeyItem.pressedVisual = true; + if (__activationKeyItem.effectiveAlternativeKeys && __activationKeyItem.effectiveAlternativeKeys.length > 0) { + __activationHoldTimer.restart(); + } + } + + function openAlternativePopup() { + const popup = VirtualKeyboard.alternativeKeysPopup; + if (__activationState !== KeyboardNavigation.ActivationState.KeyPressed + || !__activationKeyItem + || __activationKeyItem !== navigationKeyItem + || !popup) { + return; + } + if (popup.openForKey(__activationKeyItem)) { + __activationState = KeyboardNavigation.ActivationState.PopupWaitingForRelease; + } + } + + function cancelNavigationActivation() { + __activationHoldTimer.stop(); + if (__activationKeyItem) { + __activationKeyItem.pressedVisual = false; + } + const popup = VirtualKeyboard.alternativeKeysPopup; + if (popup && popup.active && popup.ownerKey === __activationKeyItem) { + popup.close(); + } + __activationState = KeyboardNavigation.ActivationState.Idle; + __activationKeyItem = null; + } + + function focusCandidates() { + if (!keyboardStrip.visible || !keyboardStrip.ensureNavigationSelection(false)) { + return false; + } + + clearNavigationKey(); + navigationArea = "candidates"; + navigationModeActive = true; + keyboardStrip.navigationModeActive = true; + return true; + } + + function moveHorizontal(direction) { + if (navigationArea !== "candidates" || !keyboardStrip.moveSelection(direction)) { + moveKeyNavigation(direction, 0); + } + } + + function handleNavigationPressed(key) { + // Handle alternate popup navigation first + const alternativePopup = VirtualKeyboard.alternativeKeysPopup; + if (alternativePopup && alternativePopup.active && alternativePopup.ownerKey === __activationKeyItem) { + if (key === Qt.Key_Left) { + alternativePopup.moveSelection(-1); + } else if (key === Qt.Key_Right) { + alternativePopup.moveSelection(1); + } else if (key === Qt.Key_Escape) { + alternativePopup.close(); + __activationState = KeyboardNavigation.ActivationState.PopupEscapePressed; + } else if ((key === Qt.Key_Return || key === Qt.Key_Enter) + && __activationState === KeyboardNavigation.ActivationState.PopupOpen) { + __activationState = KeyboardNavigation.ActivationState.PopupConfirmPressed; + } + return; + } + + if (languagePopup && languagePopup.popupVisible) { + navigationModeActive = true; + if (key === Qt.Key_Escape) { + return; + } else if (key === Qt.Key_Up) { + languagePopup.moveSelection(-1); + } else if (key === Qt.Key_Down) { + languagePopup.moveSelection(1); + } else if (key === Qt.Key_Left || key === Qt.Key_Right) { + languagePopup.close(); + resetNavigation(); + } + return; + } + + switch (key) { + case Qt.Key_Escape: + break; + case Qt.Key_Left: + moveHorizontal(-1); + break; + case Qt.Key_Right: + moveHorizontal(1); + break; + case Qt.Key_Up: + if (navigationArea === "candidates") { + break; + } + if (!moveKeyNavigation(0, -1) && keyboardStrip.visible) { + focusCandidates(); + } + break; + case Qt.Key_Down: + moveKeyNavigation(0, 1); + break; + case Qt.Key_Return: + case Qt.Key_Enter: + startNavigationActivation(); + break; + default: + break; + } + } + + function handleNavigationReleased(key) { + if (key === Qt.Key_Escape) { + if (__activationState === KeyboardNavigation.ActivationState.PopupEscapePressed) { + __activationState = KeyboardNavigation.ActivationState.Idle; + __activationKeyItem = null; + return; + } + if (languagePopup && languagePopup.popupVisible) { + languagePopup.close(); + } + resetNavigation(); + return; + } + + if (key !== Qt.Key_Return && key !== Qt.Key_Enter) { + return; + } + + __activationHoldTimer.stop(); + if (__activationKeyItem) { + __activationKeyItem.pressedVisual = false; + } + + if (__activationState === KeyboardNavigation.ActivationState.PopupWaitingForRelease) { + // Keep the popup open after the long press release + __activationState = KeyboardNavigation.ActivationState.PopupOpen; + return; + } + if (__activationState === KeyboardNavigation.ActivationState.PopupConfirmPressed) { + const alternativePopup = VirtualKeyboard.alternativeKeysPopup; + if (alternativePopup && alternativePopup.active) { + // Confirm the alternate on the next Enter release + alternativePopup.commitCurrent(); + } + __activationState = KeyboardNavigation.ActivationState.Idle; + __activationKeyItem = null; + return; + } + + __activationState = KeyboardNavigation.ActivationState.Idle; + + if (languagePopup && languagePopup.popupVisible) { + languagePopup.activateCurrent(); + return; + } + + if (!navigationModeActive) { + return; + } + + if (navigationArea === "candidates") { + keyboardStrip.activateCurrent(); + return; + } + + if (!navigationKeyItem) { + moveKeyNavigation(0, 0); + } + const keyItem = __activationKeyItem || navigationKeyItem; + __activationKeyItem = null; + if (keyItem) { + keyItem.triggerByNavigation(); + } + } +} diff --git a/virtualkeyboard/components/KeyboardRow.qml b/virtualkeyboard/components/KeyboardRow.qml new file mode 100644 index 0000000..5e0f2f2 --- /dev/null +++ b/virtualkeyboard/components/KeyboardRow.qml @@ -0,0 +1,44 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +import QtQuick +import QtQuick.Layouts + +RowLayout { + id: root + + /** + * Default width weight used by child keys that do not set their own + * weight. By default it is inherited from the parent. + */ + property real defaultKeyWeight: parent && parent.defaultKeyWeight !== undefined ? parent.defaultKeyWeight : 100 + + /** + * Width weight for this row when it is nested inside another KeyboardRow. + * Nested rows can use it to occupy the same horizontal slot as a key. + */ + property real weight: parent && parent.defaultKeyWeight !== undefined ? parent.defaultKeyWeight : 100 + + /** + * Relative height weight used by the parent KeyboardLayout when + * distributing vertical space between rows. + * For example, use heightWeight: defaultRowHeightWeight / 2 for a + * half-height row. + */ + property real heightWeight: parent && parent.defaultRowHeightWeight !== undefined ? parent.defaultRowHeightWeight : 100 + + implicitHeight: Math.round(heightWeight) + + // HACK: Layout.preferredWidth is used as a sort of size hint, not an exact size. + // If the weight is too large, preferredWidth gets capped out and stuff starts breaking. + Layout.preferredWidth: weight / Math.max(defaultKeyWeight, 1) + Layout.minimumWidth: 0 + Layout.preferredHeight: heightWeight + Layout.fillWidth: true + Layout.fillHeight: true + Layout.verticalStretchFactor: Layout.fillHeight ? Math.round(heightWeight) : -1 + spacing: 0 +} diff --git a/virtualkeyboard/components/KeyboardStrip.qml b/virtualkeyboard/components/KeyboardStrip.qml new file mode 100644 index 0000000..92e8118 --- /dev/null +++ b/virtualkeyboard/components/KeyboardStrip.qml @@ -0,0 +1,141 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +import QtQuick +import QtQuick.Controls as QQC2 + +import org.kde.plasma.keyboard +import org.kde.plasma.keyboard.virtualkeyboard + +// Word candidate strip shown by input methods when there are suggestions. + +Rectangle { + id: root + + property var inputEngine: VirtualKeyboard.inputEngine + property bool navigationModeActive: false + readonly property real candidateHorizontalPadding: Math.round(28 * BreezeConstants.scaleHint) + readonly property int candidateCount: candidateView.count + readonly property bool hasNavigationSelection: candidateView.currentIndex >= 0 + readonly property bool hasCandidates: inputEngine && inputEngine.wordCandidateListVisibleHint + + visible: hasCandidates + implicitHeight: Math.round(100 * BreezeConstants.scaleHint) + color: BreezeConstants.selectionListBackgroundColor + + function resetNavigation() { + candidateView.currentIndex = -1; + } + + function ensureNavigationSelection(fromRight) { + if (candidateCount <= 0) { + candidateView.currentIndex = -1; + return false; + } + if (candidateView.currentIndex === -1) { + candidateView.currentIndex = fromRight ? candidateCount - 1 : 0; + } + candidateView.positionViewAtIndex(candidateView.currentIndex, ListView.Contain); + return true; + } + + function moveSelection(delta) { + if (!ensureNavigationSelection(delta < 0)) { + return false; + } + + const nextIndex = candidateView.currentIndex + delta; + if (nextIndex < 0) { + return false; + } + if (nextIndex >= candidateCount) { + return false; + } + + candidateView.currentIndex = nextIndex; + candidateView.positionViewAtIndex(candidateView.currentIndex, ListView.Contain); + return true; + } + + function activateCurrent() { + if (!ensureNavigationSelection(false)) { + return false; + } + + Feedback.play(Feedback.SelectionCommit); + candidateView.model.selectItem(candidateView.currentIndex); + return true; + } + + ListView { + id: candidateView + anchors.fill: parent + orientation: ListView.Horizontal + spacing: 0 + clip: true + boundsBehavior: Flickable.StopAtBounds + model: root.inputEngine ? root.inputEngine.wordCandidateListModel : null + + delegate: Item { + required property int index + required property string display + + width: Math.round(candidateLabel.implicitWidth + root.candidateHorizontalPadding * 2) + height: candidateView.height + readonly property bool navigationActive: root.navigationModeActive && candidateView.currentIndex === index + readonly property bool pressed: candidateTapHandler.pressed + + Rectangle { + anchors { + fill: parent + // Avoid separator + leftMargin: index > 0 ? Math.round(4 * BreezeConstants.scaleHint) : 0 + } + color: (navigationActive || pressed) ? BreezeConstants.popupHighlightColor : "transparent" + } + + QQC2.Label { + id: candidateLabel + anchors.left: parent.left + anchors.leftMargin: root.candidateHorizontalPadding + anchors.verticalCenter: parent.verticalCenter + text: display + color: BreezeConstants.selectionListTextColor + opacity: navigationActive || pressed ? 1 : 0.9 + font.family: BreezeConstants.fontFamily + font.weight: navigationActive || pressed ? Font.Medium : Font.Light + font.pixelSize: Math.round(44 * BreezeConstants.scaleHint) + } + + Rectangle { + visible: index > 0 + width: Math.round(4 * BreezeConstants.scaleHint) + height: Math.round(36 * BreezeConstants.scaleHint) + radius: width / 2 + color: BreezeConstants.selectionListSeparatorColor + anchors.verticalCenter: parent.verticalCenter + anchors.left: parent.left + z: 1 + } + + TapHandler { + id: candidateTapHandler + + onPressedChanged: { + if (pressed) { + Feedback.play(Feedback.Press); + } + } + + onTapped: { + candidateView.currentIndex = index; + Feedback.play(Feedback.SelectionCommit); + candidateView.model.selectItem(index); + } + } + } + } +} diff --git a/virtualkeyboard/components/LanguagePopup.qml b/virtualkeyboard/components/LanguagePopup.qml new file mode 100644 index 0000000..5a754a0 --- /dev/null +++ b/virtualkeyboard/components/LanguagePopup.qml @@ -0,0 +1,239 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +import QtQuick +import QtQuick.Controls as QQC2 +import QtQuick.Layouts +import QtQuick.Templates as T + +import org.kde.kirigami as Kirigami +import org.kde.plasma.keyboard.virtualkeyboard + +QQC2.Popup { + id: root + + property Item keyboardPanel + property var keyboardController: VirtualKeyboard.keyboardController + readonly property bool popupVisible: visible + readonly property int itemCount: languageListView.count + property int currentIndex: languageListView.currentIndex + readonly property string currentLayoutId: (currentIndex >= 0 && keyboardController && currentIndex < keyboardController.activeLayoutIds.length) + ? keyboardController.activeLayoutIds[currentIndex] : "" + + signal showSettings() + + parent: keyboardPanel + width: Kirigami.Units.gridUnit * 10 + height: Math.min(languageListView.contentHeight, Kirigami.Units.gridUnit * 48, keyboardPanel.height - padding * 2) + padding * 2 + padding: Kirigami.Units.smallSpacing + + modal: true + dim: false + + background: PopupBackground { + theme: BreezeConstants + } + + function showForItem(parentItem) { + if (!keyboardPanel || !parentItem) { + return; + } + + if (!keyboardController) { + return; + } + + currentIndex = keyboardController.currentLayoutIndex; + languageListView.positionViewAtIndex(currentIndex, ListView.Center); + + const point = parentItem.mapToItem(keyboardPanel, 0, 0); + const maxX = Math.max(0, keyboardPanel.width - width); + const desiredX = point.x + (parentItem.width - width) / 2; + + x = Math.max(0, Math.min(maxX, desiredX)); + y = Math.max(0, point.y - height); + open(); + } + + function moveSelection(delta) { + if (itemCount <= 0) { + return false; + } + + const nextIndex = Math.max(0, Math.min(itemCount - 1, currentIndex + delta)); + if (nextIndex === currentIndex) { + return false; + } + + currentIndex = nextIndex; + languageListView.positionViewAtIndex(currentIndex, ListView.Contain); + return true; + } + + function activateCurrent() { + if (!keyboardController || currentIndex < 0 || currentIndex >= keyboardController.activeLayoutIds.length) { + return false; + } + + keyboardController.setCurrentLayout(keyboardController.activeLayoutIds[currentIndex]); + close(); + return true; + } + + contentItem: ListView { + id: languageListView + footerPositioning: ListView.OverlayFooter + clip: true + spacing: 0 + + readonly property real rowPadding: Kirigami.Units.smallSpacing + + QQC2.ScrollBar.vertical: QQC2.ScrollBar {} + + model: root.keyboardController ? root.keyboardController.activeLayoutIds : [] + + delegate: QQC2.ItemDelegate { + required property string modelData + property bool navigationActive: root.currentLayoutId === modelData + + width: languageListView.width + highlighted: root.keyboardController && (root.keyboardController.layoutId === modelData || navigationActive) + leftPadding: languageListView.rowPadding + rightPadding: languageListView.rowPadding + topPadding: languageListView.rowPadding + bottomPadding: languageListView.rowPadding + topInset: 0; bottomInset: 0; rightInset: 0; leftInset: 0 + + background: Rectangle { + color: { + if (parent.down) { + return BreezeConstants.popupHighlightBorderColor + } + if (parent.highlighted || (parent.hovered && !Kirigami.Settings.tabletMode)) { + return BreezeConstants.popupHighlightColor + } + return "transparent" + } + radius: BreezeConstants.buttonRadius + border.width: 1 + border.color: { + if (parent.down || parent.highlighted || (parent.hovered && !Kirigami.Settings.tabletMode)) { + return BreezeConstants.popupHighlightBorderColor + } + return "transparent" + } + } + + contentItem: ColumnLayout { + spacing: 0 + + QQC2.Label { + id: layoutPackageLabel + Layout.fillWidth: true + text: root.keyboardController ? root.keyboardController.layoutDisplayName(modelData) : "" + color: BreezeConstants.popupTextColor + elide: Text.ElideRight + font.family: BreezeConstants.fontFamily + font.weight: Font.Light + } + + QQC2.Label { + id: layoutLabel + Layout.fillWidth: true + text: root.keyboardController ? root.keyboardController.layoutName(modelData) : "" + color: BreezeConstants.popupTextColor + opacity: 0.75 + elide: Text.ElideRight + font.family: BreezeConstants.fontFamily + font.weight: Font.Light + font.pixelSize: layoutPackageLabel.font.pixelSize * 0.8 + } + } + + onClicked: { + if (!root.keyboardController) { + return; + } + + root.currentIndex = root.keyboardController.activeLayoutIds.indexOf(modelData); + root.keyboardController.setCurrentLayout(modelData); + root.close(); + } + } + + footer: Rectangle { + z: 999 + width: languageListView.width + height: footerColumn.implicitHeight + color: BreezeConstants.popupBackgroundColor + + ColumnLayout { + id: footerColumn + anchors.fill: parent + spacing: Kirigami.Units.smallSpacing + + Kirigami.Separator { + Layout.fillWidth: true + } + + QQC2.ItemDelegate { + id: settingsButton + + Layout.fillWidth: true + leftPadding: languageListView.rowPadding + rightPadding: languageListView.rowPadding + topPadding: languageListView.rowPadding + bottomPadding: languageListView.rowPadding + topInset: 0; bottomInset: 0; rightInset: 0; leftInset: 0 + + background: Rectangle { + color: { + if (settingsButton.down) { + return BreezeConstants.popupHighlightBorderColor + } + if (settingsButton.hovered && !Kirigami.Settings.tabletMode) { + return BreezeConstants.popupHighlightColor + } + return "transparent" + } + radius: BreezeConstants.buttonRadius + border.width: 1 + border.color: { + if (settingsButton.down || (settingsButton.hovered && !Kirigami.Settings.tabletMode)) { + return BreezeConstants.popupHighlightBorderColor + } + return "transparent" + } + } + + contentItem: RowLayout { + spacing: Kirigami.Units.largeSpacing + + Kirigami.Icon { + source: "configure" + implicitWidth: Kirigami.Units.iconSizes.small + implicitHeight: implicitWidth + } + + QQC2.Label { + Layout.fillWidth: true + text: i18n("Settings") + color: BreezeConstants.popupTextColor + elide: Text.ElideRight + font.family: BreezeConstants.fontFamily + font.weight: Font.Light + } + } + + onClicked: { + root.showSettings() + root.close() + } + } + } + } + } +} diff --git a/src/qmlplugin/BreezePopup.qml b/virtualkeyboard/components/PopupBackground.qml similarity index 77% rename from src/qmlplugin/BreezePopup.qml rename to virtualkeyboard/components/PopupBackground.qml index 7035029..d70c6ef 100644 --- a/src/qmlplugin/BreezePopup.qml +++ b/virtualkeyboard/components/PopupBackground.qml @@ -1,5 +1,8 @@ -// SPDX-FileCopyrightText: 2025 Devin Lin -// SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ import QtQuick import QtQuick.Layouts diff --git a/virtualkeyboard/components/PreeditBubble.qml b/virtualkeyboard/components/PreeditBubble.qml new file mode 100644 index 0000000..480ade2 --- /dev/null +++ b/virtualkeyboard/components/PreeditBubble.qml @@ -0,0 +1,66 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +import QtQuick +import QtQuick.Controls as QQC2 + +import org.kde.plasma.keyboard.virtualkeyboard + +Item { + id: root + + property var inputEngine: VirtualKeyboard.inputEngine + readonly property bool hasPreedit: inputEngine && inputEngine.preeditText.length > 0 + readonly property string preeditPrefix: inputEngine ? inputEngine.preeditPrefix : "" + readonly property string preeditSuffix: { + if (!inputEngine) { + return ""; + } + if (preeditPrefix.length > 0 && inputEngine.preeditText.indexOf(preeditPrefix) === 0) { + return inputEngine.preeditText.slice(preeditPrefix.length); + } + return inputEngine.preeditText; + } + + visible: hasPreedit && inputEngine.preeditBubbleVisibleHint + implicitWidth: Math.round(preeditRow.implicitWidth + horizontalPadding * 2) + implicitHeight: Math.round(preeditRow.implicitHeight + verticalPadding * 2) + + readonly property real horizontalPadding: Math.round(20 * BreezeConstants.scaleHint) + readonly property real verticalPadding: Math.round(14 * BreezeConstants.scaleHint) + + PopupBackground { + anchors.fill: parent + theme: BreezeConstants + } + + Row { + id: preeditRow + anchors.left: parent.left + anchors.leftMargin: root.horizontalPadding + anchors.verticalCenter: parent.verticalCenter + spacing: Math.round(8 * BreezeConstants.scaleHint) + + QQC2.Label { + visible: root.preeditPrefix.length > 0 + text: root.preeditPrefix + color: BreezeConstants.popupTextColor + opacity: 0.7 + font.family: BreezeConstants.fontFamily + font.weight: Font.Medium + font.pixelSize: Math.round(34 * BreezeConstants.scaleHint) + } + + QQC2.Label { + text: root.preeditSuffix + color: BreezeConstants.popupTextColor + opacity: 0.95 + font.family: BreezeConstants.fontFamily + font.weight: Font.Light + font.pixelSize: Math.round(34 * BreezeConstants.scaleHint) + } + } +} diff --git a/virtualkeyboard/components/keys/AbstractKey.qml b/virtualkeyboard/components/keys/AbstractKey.qml new file mode 100644 index 0000000..915738c --- /dev/null +++ b/virtualkeyboard/components/keys/AbstractKey.qml @@ -0,0 +1,238 @@ +// SPDX-FileCopyrightText: 2025 Devin Lin +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import QtQuick.Controls as QQC2 +import QtQuick.Layouts + +import org.kde.kirigami as Kirigami +import org.kde.plasma.keyboard +import org.kde.plasma.keyboard.virtualkeyboard + +// Base visual component shared by all keyboard keys. + +Item { + id: root + + signal clicked() + + /** + * Text sent by the key and used as the default label. + */ + property string text: "" + + /** + * Icon name shown instead of text. + */ + property string iconName: "" + + /** + * Relative width hint used by the layout row when distributing space. + */ + property real weight: parent && parent.defaultKeyWeight !== undefined ? parent.defaultKeyWeight : 100 + + /** + * Text shown on the key face. + * This can differ from text when a key should display a label that is + * different from the committed text. + */ + property string displayText: text + + /** + * Small label shown in the corner of the key. + * If empty, no small corner label is shown. + */ + property string smallText: "" + + /** + * Alternate characters offered from the long-press popup. + * Layouts can provide this either as a string or as an explicit list. + */ + property var alternativeKeys: [] + readonly property var _normalizedAlternativeKeys: typeof alternativeKeys === "string" ? alternativeKeys.split("") : (alternativeKeys || []) + + /** + * Alternate keys after filtering out text itself. + */ + readonly property var effectiveAlternativeKeys: { + const textIndex = _normalizedAlternativeKeys.indexOf(text) + if (textIndex === -1) { + return _normalizedAlternativeKeys + } + return _normalizedAlternativeKeys.slice(0, textIndex).concat(_normalizedAlternativeKeys.slice(textIndex + 1)) + } + readonly property int effectiveAlternativeKeysHighlightIndex: { + const index = _normalizedAlternativeKeys.indexOf(text) + return index > 0 && (index + 1) === _normalizedAlternativeKeys.length ? index - 1 : index + } + + /** + * Display-only override for labels shown in the alternate-key popup. + */ + property var displayAlternativeKeys: effectiveAlternativeKeys + + /** + * Whether the button "looks" pressed. + */ + property bool pressedVisual: false + + /** + * Prevents shift and caps state from changing the displayed text. + */ + property bool noModifier: false + + /** + * Enables repeating activation while the key is held. + */ + property bool repeat: false + + /** + * Uses the secondary key background styling. + */ + property bool secondaryStyle: false + + /** + * Requests the selected key visual treatment. + */ + property bool highlighted: false + + /** + * Whether the key shows a keyboard navigation highlight. + */ + property bool navigationActive: false + + /** + * Marks this key as a function key for styling and preview behavior. + */ + property bool functionKey: false + + /** + * Controls whether the key-preview popup should be shown while pressed. + */ + property bool showPreview: enabled && !functionKey + + /** + * Whether the key label should follow uppercase display rules. + */ + property bool uppercased: VirtualKeyboard.inputEngine && VirtualKeyboard.inputEngine.uppercase && !noModifier + + /** + * Pixel size used for the main key label. + */ + property real textPixelSize: ((displayText.length > 1) ? 40 : 60) * scaleHint + + /** + * Local scale factor used for key text sizing. + */ + property real scaleHint: Math.max(0.3, Math.min(width / 220, height / 140)) + + /** + * Size used for icon-based keys. + */ + readonly property real iconSize: Math.round((functionKey ? 88 : 80) * BreezeConstants.keyIconScale) + + implicitHeight: Math.round(72 * BreezeConstants.scaleHint) + + // HACK: Layout.preferredWidth is used as a sort of size hint, not an exact size. + // If the weight is too large, preferredWidth gets capped out and stuff starts breaking + Layout.preferredWidth: weight / Math.max(parent && parent.defaultKeyWeight !== undefined ? parent.defaultKeyWeight : 100, 1) + Layout.minimumWidth: 0 + Layout.fillWidth: true + Layout.fillHeight: true + + function trigger() { + if (!enabled) { + return; + } + clicked(); + } + + function triggerByNavigation() { + trigger(); + } + + function playPressFeedback() { + Feedback.play(Feedback.Press); + } + + Item { + anchors.fill: parent + + Item { + anchors.fill: parent + anchors.leftMargin: BreezeConstants.keyBackgroundHorizontalMargin + anchors.rightMargin: BreezeConstants.keyBackgroundHorizontalMargin + anchors.topMargin: BreezeConstants.keyBackgroundVerticalMargin + anchors.bottomMargin: BreezeConstants.keyBackgroundVerticalMargin + + Kirigami.ShadowedRectangle { + anchors.fill: parent + color: { + if (root.pressedVisual) { + return root.secondaryStyle ? BreezeConstants.secondaryKeyPressedBackgroundColor : BreezeConstants.normalKeyPressedBackgroundColor + } + if (root.highlighted) { + return BreezeConstants.highlightedKeyBackgroundColor + } + return root.secondaryStyle ? BreezeConstants.secondaryKeyBackgroundColor : BreezeConstants.normalKeyBackgroundColor + } + radius: BreezeConstants.buttonRadius + + shadow.color: BreezeConstants.keyShadowColor + shadow.size: BreezeConstants.keyShadowSize + shadow.yOffset: BreezeConstants.keyShadowYOffset + } + + Rectangle { + anchors.fill: parent + visible: root.navigationActive + color: BreezeConstants.navigationHighlightColor + border.width: 3 + border.color: BreezeConstants.navigationHighlightBorderColor + radius: BreezeConstants.buttonRadius + border.width + } + + QQC2.Label { + id: mainTextLabel + anchors.centerIn: parent + text: root.uppercased ? root.displayText.toUpperCase() : root.displayText + visible: text.length > 0 && root.iconName.length === 0 + color: BreezeConstants.keyTextColor + + font { + family: BreezeConstants.fontFamily + weight: Font.Light + pixelSize: root.textPixelSize + } + } + + Kirigami.Icon { + anchors.centerIn: parent + source: root.iconName + visible: root.iconName.length > 0 + implicitHeight: root.iconSize + implicitWidth: root.iconSize + height: implicitHeight + width: implicitWidth + } + + QQC2.Label { + id: smallTextLabel + text: root.smallText + anchors.top: parent.top + anchors.right: parent.right + anchors.margins: BreezeConstants.keyContentMargin / 3 + color: BreezeConstants.keySmallTextColor + + font { + family: BreezeConstants.fontFamily + weight: Font.Light + pixelSize: 25 * scaleHint + } + + visible: text.length > 0 + } + } + } +} diff --git a/virtualkeyboard/components/keys/ActionKey.qml b/virtualkeyboard/components/keys/ActionKey.qml new file mode 100644 index 0000000..f4d4a38 --- /dev/null +++ b/virtualkeyboard/components/keys/ActionKey.qml @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick + +// Key for QML-only actions that don't send text or key events. + +AbstractKey { + id: root + + KeyMouseArea { + keyItem: root + + onReleaseFinished: { + root.trigger(); + } + } +} diff --git a/virtualkeyboard/components/keys/BackspaceKey.qml b/virtualkeyboard/components/keys/BackspaceKey.qml new file mode 100644 index 0000000..5e15b8d --- /dev/null +++ b/virtualkeyboard/components/keys/BackspaceKey.qml @@ -0,0 +1,14 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick + +Key { + key: Qt.Key_Backspace + iconName: "edit-clear-symbolic" + displayText: "" + functionKey: true + secondaryStyle: true + noModifier: true + repeat: true +} diff --git a/virtualkeyboard/components/keys/ChangeLanguageKey.qml b/virtualkeyboard/components/keys/ChangeLanguageKey.qml new file mode 100644 index 0000000..46b91de --- /dev/null +++ b/virtualkeyboard/components/keys/ChangeLanguageKey.qml @@ -0,0 +1,24 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick + +import org.kde.plasma.keyboard +import org.kde.plasma.keyboard.virtualkeyboard + +// Action key that opens the keyboard layout/language selector. + +ActionKey { + id: root + + iconName: "globe-symbolic" + displayText: "" + functionKey: true + secondaryStyle: true + + onClicked: { + if (VirtualKeyboard.languagePopup) { + VirtualKeyboard.languagePopup.showForItem(root) + } + } +} diff --git a/virtualkeyboard/components/keys/EnterKey.qml b/virtualkeyboard/components/keys/EnterKey.qml new file mode 100644 index 0000000..2883211 --- /dev/null +++ b/virtualkeyboard/components/keys/EnterKey.qml @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick + +Key { + key: Qt.Key_Return + iconName: "keyboard-enter-symbolic" + displayText: "" + functionKey: true + secondaryStyle: true + noModifier: true +} diff --git a/virtualkeyboard/components/keys/FillerKey.qml b/virtualkeyboard/components/keys/FillerKey.qml new file mode 100644 index 0000000..9891508 --- /dev/null +++ b/virtualkeyboard/components/keys/FillerKey.qml @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import QtQuick.Layouts + +// Invisible spacer to align keyboard rows without creating a key. + +Item { + property real weight: parent && parent.defaultKeyWeight !== undefined ? parent.defaultKeyWeight : 100 + + // HACK: Layout.preferredWidth is used as a sort of size hint, not an exact size. + // If the weight is too large, preferredWidth gets capped out and stuff starts breaking. + Layout.preferredWidth: weight / Math.max(parent && parent.defaultKeyWeight !== undefined ? parent.defaultKeyWeight : 100, 1) + Layout.minimumWidth: 0 + Layout.fillWidth: true + Layout.fillHeight: true +} diff --git a/virtualkeyboard/components/keys/FlickKey.qml b/virtualkeyboard/components/keys/FlickKey.qml new file mode 100644 index 0000000..99be00a --- /dev/null +++ b/virtualkeyboard/components/keys/FlickKey.qml @@ -0,0 +1,251 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick + +import org.kde.plasma.keyboard.virtualkeyboard + +// Key for 12-key layouts that supports directional flicks and repeated taps. + +AbstractKey { + id: root + + enum Direction { + Center, + Left, + Top, + Right, + Bottom + } + + /** + * Primary label shown on the key when no directional flick is active. + */ + property string baseText: text + + /** + * Text sent to the input method when the key is tapped without flicking. + */ + property string baseCommitText: baseText + + /** + * Commit texts for the directional alternatives. + * The order matches the visual alternative order after removing the base + * text from alternativeKeys. + */ + property var alternativeCommitTexts: [] + + /** + * Enables repeated-tap cycling for 12-key style layouts. + * When enabled, repeated center taps ask the input method to replace the + * previously entered chunk with the next entry from the tap sequence. + */ + property bool tapSequenceEnabled: false + + /** + * Commit texts used for repeated center taps. Leave empty to use the + * base commit text followed by the directional alternative commit texts. + */ + property var tapSequenceCommitTexts: [] + + /** + * Currently highlighted label while the pointer is down. + */ + property string currentText: baseText + + /** + * Commit text paired with currentText. + */ + property string currentCommitText: baseCommitText + + property int __tapSequenceIndex: -1 + property point __pressPoint: Qt.point(0, 0) + + /** + * Distance from the press point that still counts as a center tap. + */ + readonly property real __centerRadius: width * 0.4 + + /** + * The list of flickable alternate keys, not including the base character. + */ + readonly property var flickKeys: { + // Alternative keys can either be string or array + const keys = typeof alternativeKeys === "string" ? alternativeKeys.split("") : (alternativeKeys || []); + const baseIndex = keys.indexOf(baseText); + if (baseIndex === -1) { + return keys; + } + return keys.slice(0, baseIndex).concat(keys.slice(baseIndex + 1)); + } + + // The visual alternative order is center, left, top, right, bottom. + readonly property string flickLeft: flickKeys.length > 0 ? flickKeys[0] : "" + readonly property string flickTop: flickKeys.length > 2 ? flickKeys[1] : "" + readonly property string flickBottom: flickKeys.length > 3 ? flickKeys[3] : (flickKeys.length > 2 ? flickKeys[2] : "") + readonly property string flickRight: flickKeys.length > 3 ? flickKeys[2] : (flickKeys.length === 2 ? flickKeys[1] : "") + readonly property string __flickCommitLeft: alternativeCommitTexts.length > 0 ? alternativeCommitTexts[0] : flickLeft + readonly property string __flickCommitTop: alternativeCommitTexts.length > 2 ? alternativeCommitTexts[1] : flickTop + readonly property string __flickCommitBottom: alternativeCommitTexts.length > 3 ? alternativeCommitTexts[3] : (alternativeCommitTexts.length > 2 ? alternativeCommitTexts[2] : flickBottom) + readonly property string __flickCommitRight: alternativeCommitTexts.length > 3 ? alternativeCommitTexts[2] : (alternativeCommitTexts.length === 2 ? alternativeCommitTexts[1] : flickRight) + + /** + * Ordered commit texts used for repeated center taps. + */ + readonly property var __tapSequenceCommitTexts: tapSequenceCommitTexts.length > 0 ? tapSequenceCommitTexts : [baseCommitText].concat(alternativeCommitTexts) + + displayText: pressedVisual ? currentText : baseText + + function __clearTapSequence() { + __tapSequenceIndex = -1; + tapSequenceTimer.stop(); + pressedVisual = false; + FlickKeyPrivate.clearActiveTapSequenceKey(root); + } + + function __resetCurrentText() { + currentText = baseText; + currentCommitText = baseCommitText; + } + + // Get the angle that the given point is from the initial "tap point" + function __angle(point) { + const dx = point.x - __pressPoint.x; + const dy = point.y - __pressPoint.y; + const theta = Math.atan2(-dy, dx) * 360 / (2 * Math.PI); + return theta < 0 ? theta + 360 : theta; + } + + function __distance(point) { + const dx = point.x - __pressPoint.x; + const dy = point.y - __pressPoint.y; + return Math.sqrt(dx * dx + dy * dy); + } + + function __directionForPoint(point) { + if (__distance(point) < __centerRadius) { + return FlickKey.Direction.Center; + } + + const currentAngle = __angle(point); + if (currentAngle < 45 || currentAngle > 315) { + return FlickKey.Direction.Right; + } + if (currentAngle < 135) { + return FlickKey.Direction.Top; + } + if (currentAngle < 225) { + return FlickKey.Direction.Left; + } + return FlickKey.Direction.Bottom; + } + + function __keyForText(textValue) { + return textValue && textValue.length === 1 ? textValue.charCodeAt(0) : Qt.Key_unknown; + } + + function __commitTapSequence() { + if (!tapSequenceEnabled || __tapSequenceCommitTexts.length === 0) { + return false; + } + + let nextIndex = 0; + if (tapSequenceTimer.running) { + // Cycle through the possible keys if the tapSequenceTimer is running + nextIndex = (__tapSequenceIndex + 1) % __tapSequenceCommitTexts.length; + if (__tapSequenceIndex >= 0 && VirtualKeyboard.inputEngine.textComposer.replaceLastInput(__tapSequenceCommitTexts[nextIndex])) { + __tapSequenceIndex = nextIndex; + tapSequenceTimer.restart(); + pressedVisual = true; + FlickKeyPrivate.setActiveTapSequenceKey(root); + return true; + } + } + + __tapSequenceIndex = 0; + tapSequenceTimer.restart(); + pressedVisual = true; + FlickKeyPrivate.setActiveTapSequenceKey(root); + return false; + } + + function trigger() { + if (!enabled) { + return; + } + VirtualKeyboard.inputEngine.sendTextComposerKey(root.__keyForText(root.baseText), root.baseCommitText); + clicked(); + } + + function __updateCurrentText(x, y) { + const direction = __directionForPoint(Qt.point(x, y)); + switch (direction) { + case FlickKey.Direction.Left: + currentText = flickLeft || baseText; + currentCommitText = __flickCommitLeft || currentText; + break; + case FlickKey.Direction.Top: + currentText = flickTop || baseText; + currentCommitText = __flickCommitTop || currentText; + break; + case FlickKey.Direction.Right: + currentText = flickRight || baseText; + currentCommitText = __flickCommitRight || currentText; + break; + case FlickKey.Direction.Bottom: + currentText = flickBottom || baseText; + currentCommitText = __flickCommitBottom || currentText; + break; + default: + __resetCurrentText(); + break; + } + } + + Timer { + id: tapSequenceTimer + interval: 1000 + repeat: false + onTriggered: root.__clearTapSequence(); + } + + KeyMouseArea { + keyItem: root + + onPressStarted: (point) => { + root.__pressPoint = Qt.point(point.x, point.y); + root.__resetCurrentText(); + VirtualKeyboard.flickPreviewPopup.openForKey(root); + } + + onPositionChanged: (point) => { + root.__updateCurrentText(point.x, point.y); + VirtualKeyboard.flickPreviewPopup.updateFromKey(root); + } + + onReleaseFinished: { + VirtualKeyboard.flickPreviewPopup.close(); + + const usedExplicitFlick = root.currentText !== root.baseText || root.currentCommitText !== root.baseCommitText; + if (usedExplicitFlick) { + root.__clearTapSequence(); + } else if (root.__commitTapSequence()) { + root.clicked(); + root.__resetCurrentText(); + return; + } + + VirtualKeyboard.inputEngine.sendTextComposerKey(root.__keyForText(root.currentText), root.currentCommitText); + root.clicked(); + root.__resetCurrentText(); + } + + onCancelFinished: { + VirtualKeyboard.flickPreviewPopup.close(); + root.__clearTapSequence(); + root.__resetCurrentText(); + } + } + + Component.onDestruction: FlickKeyPrivate.clearActiveTapSequenceKey(root) +} diff --git a/virtualkeyboard/components/keys/FlickKeyPrivate.qml b/virtualkeyboard/components/keys/FlickKeyPrivate.qml new file mode 100644 index 0000000..ef790c1 --- /dev/null +++ b/virtualkeyboard/components/keys/FlickKeyPrivate.qml @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +pragma Singleton + +import QtQuick + +QtObject { + property var activeTapSequenceKey: null + + function keyPressStarted(key) { + if (activeTapSequenceKey && activeTapSequenceKey !== key) { + activeTapSequenceKey.__clearTapSequence(); + activeTapSequenceKey = null; + } + } + + function setActiveTapSequenceKey(key) { + activeTapSequenceKey = key; + } + + function clearActiveTapSequenceKey(key) { + if (activeTapSequenceKey === key) { + activeTapSequenceKey = null; + } + } +} diff --git a/virtualkeyboard/components/keys/HideKeyboardKey.qml b/virtualkeyboard/components/keys/HideKeyboardKey.qml new file mode 100644 index 0000000..da14f87 --- /dev/null +++ b/virtualkeyboard/components/keys/HideKeyboardKey.qml @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick + +import org.kde.plasma.keyboard.virtualkeyboard + +// Action key to hide the keyboard. + +ActionKey { + id: root + + iconName: "input-keyboard-virtual-hide-symbolic" + displayText: "" + functionKey: true + secondaryStyle: true + + onClicked: if (VirtualKeyboard.inputMethodConnection) VirtualKeyboard.inputMethodConnection.hide() +} diff --git a/virtualkeyboard/components/keys/InputModeKey.qml b/virtualkeyboard/components/keys/InputModeKey.qml new file mode 100644 index 0000000..2a5cc05 --- /dev/null +++ b/virtualkeyboard/components/keys/InputModeKey.qml @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick + +import org.kde.plasma.keyboard.virtualkeyboard + +// Action key that cycles through input modes provided by a keyboard layout. + +ActionKey { + id: root + + /** + * Input modes to cycle through (that the text composer supports). + */ + property var modes: [] + + /** + * Text composer to set the mode of. + */ + property var textComposer + + /** + * Whether to show the next mode as the current text on the key, instead of + * the currently active mode. + */ + property bool showNextMode: false + + readonly property string __currentInputMode: textComposer && textComposer.inputMode !== undefined ? textComposer.inputMode : "" + readonly property var __modes: (modes || []) + .map(function(mode) { + if (typeof mode === "string") { + return { value: mode, label: mode }; + } + return { + value: mode.value ?? "", + label: mode.label ?? mode.value ?? "" + }; + }) + .filter(function(mode) { + return mode.value.length > 0; + }) + readonly property int __currentIndex: __modes.findIndex(function(mode) { + return mode.value === __currentInputMode; + }) + readonly property var __currentMode: __currentIndex >= 0 ? __modes[__currentIndex] : (__modes[0] ?? null) + readonly property var __nextMode: __modes.length === 0 ? null : __modes[(__currentIndex + 1) % __modes.length] + readonly property var __displayedMode: showNextMode ? __nextMode : __currentMode + + displayText: __displayedMode ? __displayedMode.label : "Mode" + functionKey: true + secondaryStyle: true + + onClicked: { + if (textComposer && __nextMode) { + textComposer.inputMode = __nextMode.value; + } + } +} diff --git a/virtualkeyboard/components/keys/Key.qml b/virtualkeyboard/components/keys/Key.qml new file mode 100644 index 0000000..4ffb831 --- /dev/null +++ b/virtualkeyboard/components/keys/Key.qml @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: 2025 Devin Lin +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick + +import org.kde.plasma.keyboard.virtualkeyboard + +// Standard key that sends text/key clicks through the input method. + +AbstractKey { + id: root + + /** + * Logical key code sent to the input engine when the key is activated. + */ + property int key: Qt.Key_unknown + + property string commitText: root.text + property bool noKeyEvent: key === Qt.Key_unknown && commitText.length === 0 + readonly property bool alternativeKeysActive: { + const popup = VirtualKeyboard.alternativeKeysPopup; + return !!(popup && popup.active && popup.ownerKey === root); + } + + function trigger() { + if (!enabled) { + return; + } + if (!noKeyEvent) { + commitKeyText(root.commitText); + } + clicked(); + } + + function commitAlternativeText(text) { + commitKeyText(text); + } + + function commitKeyText(text) { + const engine = VirtualKeyboard.inputEngine; + if (engine) { + engine.sendTextComposerKey(root.key, text); + } + } + + KeyMouseArea { + keyItem: root + repeatEnabled: root.repeat && !root.noKeyEvent + pressAndHoldInterval: 500 + + onRepeatTriggered: root.commitKeyText(root.commitText) + + onPressStarted: (mouse) => { + const popup = VirtualKeyboard.alternativeKeysPopup; + if (popup && popup.active && popup.ownerKey !== root) { + popup.close(); + } + + const characterPopup = VirtualKeyboard.characterPopup; + if (characterPopup) { + characterPopup.openForKey(root); + } + } + + onPressAndHold: (mouse) => { + const popup = VirtualKeyboard.alternativeKeysPopup; + if (!popup || root.effectiveAlternativeKeys.length === 0) { + return; + } + + if (popup.openForKey(root)) { + const characterPopup = VirtualKeyboard.characterPopup; + if (characterPopup) { + characterPopup.closeForKey(root); + } + stopRepeat(); + } + } + + onPositionChanged: (mouse) => { + const popup = VirtualKeyboard.alternativeKeysPopup; + if (pressed && popup && popup.active && popup.ownerKey === root) { + popup.moveFromKey(root, mouse.x); + } + } + + onReleaseFinished: (mouse) => { + const characterPopup = VirtualKeyboard.characterPopup; + if (characterPopup) { + characterPopup.closeForKey(root); + } + + const popup = VirtualKeyboard.alternativeKeysPopup; + if (popup && popup.active && popup.ownerKey === root) { + popup.commitCurrent(); + return; + } + + if (root.noKeyEvent) { + root.clicked(); + return; + } + + if (!root.repeat) { + root.commitKeyText(root.commitText); + } + root.clicked(); + } + + onCancelFinished: { + const characterPopup = VirtualKeyboard.characterPopup; + if (characterPopup) { + characterPopup.closeForKey(root); + } + + const popup = VirtualKeyboard.alternativeKeysPopup; + if (popup && popup.active && popup.ownerKey === root) { + popup.close(); + return; + } + } + } +} diff --git a/virtualkeyboard/components/keys/KeyMouseArea.qml b/virtualkeyboard/components/keys/KeyMouseArea.qml new file mode 100644 index 0000000..4048de8 --- /dev/null +++ b/virtualkeyboard/components/keys/KeyMouseArea.qml @@ -0,0 +1,154 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick + +// Controller for tap/hold/swiping on keys. +// Implements key repeat, press-and-hold, listening to swipe positions, all +// while not taking exclusive grab (so multiple keys can be pressed at the +// same time). + +MultiPointTouchArea { + id: root + + /** + * Key item that owns the pressed visual state and feedback behavior. + */ + required property Item keyItem + + /** + * Whether holding this key should repeatedly trigger repeatTriggered. + */ + property bool repeatEnabled: keyItem.repeat + + /** + * Delay before key repeat starts. + */ + property int repeatDelay: 600 + + /** + * Interval used after key repeat starts. + */ + property int repeatInterval: 50 + + /** + * Delay before pressAndHold is emitted. + */ + property int pressAndHoldInterval: 800 + + property bool __pressed: false + property var __lastPoint: touchPoint + + signal pressStarted(var point) + signal pressAndHold(var point) + signal positionChanged(var point) + signal releaseFinished(var point) + signal cancelFinished() + signal repeatTriggered() + + anchors.fill: parent + z: 1 + minimumTouchPoints: 1 + maximumTouchPoints: 1 + mouseEnabled: true + + function stopRepeat() { + repeatDelayTimer.stop(); + repeatTimer.stop(); + } + + function startPress(point) { + if (root.__pressed) { + cancelPress(); + } + + root.__pressed = true; + root.__lastPoint = point; + FlickKeyPrivate.keyPressStarted(keyItem); + keyItem.pressedVisual = true; + keyItem.playPressFeedback(); + root.pressStarted(point); + pressAndHoldTimer.restart(); + if (root.repeatEnabled) { + root.repeatTriggered(); + repeatDelayTimer.start(); + } + } + + function updatePress(point) { + if (!root.__pressed) { + return; + } + + root.__lastPoint = point; + root.positionChanged(point); + } + + function finishPress(point) { + if (!root.__pressed) { + return; + } + + root.__pressed = false; + root.__lastPoint = point; + keyItem.pressedVisual = false; + pressAndHoldTimer.stop(); + root.stopRepeat(); + root.releaseFinished(point); + } + + function cancelPress() { + if (!root.__pressed) { + return; + } + + root.__pressed = false; + keyItem.pressedVisual = false; + pressAndHoldTimer.stop(); + root.stopRepeat(); + root.cancelFinished(); + } + + touchPoints: [ + TouchPoint { + id: touchPoint + } + ] + + Timer { + id: repeatDelayTimer + interval: root.repeatDelay + repeat: false + onTriggered: repeatTimer.start() + } + + Timer { + id: repeatTimer + interval: root.repeatInterval + repeat: true + onTriggered: root.repeatTriggered() + } + + Timer { + id: pressAndHoldTimer + interval: root.pressAndHoldInterval + repeat: false + onTriggered: root.pressAndHold(root.__lastPoint) + } + + onPressed: { + root.startPress(touchPoint); + } + + onUpdated: { + root.updatePress(touchPoint); + } + + onReleased: { + root.finishPress(touchPoint); + } + + onCanceled: { + root.cancelPress(); + } +} diff --git a/virtualkeyboard/components/keys/KeysymKey.qml b/virtualkeyboard/components/keys/KeysymKey.qml new file mode 100644 index 0000000..2e4cc44 --- /dev/null +++ b/virtualkeyboard/components/keys/KeysymKey.qml @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick + +import org.kde.plasma.keyboard.virtualkeyboard + +// Desktop key that sends a keysym (ex. modifier) rather than a typical textual key. + +AbstractKey { + id: root + + /** + * Logical key code sent through KWin fake input when the key is activated. + */ + property int key: Qt.Key_unknown + + /** + * Whether this key toggles between pressed and released when tapped. + */ + property bool sticky: false + + /** + * Whether this key is currently pressed through the direct key backend. + */ + readonly property bool keyPressed: VirtualKeyboard.inputEngine && VirtualKeyboard.inputEngine.pressedKeys.indexOf(root.key) !== -1 + + functionKey: true + secondaryStyle: true + noModifier: true + showPreview: false + highlighted: keyPressed + + function sendPressed(pressed) { + if (VirtualKeyboard.inputEngine) { + VirtualKeyboard.inputEngine.sendDirectKey(root.key, pressed); + } + } + + function sendClick() { + root.sendPressed(true); + root.sendPressed(false); + } + + function trigger() { + if (!enabled) { + return; + } + if (root.sticky) { + root.sendPressed(!root.keyPressed); + } else { + root.sendClick(); + } + clicked(); + } + + KeyMouseArea { + keyItem: root + repeatEnabled: root.repeat + + onRepeatTriggered: root.sendClick() + + onReleaseFinished: { + if (!root.repeat) { + if (root.sticky) { + root.sendPressed(!root.keyPressed); + } else { + root.sendClick(); + } + } + root.clicked() + } + } +} diff --git a/virtualkeyboard/components/keys/ShiftKey.qml b/virtualkeyboard/components/keys/ShiftKey.qml new file mode 100644 index 0000000..24b24f7 --- /dev/null +++ b/virtualkeyboard/components/keys/ShiftKey.qml @@ -0,0 +1,98 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import org.kde.plasma.keyboard.virtualkeyboard + +// Action key that toggles shift and enables caps lock on double tap. + +ActionKey { + id: shiftKey + + /** + * Whether this simulates a keyboard "shift click". + * Desktop layouts use this so Shift+letter behaves like a real + * keyboard shortcut/key event. Mobile layouts should leave this off. + */ + property bool sendDirectKeyEvents: false + + property int __doubleTapIntervalMs: 250 + property double __lastTapTimestamp: 0 + + iconName: { + if (!VirtualKeyboard.inputEngine) { + return "keyboard-caps-disabled-symbolic" + } + if (VirtualKeyboard.inputEngine.capsLockActive) { + return "keyboard-caps-locked-symbolic" + } + if (VirtualKeyboard.inputEngine.shiftActive) { + return "keyboard-caps-enabled-symbolic" + } + return "keyboard-caps-disabled-symbolic" + } + displayText: "" + functionKey: true + secondaryStyle: true + highlighted: VirtualKeyboard.inputEngine && (VirtualKeyboard.inputEngine.shiftActive || VirtualKeyboard.inputEngine.capsLockActive) + + function syncDirectShift() { + if (sendDirectKeyEvents && VirtualKeyboard.inputEngine) { + VirtualKeyboard.inputEngine.sendDirectKey(Qt.Key_Shift, VirtualKeyboard.inputEngine.shiftActive); + } + } + + Connections { + target: VirtualKeyboard.inputEngine + + function onPressedKeysChanged() { + if (!sendDirectKeyEvents || !VirtualKeyboard.inputEngine) { + return; + } + if (VirtualKeyboard.inputEngine.capsLockActive || !VirtualKeyboard.inputEngine.shiftActive) { + return; + } + + const pressedKeys = VirtualKeyboard.inputEngine.pressedKeys; + const shiftPressed = pressedKeys.indexOf(Qt.Key_Shift) !== -1; + if (!shiftPressed) { + VirtualKeyboard.inputEngine.shiftActive = false; + return; + } + + if (pressedKeys.length === 1 && pressedKeys[0] === Qt.Key_Shift) { + return; + } + } + } + + onClicked: { + if (!VirtualKeyboard.inputEngine) { + return; + } + + const now = Date.now(); + + if (VirtualKeyboard.inputEngine.capsLockActive) { + VirtualKeyboard.inputEngine.capsLockActive = false; + VirtualKeyboard.inputEngine.shiftActive = false; + __lastTapTimestamp = 0; + shiftKey.syncDirectShift(); + return; + } + + if (VirtualKeyboard.inputEngine.shiftActive) { + if (__lastTapTimestamp > 0 && (now - __lastTapTimestamp) <= __doubleTapIntervalMs) { + VirtualKeyboard.inputEngine.capsLockActive = true; + VirtualKeyboard.inputEngine.shiftActive = false; + } else { + VirtualKeyboard.inputEngine.shiftActive = false; + } + __lastTapTimestamp = 0; + } else { + VirtualKeyboard.inputEngine.shiftActive = true; + __lastTapTimestamp = now; + } + shiftKey.syncDirectShift(); + } +} diff --git a/virtualkeyboard/components/keys/SpaceKey.qml b/virtualkeyboard/components/keys/SpaceKey.qml new file mode 100644 index 0000000..ede9b95 --- /dev/null +++ b/virtualkeyboard/components/keys/SpaceKey.qml @@ -0,0 +1,17 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick + +import org.kde.plasma.keyboard.virtualkeyboard + +// Space key that labels itself with the current input language. + +Key { + key: Qt.Key_Space + text: " " + displayText: VirtualKeyboard.inputEngine ? Qt.locale(VirtualKeyboard.inputEngine.locale).nativeLanguageName : "" + noModifier: true + showPreview: false + textPixelSize: 24 * scaleHint +} diff --git a/virtualkeyboard/components/keys/SymbolModeKey.qml b/virtualkeyboard/components/keys/SymbolModeKey.qml new file mode 100644 index 0000000..6b2e877 --- /dev/null +++ b/virtualkeyboard/components/keys/SymbolModeKey.qml @@ -0,0 +1,17 @@ +// SPDX-FileCopyrightText: 2026 Devin Lin +// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL + +import QtQuick +import org.kde.plasma.keyboard.virtualkeyboard + +// Action key that switches between the main and symbol layouts. + +ActionKey { + id: root + + displayText: "?123" + functionKey: true + secondaryStyle: true + + onClicked: VirtualKeyboard.keyboardController.symbolMode = !VirtualKeyboard.keyboardController.symbolMode +} diff --git a/virtualkeyboard/inputbackend.cpp b/virtualkeyboard/inputbackend.cpp new file mode 100644 index 0000000..f8afe2a --- /dev/null +++ b/virtualkeyboard/inputbackend.cpp @@ -0,0 +1,52 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "inputbackend.h" + +#include + +InputBackend::InputBackend(QObject *parent) + : QObject(parent) +{ +} + +InputBackend::~InputBackend() = default; + +QList InputBackend::pressedKeys() const +{ + return m_pressedKeys; +} + +void InputBackend::clearPressedKeys() +{ + const QList keys = m_pressedKeys; + for (const int key : keys) { + sendKeyPressed(key, false); + } +} + +void InputBackend::reset() +{ + clearPressedKeys(); + Q_EMIT resetRequested(); +} + +void InputBackend::setKeyPressed(int key, bool pressed) +{ + if (pressed) { + if (m_pressedKeys.contains(key)) { + return; + } + m_pressedKeys.append(key); + std::sort(m_pressedKeys.begin(), m_pressedKeys.end()); + } else { + if (!m_pressedKeys.removeAll(key)) { + return; + } + } + + Q_EMIT pressedKeysChanged(); +} diff --git a/virtualkeyboard/inputbackend.h b/virtualkeyboard/inputbackend.h new file mode 100644 index 0000000..9d8a09e --- /dev/null +++ b/virtualkeyboard/inputbackend.h @@ -0,0 +1,53 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include +#include +#include + +/** + * Interface between the input engine <-> platform (compositor, such as KWin). + * + * Abstract class that should be implemented for the platform that receives events from the input engine. + */ +class InputBackend : public QObject +{ + Q_OBJECT + +public: + explicit InputBackend(QObject *parent = nullptr); + virtual ~InputBackend(); + + virtual bool isActive() const = 0; + virtual Qt::InputMethodHints inputMethodHints() const = 0; + virtual QString surroundingText() const = 0; + virtual uint32_t cursorPositionUtf8() const = 0; + virtual uint32_t anchorPositionUtf8() const = 0; + QList pressedKeys() const; + + virtual void setPreeditText(const QString &text) = 0; + virtual void commitText(const QString &text) = 0; + virtual void deleteSurroundingText(int index, int length) = 0; + virtual bool sendKeyClick(int key) = 0; + virtual bool sendKeyPressed(int key, bool pressed) = 0; + void clearPressedKeys(); + void reset(); + +Q_SIGNALS: + void activeChanged(); + void surroundingTextChanged(); + void inputMethodHintsChanged(); + void pressedKeysChanged(); + void resetRequested(); + +protected: + void setKeyPressed(int key, bool pressed); + +private: + QList m_pressedKeys; +}; diff --git a/virtualkeyboard/inputengine.cpp b/virtualkeyboard/inputengine.cpp new file mode 100644 index 0000000..49803f9 --- /dev/null +++ b/virtualkeyboard/inputengine.cpp @@ -0,0 +1,456 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "inputengine.h" + +#include "inputbackend.h" +#include "textcomposers/abstracttextcomposer.h" + +#include + +static bool isNonShiftModifierKey(int key) +{ + switch (key) { + case Qt::Key_Control: + case Qt::Key_Alt: + case Qt::Key_Meta: + case Qt::Key_AltGr: + return true; + default: + return false; + } +} + +InputEngine::InputEngine(InputBackend *backend, QObject *parent) + : QObject(parent) + , m_backend(backend) + , m_locale(QLocale().name()) +{ + Q_ASSERT(m_backend); + connectBackend(); + connect(this, &InputEngine::uppercaseChanged, this, [this] { + if (!m_textComposer) { + return; + } + m_textComposer->setTextCase(uppercase() ? AbstractTextComposer::TextCase::Upper : AbstractTextComposer::TextCase::Lower); + }); + connect(this, &InputEngine::textComposerChanged, this, [this] { + if (!m_textComposer) { + return; + } + m_textComposer->setTextCase(uppercase() ? AbstractTextComposer::TextCase::Upper : AbstractTextComposer::TextCase::Lower); + }); + connect(this, &InputEngine::preeditTextChanged, this, &InputEngine::updateAutomaticShift); +} + +AbstractTextComposer *InputEngine::textComposer() const +{ + return m_textComposer; +} + +void InputEngine::setTextComposer(AbstractTextComposer *textComposer) +{ + if (m_textComposer == textComposer) { + return; + } + + if (m_textComposer) { + disconnect(m_textComposer, &AbstractTextComposer::autoCapitalizationSupportedChanged, this, &InputEngine::resetShiftState); + disconnect(m_textComposer, &AbstractTextComposer::autoCapitalizationPolicyChanged, this, &InputEngine::updateAutomaticShift); + m_textComposer->reset(); + m_textComposer->setParent(this); + } + + m_textComposer = textComposer; + if (m_textComposer) { + m_textComposer->setParent(this); + m_textComposer->setInputEngine(this); + m_textComposer->setTextCase(uppercase() ? AbstractTextComposer::TextCase::Upper : AbstractTextComposer::TextCase::Lower); + connect(m_textComposer, &AbstractTextComposer::autoCapitalizationSupportedChanged, this, &InputEngine::resetShiftState); + connect(m_textComposer, &AbstractTextComposer::autoCapitalizationPolicyChanged, this, &InputEngine::updateAutomaticShift); + } + Q_EMIT textComposerChanged(); + + if (!m_textComposer || !m_textComposer->autoCapitalizationSupported()) { + setCapsLockActive(false); + setShiftActive(false); + } else if (inputMethodHints().testAnyFlags(Qt::ImhPreferUppercase | Qt::ImhUppercaseOnly)) { + resetShiftState(); + } else { + updateAutomaticShift(); + } +} + +bool InputEngine::shiftActive() const +{ + return m_shiftActive; +} + +void InputEngine::setShiftActive(bool active) +{ + if (m_shiftActive == active) { + return; + } + + m_shiftActive = active; + if (!m_shiftActive && m_backend->pressedKeys().contains(Qt::Key_Shift)) { + m_backend->sendKeyPressed(Qt::Key_Shift, false); + } + Q_EMIT shiftActiveChanged(); + Q_EMIT uppercaseChanged(); +} + +bool InputEngine::capsLockActive() const +{ + return m_capsLockActive; +} + +void InputEngine::setCapsLockActive(bool active) +{ + if (m_capsLockActive == active) { + return; + } + + m_capsLockActive = active; + Q_EMIT capsLockActiveChanged(); + Q_EMIT uppercaseChanged(); +} + +bool InputEngine::uppercase() const +{ + if (m_capsLockActive) { + return true; + } + if (!m_shiftActive) { + return false; + } + + for (const int key : m_backend->pressedKeys()) { + if (isNonShiftModifierKey(key)) { + return false; + } + } + + return true; +} + +QString InputEngine::preeditText() const +{ + return m_preeditText; +} + +void InputEngine::setPreeditText(const QString &text) +{ + if (m_preeditText == text) { + return; + } + + m_preeditText = text; + m_backend->setPreeditText(text); + Q_EMIT preeditTextChanged(); +} + +QString InputEngine::preeditPrefix() const +{ + return m_preeditPrefix; +} + +void InputEngine::setPreeditPrefix(const QString &text) +{ + if (m_preeditPrefix == text) { + return; + } + + m_preeditPrefix = text; + Q_EMIT preeditPrefixChanged(); +} + +QStringList InputEngine::candidates() const +{ + return m_candidates; +} + +void InputEngine::setCandidates(const QStringList &candidates) +{ + if (m_candidates == candidates) { + return; + } + + m_candidates = candidates; + Q_EMIT candidatesChanged(); + Q_EMIT wordCandidateListVisibleHintChanged(); +} + +QString InputEngine::locale() const +{ + return m_locale; +} + +void InputEngine::setLocale(const QString &locale) +{ + if (m_locale == locale) { + return; + } + + m_locale = locale; + Q_EMIT localeChanged(); +} + +int InputEngine::anchorPosition() const +{ + return utf16PositionFromUtf8Offset(m_backend->anchorPositionUtf8()); +} + +int InputEngine::cursorPosition() const +{ + return utf16PositionFromUtf8Offset(m_backend->cursorPositionUtf8()); +} + +Qt::InputMethodHints InputEngine::inputMethodHints() const +{ + return m_backend->inputMethodHints(); +} + +QString InputEngine::surroundingText() const +{ + return m_backend->surroundingText(); +} + +QString InputEngine::selectedText() const +{ + const QByteArray utf8 = surroundingText().toUtf8(); + const int start = qMin(m_backend->cursorPositionUtf8(), m_backend->anchorPositionUtf8()); + const int end = qMax(m_backend->cursorPositionUtf8(), m_backend->anchorPositionUtf8()); + return QString::fromUtf8(utf8.mid(start, end - start)); +} + +QList InputEngine::pressedKeys() const +{ + return m_backend->pressedKeys(); +} + +bool InputEngine::preeditBubbleVisibleHint() const +{ + return m_textComposer && m_textComposer->showsPreeditBubble(); +} + +WordCandidateListModel *InputEngine::wordCandidateListModel() const +{ + if (!m_wordCandidateListModel) { + m_wordCandidateListModel = new WordCandidateListModel(const_cast(this), const_cast(this)); + } + return m_wordCandidateListModel; +} + +bool InputEngine::wordCandidateListVisibleHint() const +{ + return !m_candidates.isEmpty(); +} + +bool InputEngine::sendTextComposerKey(int key, const QString &text) +{ + if (!m_textComposer) { + return false; + } + + if (!m_backend->pressedKeys().isEmpty()) { + return sendDirectKeyClick(key); + } + + return m_textComposer->keyEvent(Qt::Key(key), text); +} + +bool InputEngine::sendDirectKey(int key, bool pressed) +{ + return m_backend->sendKeyPressed(key, pressed); +} + +bool InputEngine::isKeyPressed(int key) const +{ + return m_backend->pressedKeys().contains(key); +} + +bool InputEngine::selectCandidate(int index) +{ + if (!m_textComposer) { + return false; + } + + return m_textComposer->selectCandidate(index); +} + +void InputEngine::commit() +{ + if (!m_preeditText.isEmpty()) { + m_backend->commitText(m_preeditText); + clearCompositionState(true); + } +} + +void InputEngine::commit(const QString &text, int replaceFrom, int replaceLength) +{ + if (replaceLength != 0) { + m_backend->deleteSurroundingText(replaceFrom, replaceLength); + } + + if (!text.isEmpty()) { + m_backend->commitText(text); + } + + clearCompositionState(true); +} + +void InputEngine::clear() +{ + clearCompositionState(true); +} + +bool InputEngine::handleKeyCommit(int key, const QString &text) +{ + switch (key) { + case Qt::Key_Backspace: + case Qt::Key_Delete: + case Qt::Key_Left: + case Qt::Key_Right: + case Qt::Key_Up: + case Qt::Key_Down: + case Qt::Key_Home: + case Qt::Key_End: + case Qt::Key_Return: + case Qt::Key_Enter: + case Qt::Key_Tab: + case Qt::Key_Space: + m_backend->sendKeyClick(key); + return true; + default: + break; + } + + if (text.isEmpty()) { + return false; + } + + commit(text); + if (m_shiftActive && !m_capsLockActive) { + setShiftActive(false); + } + return true; +} + +void InputEngine::connectBackend() +{ + if (!m_backend->parent()) { + m_backend->setParent(this); + } + + connect(m_backend, &InputBackend::surroundingTextChanged, this, [this] { + Q_EMIT surroundingTextChanged(); + Q_EMIT selectedTextChanged(); + Q_EMIT anchorPositionChanged(); + Q_EMIT cursorPositionChanged(); + updateAutomaticShift(); + }); + connect(m_backend, &InputBackend::inputMethodHintsChanged, this, [this] { + Q_EMIT inputMethodHintsChanged(); + resetShiftState(); + }); + connect(m_backend, &InputBackend::pressedKeysChanged, this, [this] { + Q_EMIT pressedKeysChanged(); + Q_EMIT uppercaseChanged(); + }); + connect(m_backend, &InputBackend::activeChanged, this, [this] { + Q_EMIT surroundingTextChanged(); + Q_EMIT selectedTextChanged(); + Q_EMIT anchorPositionChanged(); + Q_EMIT cursorPositionChanged(); + Q_EMIT inputMethodHintsChanged(); + resetShiftState(); + }); + connect(m_backend, &InputBackend::resetRequested, this, [this] { + if (m_textComposer) { + m_textComposer->reset(); + } else { + clear(); + } + resetShiftState(); + }); +} + +void InputEngine::resetShiftState() +{ + if (!m_backend->isActive()) { + setCapsLockActive(false); + setShiftActive(false); + return; + } + + const auto hints = inputMethodHints(); + const bool preferUppercase = + m_textComposer && m_textComposer->autoCapitalizationSupported() && hints.testAnyFlags(Qt::ImhPreferUppercase | Qt::ImhUppercaseOnly); + setCapsLockActive(preferUppercase); + setShiftActive(false); + + if (!preferUppercase) { + updateAutomaticShift(); + } +} + +void InputEngine::updateAutomaticShift() +{ + if (m_capsLockActive) { + return; + } + + if (!m_textComposer || !m_textComposer->autoCapitalizationSupported()) { + setShiftActive(false); + return; + } + + const auto hints = inputMethodHints(); + const auto disablingHints = Qt::ImhNoAutoUppercase | Qt::ImhUppercaseOnly | Qt::ImhLowercaseOnly | Qt::ImhEmailCharactersOnly | Qt::ImhUrlCharactersOnly + | Qt::ImhDialableCharactersOnly | Qt::ImhFormattedNumbersOnly | Qt::ImhDigitsOnly; + if (!m_backend->isActive() || hints.testAnyFlags(disablingHints) || hints.testFlag(Qt::ImhPreferLowercase) || !m_preeditText.isEmpty()) { + setShiftActive(false); + return; + } + + const QString textBeforeCursor = surroundingText().left(cursorPosition()); + setShiftActive(m_textComposer->shouldAutoCapitalize(textBeforeCursor)); +} + +void InputEngine::clearCompositionState(bool updateBackend) +{ + const bool hadPreedit = !m_preeditText.isEmpty(); + const bool hadCandidates = !m_candidates.isEmpty(); + + if (updateBackend && hadPreedit) { + m_backend->setPreeditText(QString()); + } + + if (hadPreedit) { + m_preeditText.clear(); + Q_EMIT preeditTextChanged(); + } + if (!m_preeditPrefix.isEmpty()) { + m_preeditPrefix.clear(); + Q_EMIT preeditPrefixChanged(); + } + if (hadCandidates) { + m_candidates.clear(); + Q_EMIT candidatesChanged(); + Q_EMIT wordCandidateListVisibleHintChanged(); + } +} + +bool InputEngine::sendDirectKeyClick(int key) +{ + return m_backend->sendKeyClick(key); +} + +int InputEngine::utf16PositionFromUtf8Offset(uint32_t offset) const +{ + return QString::fromUtf8(surroundingText().toUtf8().first(offset)).size(); +} diff --git a/virtualkeyboard/inputengine.h b/virtualkeyboard/inputengine.h new file mode 100644 index 0000000..35dac6f --- /dev/null +++ b/virtualkeyboard/inputengine.h @@ -0,0 +1,128 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include +#include +#include +#include +#include + +#include "textcomposers/abstracttextcomposer.h" +#include "wordcandidatelistmodel.h" + +class InputBackend; + +/** + * The input context for the current session. This contains fields such as: + * - Preedit text (word being built) + * - Preedit prefix (character being formed, used for CJK) + * - Capslock state + * - Shift state + * - Word prediction candidates list + * + * Text input is received from the TextComposer for the most part (though producers can also bypass it to enter text here). + * + * Events are sent and received via the InputBackend to communicate with the platform (which provides other state, such as the cursor position). + */ +class InputEngine : public QObject +{ + Q_OBJECT + Q_PROPERTY(AbstractTextComposer *textComposer READ textComposer WRITE setTextComposer NOTIFY textComposerChanged) + Q_PROPERTY(bool shiftActive READ shiftActive WRITE setShiftActive NOTIFY shiftActiveChanged) + Q_PROPERTY(bool capsLockActive READ capsLockActive WRITE setCapsLockActive NOTIFY capsLockActiveChanged) + Q_PROPERTY(bool uppercase READ uppercase NOTIFY uppercaseChanged) + Q_PROPERTY(QString preeditText READ preeditText NOTIFY preeditTextChanged) + Q_PROPERTY(QString preeditPrefix READ preeditPrefix NOTIFY preeditPrefixChanged) + Q_PROPERTY(QStringList candidates READ candidates NOTIFY candidatesChanged) + Q_PROPERTY(QString locale READ locale NOTIFY localeChanged) + Q_PROPERTY(int anchorPosition READ anchorPosition NOTIFY anchorPositionChanged) + Q_PROPERTY(int cursorPosition READ cursorPosition NOTIFY cursorPositionChanged) + Q_PROPERTY(Qt::InputMethodHints inputMethodHints READ inputMethodHints NOTIFY inputMethodHintsChanged) + Q_PROPERTY(QString surroundingText READ surroundingText NOTIFY surroundingTextChanged) + Q_PROPERTY(QString selectedText READ selectedText NOTIFY selectedTextChanged) + Q_PROPERTY(QList pressedKeys READ pressedKeys NOTIFY pressedKeysChanged) + Q_PROPERTY(bool preeditBubbleVisibleHint READ preeditBubbleVisibleHint NOTIFY textComposerChanged) + Q_PROPERTY(WordCandidateListModel *wordCandidateListModel READ wordCandidateListModel CONSTANT) + Q_PROPERTY(bool wordCandidateListVisibleHint READ wordCandidateListVisibleHint NOTIFY wordCandidateListVisibleHintChanged) + +public: + explicit InputEngine(InputBackend *backend, QObject *parent = nullptr); + + AbstractTextComposer *textComposer() const; + void setTextComposer(AbstractTextComposer *textComposer); + bool shiftActive() const; + void setShiftActive(bool active); + bool capsLockActive() const; + void setCapsLockActive(bool active); + bool uppercase() const; + QString preeditText() const; + void setPreeditText(const QString &text); + QString preeditPrefix() const; + void setPreeditPrefix(const QString &text); + QStringList candidates() const; + void setCandidates(const QStringList &candidates); + QString locale() const; + void setLocale(const QString &locale); + int anchorPosition() const; + int cursorPosition() const; + Qt::InputMethodHints inputMethodHints() const; + QString surroundingText() const; + QString selectedText() const; + QList pressedKeys() const; + bool preeditBubbleVisibleHint() const; + WordCandidateListModel *wordCandidateListModel() const; + bool wordCandidateListVisibleHint() const; + + /** Sends a text key through the active text composer. */ + Q_INVOKABLE bool sendTextComposerKey(int key, const QString &text); + + /** Sends a key event directly to the backend, bypassing composition. */ + Q_INVOKABLE bool sendDirectKey(int key, bool pressed); + Q_INVOKABLE bool isKeyPressed(int key) const; + Q_INVOKABLE bool selectCandidate(int index); + Q_INVOKABLE void commit(); + Q_INVOKABLE void commit(const QString &text, int replaceFrom = 0, int replaceLength = 0); + Q_INVOKABLE void clear(); + + bool handleKeyCommit(int key, const QString &text); + +Q_SIGNALS: + void textComposerChanged(); + void shiftActiveChanged(); + void capsLockActiveChanged(); + void uppercaseChanged(); + void preeditTextChanged(); + void preeditPrefixChanged(); + void candidatesChanged(); + void localeChanged(); + void surroundingTextChanged(); + void selectedTextChanged(); + void anchorPositionChanged(); + void cursorPositionChanged(); + void inputMethodHintsChanged(); + void pressedKeysChanged(); + void wordCandidateListVisibleHintChanged(); + +private: + void connectBackend(); + void clearCompositionState(bool updateBackend); + void resetShiftState(); + void updateAutomaticShift(); + bool sendDirectKeyClick(int key); + int utf16PositionFromUtf8Offset(uint32_t offset) const; + + InputBackend *m_backend = nullptr; + QPointer m_textComposer; + mutable WordCandidateListModel *m_wordCandidateListModel = nullptr; + QString m_locale; + bool m_shiftActive = false; + bool m_capsLockActive = false; + QString m_preeditText; + QString m_preeditPrefix; + QStringList m_candidates; +}; diff --git a/virtualkeyboard/keyboardcontroller.cpp b/virtualkeyboard/keyboardcontroller.cpp new file mode 100644 index 0000000..fe6b73f --- /dev/null +++ b/virtualkeyboard/keyboardcontroller.cpp @@ -0,0 +1,195 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "keyboardcontroller.h" + +#include "inputengine.h" +#include "keyboardlayoutmetadata.h" +#include "keyboardpackageresolver.h" + +KeyboardController::KeyboardController(InputEngine *inputEngine, KeyboardPackageResolver *packageResolver, QObject *parent) + : QObject(parent) + , m_inputEngine(inputEngine) + , m_packageResolver(packageResolver) +{ + Q_ASSERT(m_inputEngine); + Q_ASSERT(m_packageResolver); + + connect(m_inputEngine, &InputEngine::inputMethodHintsChanged, this, &KeyboardController::layoutTypeChanged); + connect(m_packageResolver, &KeyboardPackageResolver::layoutIdsChanged, this, [this] { + refreshLayoutId(); + }); + + refreshLayoutId(); +} + +QString KeyboardController::layoutId() const +{ + return m_layoutId; +} + +void KeyboardController::setLayoutId(const QString &layoutId) +{ + QString resolvedId = m_packageResolver->resolveLayoutId(layoutId); + if (!m_activeLayoutIds.isEmpty() && !m_activeLayoutIds.contains(resolvedId)) { + resolvedId = m_activeLayoutIds.constFirst(); + } + if (m_layoutId == resolvedId) { + return; + } + + m_layoutId = resolvedId; + refreshLocale(); + Q_EMIT layoutIdChanged(); +} + +QStringList KeyboardController::activeLayoutIds() const +{ + return m_activeLayoutIds; +} + +void KeyboardController::setActiveLayoutIds(const QStringList &activeLayoutIds) +{ + QStringList resolvedIds; + const QStringList availableIds = m_packageResolver->layoutIds(); + for (const auto &layoutId : activeLayoutIds) { + const QString resolvedId = m_packageResolver->resolveLayoutId(layoutId); + if (availableIds.contains(resolvedId) && !resolvedIds.contains(resolvedId)) { + resolvedIds.append(resolvedId); + } + } + + if (m_activeLayoutIds == resolvedIds) { + return; + } + + m_activeLayoutIds = resolvedIds; + Q_EMIT activeLayoutIdsChanged(); + + if (m_activeLayoutIds.isEmpty()) { + refreshLayoutId(); + return; + } + + if (!m_activeLayoutIds.contains(m_layoutId)) { + setLayoutId(m_activeLayoutIds.constFirst()); + return; + } + + refreshLocale(); +} + +int KeyboardController::currentLayoutIndex() const +{ + return m_activeLayoutIds.indexOf(m_layoutId); +} + +bool KeyboardController::hasMultipleLayouts() const +{ + return m_activeLayoutIds.size() > 1; +} + +bool KeyboardController::symbolMode() const +{ + return m_symbolMode; +} + +void KeyboardController::setSymbolMode(bool symbolMode) +{ + if (m_symbolMode == symbolMode) { + return; + } + + m_symbolMode = symbolMode; + Q_EMIT symbolModeChanged(); + Q_EMIT layoutTypeChanged(); +} + +QString KeyboardController::layoutType() const +{ + const auto hints = m_inputEngine->inputMethodHints(); + if (hints.testFlag(Qt::ImhDialableCharactersOnly)) { + return QStringLiteral("dialpad"); + } + if (hints.testFlag(Qt::ImhFormattedNumbersOnly)) { + return QStringLiteral("numbers"); + } + if (hints.testFlag(Qt::ImhDigitsOnly)) { + return QStringLiteral("digits"); + } + if (m_symbolMode) { + return QStringLiteral("symbols"); + } + return QStringLiteral("main"); +} + +void KeyboardController::cycleLayout() +{ + if (m_activeLayoutIds.size() <= 1) { + return; + } + + const int currentIndex = m_activeLayoutIds.indexOf(m_layoutId); + const int nextIndex = currentIndex < 0 || currentIndex + 1 >= m_activeLayoutIds.size() ? 0 : currentIndex + 1; + setLayoutId(m_activeLayoutIds.at(nextIndex)); +} + +void KeyboardController::setCurrentLayout(const QString &layoutId) +{ + if (layoutId.isEmpty()) { + return; + } + + if (!m_activeLayoutIds.isEmpty() && !m_activeLayoutIds.contains(layoutId)) { + return; + } + + setLayoutId(layoutId); +} + +QString KeyboardController::layoutDisplayName(const QString &layoutId) const +{ + const QString name = m_packageResolver->keyboardName(layoutId); + if (!name.isEmpty()) { + return name; + } + + const QString locale = m_packageResolver->keyboardPrimaryLocale(layoutId); + if (!locale.isEmpty()) { + return KeyboardLayoutMetadata::localeDisplayName(locale); + } + + return layoutId; +} + +QString KeyboardController::layoutName(const QString &layoutId) const +{ + const QString name = m_packageResolver->layoutName(layoutId); + return name.isEmpty() ? layoutDisplayName(layoutId) : name; +} + +QString KeyboardController::layoutPrimaryLocale(const QString &layoutId) const +{ + return m_packageResolver->keyboardPrimaryLocale(layoutId); +} + +void KeyboardController::refreshLayoutId() +{ + if (!m_activeLayoutIds.isEmpty()) { + setLayoutId(m_activeLayoutIds.contains(m_layoutId) ? m_layoutId : m_activeLayoutIds.constFirst()); + return; + } + + setLayoutId(QString()); +} + +void KeyboardController::refreshLocale() +{ + const QString locale = layoutPrimaryLocale(m_layoutId); + if (!locale.isEmpty() && m_inputEngine->locale() != locale) { + m_inputEngine->setLocale(locale); + } +} diff --git a/virtualkeyboard/keyboardcontroller.h b/virtualkeyboard/keyboardcontroller.h new file mode 100644 index 0000000..abd9bb6 --- /dev/null +++ b/virtualkeyboard/keyboardcontroller.h @@ -0,0 +1,69 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include +#include +#include + +class InputEngine; +class KeyboardPackageResolver; + +/** + * The keyboard's state. + * + * Selects the active keyboard layout and its input-specific layout type. + */ +class KeyboardController : public QObject +{ + Q_OBJECT + QML_ANONYMOUS + Q_PROPERTY(QString layoutId READ layoutId WRITE setLayoutId NOTIFY layoutIdChanged) + Q_PROPERTY(QStringList activeLayoutIds READ activeLayoutIds WRITE setActiveLayoutIds NOTIFY activeLayoutIdsChanged) + Q_PROPERTY(int currentLayoutIndex READ currentLayoutIndex NOTIFY layoutIdChanged) + Q_PROPERTY(bool hasMultipleLayouts READ hasMultipleLayouts NOTIFY activeLayoutIdsChanged) + Q_PROPERTY(bool symbolMode READ symbolMode WRITE setSymbolMode NOTIFY symbolModeChanged) + Q_PROPERTY(QString layoutType READ layoutType NOTIFY layoutTypeChanged) + +public: + explicit KeyboardController(InputEngine *inputEngine, KeyboardPackageResolver *packageResolver, QObject *parent = nullptr); + + QString layoutId() const; + void setLayoutId(const QString &layoutId); + + QStringList activeLayoutIds() const; + void setActiveLayoutIds(const QStringList &activeLayoutIds); + int currentLayoutIndex() const; + bool hasMultipleLayouts() const; + + bool symbolMode() const; + void setSymbolMode(bool symbolMode); + + QString layoutType() const; + + Q_INVOKABLE void cycleLayout(); + Q_INVOKABLE void setCurrentLayout(const QString &layoutId); + Q_INVOKABLE QString layoutDisplayName(const QString &layoutId) const; + Q_INVOKABLE QString layoutName(const QString &layoutId) const; + +Q_SIGNALS: + void layoutIdChanged(); + void activeLayoutIdsChanged(); + void symbolModeChanged(); + void layoutTypeChanged(); + +private: + void refreshLayoutId(); + void refreshLocale(); + QString layoutPrimaryLocale(const QString &layoutId) const; + + InputEngine *m_inputEngine = nullptr; + KeyboardPackageResolver *m_packageResolver = nullptr; + QString m_layoutId; + QStringList m_activeLayoutIds; + bool m_symbolMode = false; +}; diff --git a/virtualkeyboard/keyboardlayoutmetadata.cpp b/virtualkeyboard/keyboardlayoutmetadata.cpp new file mode 100644 index 0000000..328aed6 --- /dev/null +++ b/virtualkeyboard/keyboardlayoutmetadata.cpp @@ -0,0 +1,126 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "keyboardlayoutmetadata.h" + +#include + +#include +#include +#include +#include +#include + +using namespace Qt::StringLiterals; + +static QVariantMap keyboardSection(const KPluginMetaData &metadata) +{ + return metadata.rawData().toVariantMap().value(u"X-Plasma-Keyboard"_s).toMap(); +} + +static QStringList locales(const KPluginMetaData &metadata) +{ + return keyboardSection(metadata).value(u"Locales"_s).toStringList(); +} + +static QVariantList keyboardLayoutDefinitions(const KPluginMetaData &metadata) +{ + return keyboardSection(metadata).value(u"KeyboardLayouts"_s).toList(); +} + +static QString packageId(const QString &directoryName, const KPluginMetaData &metadata) +{ + return metadata.pluginId().isEmpty() ? directoryName : metadata.pluginId(); +} + +static QStringList rootPaths() +{ + return QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, u"plasma/keyboard/keyboardpackages"_s, QStandardPaths::LocateDirectory); +} + +static QString localLayoutId(const QVariantMap &layout) +{ + return layout.value(u"Id"_s).toString(); +} + +QString KeyboardLayoutMetadata::localeDisplayName(const QString &locale) +{ + if (locale.isEmpty()) { + return {}; + } + + const QLocale qlocale(locale); + const QString language = qlocale.nativeLanguageName(); + const QString territory = qlocale.nativeTerritoryName(); + return territory.isEmpty() ? language : language + u" ("_s + territory + u")"_s; +} + +QString KeyboardLayoutMetadata::keyboardLayoutName(const QVariantMap &layout) +{ + return layout.value(u"Name"_s).toString(); +} + +QString KeyboardLayoutMetadata::keyboardLayoutFile(const QVariantMap &layout, const QString &layoutType) +{ + const QVariantMap files = layout.value(u"Files"_s).toMap(); + const QString fileName = files.value(layoutType).toString(); + if (!fileName.isEmpty()) { + return fileName; + } + return layoutType + u".qml"_s; +} + +QStringList KeyboardLayoutMetadata::keyboardLayoutFormFactors(const QVariantMap &layout) +{ + return layout.value(u"FormFactors"_s).toStringList(); +} + +QString KeyboardLayoutMetadata::keyboardDisplayName(const Layout &layout) +{ + return layout.keyboardName.isEmpty() ? layout.packageId : layout.keyboardName; +} + +QList KeyboardLayoutMetadata::keyboardLayouts() +{ + QList layouts; + + for (const auto &root : rootPaths()) { + const QDir rootDir(root); + const QFileInfoList entries = rootDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); + for (const auto &entry : entries) { + const QString metadataPath = entry.absoluteFilePath() + u"/metadata.json"_s; + if (!QFileInfo::exists(metadataPath)) { + continue; + } + + const KPluginMetaData metadata = KPluginMetaData::fromJsonFile(metadataPath); + if (!metadata.isValid()) { + continue; + } + + const QString currentPackageId = packageId(entry.fileName(), metadata); + for (const auto &value : keyboardLayoutDefinitions(metadata)) { + const QVariantMap layoutDefinition = value.toMap(); + const QString currentLocalLayoutId = localLayoutId(layoutDefinition); + if (currentLocalLayoutId.isEmpty()) { + continue; + } + + layouts.append({ + .packageId = currentPackageId, + .layoutId = currentPackageId + u"/"_s + currentLocalLayoutId, + .packagePath = entry.absoluteFilePath(), + .keyboardName = metadata.name(), + .locales = locales(metadata), + .formFactors = keyboardLayoutFormFactors(layoutDefinition), + .layoutDefinition = layoutDefinition, + }); + } + } + } + + return layouts; +} diff --git a/virtualkeyboard/keyboardlayoutmetadata.h b/virtualkeyboard/keyboardlayoutmetadata.h new file mode 100644 index 0000000..19d993f --- /dev/null +++ b/virtualkeyboard/keyboardlayoutmetadata.h @@ -0,0 +1,34 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include +#include + +/** + * Discovers installed keyboard layouts and reads their package metadata. + */ +class KeyboardLayoutMetadata +{ +public: + struct Layout { + QString packageId; + QString layoutId; + QString packagePath; + QString keyboardName; + QStringList locales; + QStringList formFactors; + QVariantMap layoutDefinition; + }; + + static QString localeDisplayName(const QString &locale); + static QString keyboardLayoutName(const QVariantMap &layout); + static QString keyboardLayoutFile(const QVariantMap &layout, const QString &layoutType); + static QStringList keyboardLayoutFormFactors(const QVariantMap &layout); + static QString keyboardDisplayName(const Layout &layout); + static QList keyboardLayouts(); +}; diff --git a/virtualkeyboard/keyboardpackageresolver.cpp b/virtualkeyboard/keyboardpackageresolver.cpp new file mode 100644 index 0000000..38b1f79 --- /dev/null +++ b/virtualkeyboard/keyboardpackageresolver.cpp @@ -0,0 +1,126 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "keyboardpackageresolver.h" +#include "logging.h" + +#include + +using namespace Qt::StringLiterals; + +KeyboardPackageResolver::KeyboardPackageResolver(QObject *parent) + : QObject(parent) +{ + rebuildIndex(); +} + +QStringList KeyboardPackageResolver::layoutIds() const +{ + return m_layoutIds; +} + +QString KeyboardPackageResolver::packageId(const QString &layoutId) const +{ + const auto *layout = findLayout(layoutId); + return layout ? layout->packageId : QString(); +} + +QString KeyboardPackageResolver::resolveLayoutId(const QString &id) const +{ + const auto *layout = findLayout(id); + return layout ? layout->layoutId : QString(); +} + +QString KeyboardPackageResolver::layoutName(const QString &layoutId) const +{ + const auto *layout = findLayout(layoutId); + if (!layout) { + return {}; + } + + const QString name = KeyboardLayoutMetadata::keyboardLayoutName(layout->layoutDefinition); + return name.isEmpty() ? KeyboardLayoutMetadata::keyboardDisplayName(*layout) : name; +} + +QString KeyboardPackageResolver::keyboardName(const QString &layoutId) const +{ + const auto *layout = findLayout(layoutId); + return layout ? KeyboardLayoutMetadata::keyboardDisplayName(*layout) : QString(); +} + +QString KeyboardPackageResolver::keyboardPrimaryLocale(const QString &layoutId) const +{ + const auto *layout = findLayout(layoutId); + return layout && !layout->locales.isEmpty() ? layout->locales.constFirst() : QString(); +} + +QStringList KeyboardPackageResolver::keyboardLocales(const QString &layoutId) const +{ + const auto *layout = findLayout(layoutId); + return layout ? layout->locales : QStringList(); +} + +QString KeyboardPackageResolver::layoutPath(const QString &layoutId, const QString &layoutType) const +{ + const auto *layout = findLayout(layoutId); + if (!layout || layoutType.isEmpty()) { + return {}; + } + + const QString fileName = KeyboardLayoutMetadata::keyboardLayoutFile(layout->layoutDefinition, layoutType); + const QString layoutPath = layout->packagePath + u"/contents/layouts/"_s + fileName; + if (QFileInfo::exists(layoutPath)) { + return layoutPath; + } + return {}; +} + +QUrl KeyboardPackageResolver::layoutUrl(const QString &layoutId, const QString &layoutType) const +{ + const QString path = layoutPath(layoutId, layoutType); + qCDebug(PlasmaKeyboard) << "KeyboardPackageResolver: loading keyboard layout" << layoutId << layoutType << path; + return path.isEmpty() ? QUrl() : QUrl::fromLocalFile(path); +} + +void KeyboardPackageResolver::rebuildIndex() +{ + QList layouts = KeyboardLayoutMetadata::keyboardLayouts(); + for (const auto &layout : layouts) { + qCDebug(PlasmaKeyboard) << "KeyboardPackageResolver: discovered keyboard layout" << layout.layoutId << layout.packageId << layout.packagePath; + } + + QStringList ids; + ids.reserve(layouts.size()); + for (const auto &layout : layouts) { + ids.append(layout.layoutId); + } + + if (m_layoutIds == ids && m_layouts.size() == layouts.size()) { + return; + } + + m_layouts = layouts; + m_layoutIds = ids; + qCDebug(PlasmaKeyboard) << "KeyboardPackageResolver: active keyboard layouts" << m_layoutIds; + Q_EMIT layoutIdsChanged(); +} + +const KeyboardLayoutMetadata::Layout *KeyboardPackageResolver::findLayout(const QString &id) const +{ + for (const auto &layout : m_layouts) { + if (layout.layoutId == id) { + return &layout; + } + } + + for (const auto &layout : m_layouts) { + if (layout.packageId == id) { + return &layout; + } + } + + return nullptr; +} diff --git a/virtualkeyboard/keyboardpackageresolver.h b/virtualkeyboard/keyboardpackageresolver.h new file mode 100644 index 0000000..f128bff --- /dev/null +++ b/virtualkeyboard/keyboardpackageresolver.h @@ -0,0 +1,90 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include +#include +#include +#include + +#include "keyboardlayoutmetadata.h" + +/** + * Utility to find and parse keyboard "layout packages". + */ +class KeyboardPackageResolver : public QObject +{ + Q_OBJECT + QML_ANONYMOUS + Q_PROPERTY(QStringList layoutIds READ layoutIds NOTIFY layoutIdsChanged) + +public: + /** + * Creates a resolver and indexes installed layout packages. + */ + explicit KeyboardPackageResolver(QObject *parent = nullptr); + + /** + * Returns the installed layout IDs. + */ + QStringList layoutIds() const; + + /** + * Returns the package ID containing @p layoutId. + * Package ID example: org.kde.plasma.keyboard.en + * + * The argument may be a layout ID or a package ID. + */ + Q_INVOKABLE QString packageId(const QString &layoutId) const; + + /** + * Returns the layout ID for @p id. + * Layout ID example: org.kde.plasma.keyboard.en/mobile-qwerty + * + * A package ID resolves to its first layout. + */ + Q_INVOKABLE QString resolveLayoutId(const QString &id) const; + + /** + * Returns the display name of @p layoutId. + */ + Q_INVOKABLE QString layoutName(const QString &layoutId) const; + + /** + * Returns the keyboard name for @p layoutId. + */ + Q_INVOKABLE QString keyboardName(const QString &layoutId) const; + + /** + * Returns the primary locale of the keyboard containing @p layoutId. + */ + Q_INVOKABLE QString keyboardPrimaryLocale(const QString &layoutId) const; + + /** + * Returns the locales supported by the keyboard containing @p layoutId. + */ + Q_INVOKABLE QStringList keyboardLocales(const QString &layoutId) const; + + /** + * Returns the local QML file URL for @p layoutId and @p layoutType. + */ + Q_INVOKABLE QUrl layoutUrl(const QString &layoutId, const QString &layoutType) const; + +Q_SIGNALS: + /** + * Emitted when the installed layout IDs change. + */ + void layoutIdsChanged(); + +private: + void rebuildIndex(); + QString layoutPath(const QString &layoutId, const QString &layoutType) const; + const KeyboardLayoutMetadata::Layout *findLayout(const QString &id) const; + + QStringList m_layoutIds; + QList m_layouts; +}; diff --git a/virtualkeyboard/textcomposers/abstracttextcomposer.cpp b/virtualkeyboard/textcomposers/abstracttextcomposer.cpp new file mode 100644 index 0000000..c6d1410 --- /dev/null +++ b/virtualkeyboard/textcomposers/abstracttextcomposer.cpp @@ -0,0 +1,97 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "abstracttextcomposer.h" + +#include "../inputengine.h" + +AbstractTextComposer::AbstractTextComposer(QObject *parent) + : QObject(parent) +{ +} + +AbstractTextComposer::~AbstractTextComposer() = default; + +InputEngine *AbstractTextComposer::inputEngine() const +{ + return m_inputEngine; +} + +bool AbstractTextComposer::shouldAutoCapitalize(QStringView textBeforeCursor) const +{ + Q_UNUSED(textBeforeCursor) + return false; +} + +bool AbstractTextComposer::selectCandidate(int index) +{ + Q_UNUSED(index) + return false; +} + +bool AbstractTextComposer::replaceLastInput(const QString &text) +{ + Q_UNUSED(text) + return false; +} + +bool AbstractTextComposer::showsPreeditBubble() const +{ + return false; +} + +void AbstractTextComposer::reset() +{ + clearComposition(); +} + +QString AbstractTextComposer::preeditText() const +{ + return inputEngine() ? inputEngine()->preeditText() : QString(); +} + +QString AbstractTextComposer::preeditPrefix() const +{ + return inputEngine() ? inputEngine()->preeditPrefix() : QString(); +} + +QStringList AbstractTextComposer::candidates() const +{ + return inputEngine() ? inputEngine()->candidates() : QStringList(); +} + +void AbstractTextComposer::setPreeditText(const QString &text) +{ + if (auto *engine = inputEngine()) { + engine->setPreeditText(text); + } +} + +void AbstractTextComposer::setPreeditPrefix(const QString &text) +{ + if (auto *engine = inputEngine()) { + engine->setPreeditPrefix(text); + } +} + +void AbstractTextComposer::setCandidates(const QStringList &candidates) +{ + if (auto *engine = inputEngine()) { + engine->setCandidates(candidates); + } +} + +void AbstractTextComposer::clearComposition() +{ + setPreeditPrefix(QString()); + setPreeditText(QString()); + setCandidates({}); +} + +void AbstractTextComposer::setInputEngine(InputEngine *inputEngine) +{ + m_inputEngine = inputEngine; +} diff --git a/virtualkeyboard/textcomposers/abstracttextcomposer.h b/virtualkeyboard/textcomposers/abstracttextcomposer.h new file mode 100644 index 0000000..4140dec --- /dev/null +++ b/virtualkeyboard/textcomposers/abstracttextcomposer.h @@ -0,0 +1,71 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include +#include +#include +#include +#include + +class InputEngine; + +/** + * Base class that sits between the keyboard and input engine, and converts + * keyboard input into composed text and word candidates. + * + * Extend it to implement language specific features (e.g. word prediction, + * character transformation for Korean). + * + * @see DirectTextComposer + */ +class AbstractTextComposer : public QObject +{ + Q_OBJECT + Q_PROPERTY(bool autoCapitalizationSupported READ autoCapitalizationSupported NOTIFY autoCapitalizationSupportedChanged) + +public: + enum class TextCase { + Lower, + Upper, + }; + Q_ENUM(TextCase) + + explicit AbstractTextComposer(QObject *parent = nullptr); + ~AbstractTextComposer() override; + + InputEngine *inputEngine() const; + + virtual bool autoCapitalizationSupported() const = 0; + virtual bool setTextCase(TextCase textCase) = 0; + virtual bool shouldAutoCapitalize(QStringView textBeforeCursor) const; + virtual bool keyEvent(Qt::Key key, const QString &text) = 0; + virtual bool selectCandidate(int index); + Q_INVOKABLE virtual bool replaceLastInput(const QString &text); + virtual bool showsPreeditBubble() const; + +public Q_SLOTS: + virtual void reset(); + +Q_SIGNALS: + void autoCapitalizationSupportedChanged(); + void autoCapitalizationPolicyChanged(); + +protected: + QString preeditText() const; + QString preeditPrefix() const; + QStringList candidates() const; + void setPreeditText(const QString &text); + void setPreeditPrefix(const QString &text); + void setCandidates(const QStringList &candidates); + void clearComposition(); + void setInputEngine(InputEngine *inputEngine); + +private: + friend class InputEngine; + QPointer m_inputEngine; +}; diff --git a/virtualkeyboard/textcomposers/basictextcomposer.cpp b/virtualkeyboard/textcomposers/basictextcomposer.cpp new file mode 100644 index 0000000..b66e9fa --- /dev/null +++ b/virtualkeyboard/textcomposers/basictextcomposer.cpp @@ -0,0 +1,45 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "basictextcomposer.h" + +BasicTextComposer::BasicTextComposer(QObject *parent) + : DirectTextComposer(parent) +{ +} + +QString BasicTextComposer::sentenceEndingCharacters() const +{ + return m_sentenceEndingCharacters; +} + +void BasicTextComposer::setSentenceEndingCharacters(const QString &characters) +{ + if (m_sentenceEndingCharacters == characters) { + return; + } + + m_sentenceEndingCharacters = characters; + Q_EMIT sentenceEndingCharactersChanged(); + Q_EMIT autoCapitalizationPolicyChanged(); +} + +bool BasicTextComposer::autoCapitalizationSupported() const +{ + return true; +} + +bool BasicTextComposer::shouldAutoCapitalize(QStringView textBeforeCursor) const +{ + if (textBeforeCursor.trimmed().isEmpty()) { + return true; + } + if (textBeforeCursor.size() < 2 || !textBeforeCursor.endsWith(QLatin1Char(' '))) { + return false; + } + + return m_sentenceEndingCharacters.contains(textBeforeCursor.at(textBeforeCursor.size() - 2)); +} diff --git a/virtualkeyboard/textcomposers/basictextcomposer.h b/virtualkeyboard/textcomposers/basictextcomposer.h new file mode 100644 index 0000000..965d957 --- /dev/null +++ b/virtualkeyboard/textcomposers/basictextcomposer.h @@ -0,0 +1,37 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include "directtextcomposer.h" + +/** + * Text composer that passes input directly to the backend. + * + * Supports auto-capitalization (if enabled). + */ +class BasicTextComposer : public DirectTextComposer +{ + Q_OBJECT + QML_NAMED_ELEMENT(BasicTextComposer) + Q_PROPERTY(QString sentenceEndingCharacters READ sentenceEndingCharacters WRITE setSentenceEndingCharacters NOTIFY sentenceEndingCharactersChanged) + +public: + explicit BasicTextComposer(QObject *parent = nullptr); + + /** Characters recognized as sentence terminators. */ + QString sentenceEndingCharacters() const; + void setSentenceEndingCharacters(const QString &characters); + + bool autoCapitalizationSupported() const override; + bool shouldAutoCapitalize(QStringView textBeforeCursor) const override; + +Q_SIGNALS: + void sentenceEndingCharactersChanged(); + +private: + QString m_sentenceEndingCharacters = QStringLiteral(".!?¡¿"); +}; diff --git a/virtualkeyboard/textcomposers/directtextcomposer.cpp b/virtualkeyboard/textcomposers/directtextcomposer.cpp new file mode 100644 index 0000000..e5f4de6 --- /dev/null +++ b/virtualkeyboard/textcomposers/directtextcomposer.cpp @@ -0,0 +1,46 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "directtextcomposer.h" + +#include "../inputengine.h" + +#include + +DirectTextComposer::DirectTextComposer(QObject *parent) + : AbstractTextComposer(parent) +{ +} + +bool DirectTextComposer::autoCapitalizationSupported() const +{ + return false; +} + +bool DirectTextComposer::setTextCase(TextCase textCase) +{ + m_textCase = textCase; + return true; +} + +bool DirectTextComposer::keyEvent(Qt::Key key, const QString &text) +{ + auto *engine = inputEngine(); + if (!engine) { + return false; + } + + return engine->handleKeyCommit(key, transformedText(text)); +} + +QString DirectTextComposer::transformedText(const QString &text) const +{ + if (m_textCase != TextCase::Upper || text.size() != 1) { + return text; + } + + return QLocale(inputEngine() ? inputEngine()->locale() : QString()).toUpper(text); +} diff --git a/virtualkeyboard/textcomposers/directtextcomposer.h b/virtualkeyboard/textcomposers/directtextcomposer.h new file mode 100644 index 0000000..5251ff5 --- /dev/null +++ b/virtualkeyboard/textcomposers/directtextcomposer.h @@ -0,0 +1,32 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include "abstracttextcomposer.h" + +#include + +/** + * Text composer that passes input directly to the backend, applying the requested letter case. + */ +class DirectTextComposer : public AbstractTextComposer +{ + Q_OBJECT + QML_NAMED_ELEMENT(DirectTextComposer) + +public: + explicit DirectTextComposer(QObject *parent = nullptr); + + bool autoCapitalizationSupported() const override; + bool setTextCase(TextCase textCase) override; + bool keyEvent(Qt::Key key, const QString &text) override; + +private: + QString transformedText(const QString &text) const; + + TextCase m_textCase = TextCase::Lower; +}; diff --git a/virtualkeyboard/virtualkeyboardattached.cpp b/virtualkeyboard/virtualkeyboardattached.cpp new file mode 100644 index 0000000..ac0c1d3 --- /dev/null +++ b/virtualkeyboard/virtualkeyboardattached.cpp @@ -0,0 +1,155 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "virtualkeyboardattached.h" + +#include "inputengine.h" +#include "keyboardcontroller.h" +#include "keyboardpackageresolver.h" +#include "virtualkeyboardcontext.h" + +#include +#include +#include +#include + +static VirtualKeyboardContext *contextFromObject(QObject *object) +{ + if (!object) { + return nullptr; + } + + const QVariant contextProperty = object->property("virtualKeyboardContext"); + if (auto *keyboardContext = qvariant_cast(contextProperty)) { + return keyboardContext; + } + return qobject_cast(qvariant_cast(contextProperty)); +} + +static QObject *objectProperty(QObject *object, const char *name) +{ + if (!object) { + return nullptr; + } + + const QVariant property = object->property(name); + if (auto *propertyObject = qvariant_cast(property)) { + return propertyObject; + } + return nullptr; +} + +VirtualKeyboardAttached::VirtualKeyboardAttached(QObject *attachedObject) + : QObject(attachedObject) + , m_attachedObject(attachedObject) +{ + if (auto *item = qobject_cast(attachedObject)) { + connect(item, &QQuickItem::parentChanged, this, &VirtualKeyboardAttached::contextChanged); + connect(item, &QQuickItem::windowChanged, this, &VirtualKeyboardAttached::contextChanged); + } + + QTimer::singleShot(0, this, &VirtualKeyboardAttached::contextChanged); +} + +InputEngine *VirtualKeyboardAttached::inputEngine() const +{ + auto *keyboardContext = context(); + return keyboardContext ? keyboardContext->inputEngine() : nullptr; +} + +KeyboardController *VirtualKeyboardAttached::keyboardController() const +{ + auto *keyboardContext = context(); + return keyboardContext ? keyboardContext->keyboardController() : nullptr; +} + +KeyboardPackageResolver *VirtualKeyboardAttached::keyboardPackageResolver() const +{ + auto *keyboardContext = context(); + return keyboardContext ? keyboardContext->keyboardPackageResolver() : nullptr; +} + +QObject *VirtualKeyboardAttached::alternativeKeysPopup() const +{ + return attachedObjectProperty("alternativeKeysPopupItem"); +} + +QObject *VirtualKeyboardAttached::characterPopup() const +{ + return attachedObjectProperty("characterPopupItem"); +} + +QObject *VirtualKeyboardAttached::flickPreviewPopup() const +{ + return attachedObjectProperty("flickPreviewPopupItem"); +} + +QObject *VirtualKeyboardAttached::languagePopup() const +{ + return attachedObjectProperty("languagePopupItem"); +} + +QObject *VirtualKeyboardAttached::inputMethodConnection() const +{ + return attachedObjectProperty("inputMethodConnection"); +} + +VirtualKeyboardContext *VirtualKeyboardAttached::context() const +{ + for (QObject *object = m_attachedObject; object; object = object->parent()) { + if (auto *keyboardContext = contextFromObject(object)) { + return keyboardContext; + } + + auto *item = qobject_cast(object); + if (!item) { + continue; + } + + for (QQuickItem *parentItem = item->parentItem(); parentItem; parentItem = parentItem->parentItem()) { + if (auto *keyboardContext = contextFromObject(parentItem)) { + return keyboardContext; + } + } + + if (auto *keyboardContext = contextFromObject(item->window())) { + return keyboardContext; + } + } + + return nullptr; +} + +QObject *VirtualKeyboardAttached::attachedObjectProperty(const char *name) const +{ + for (QObject *object = m_attachedObject; object; object = object->parent()) { + if (auto *propertyObject = objectProperty(object, name)) { + return propertyObject; + } + + auto *item = qobject_cast(object); + if (!item) { + continue; + } + + for (QQuickItem *parentItem = item->parentItem(); parentItem; parentItem = parentItem->parentItem()) { + if (auto *propertyObject = objectProperty(parentItem, name)) { + return propertyObject; + } + } + + if (auto *propertyObject = objectProperty(item->window(), name)) { + return propertyObject; + } + } + + return nullptr; +} + +VirtualKeyboardAttached *VirtualKeyboard::qmlAttachedProperties(QObject *object) +{ + return new VirtualKeyboardAttached(object); +} diff --git a/virtualkeyboard/virtualkeyboardattached.h b/virtualkeyboard/virtualkeyboardattached.h new file mode 100644 index 0000000..09a21f6 --- /dev/null +++ b/virtualkeyboard/virtualkeyboardattached.h @@ -0,0 +1,72 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include +#include + +class InputEngine; +class KeyboardController; +class KeyboardPackageResolver; +class VirtualKeyboardContext; + +/** + * Class that holds the keyboard and input state, as well as access to keyboard UI components. + * + * The state is extracted from the VirtualKeyboardContext for a keyboard instance. + */ +class VirtualKeyboardAttached : public QObject +{ + Q_OBJECT + Q_PROPERTY(InputEngine *inputEngine READ inputEngine NOTIFY contextChanged) + Q_PROPERTY(KeyboardController *keyboardController READ keyboardController NOTIFY contextChanged) + Q_PROPERTY(KeyboardPackageResolver *keyboardPackageResolver READ keyboardPackageResolver NOTIFY contextChanged) + Q_PROPERTY(QObject *alternativeKeysPopup READ alternativeKeysPopup NOTIFY contextChanged) + Q_PROPERTY(QObject *characterPopup READ characterPopup NOTIFY contextChanged) + Q_PROPERTY(QObject *flickPreviewPopup READ flickPreviewPopup NOTIFY contextChanged) + Q_PROPERTY(QObject *languagePopup READ languagePopup NOTIFY contextChanged) + Q_PROPERTY(QObject *inputMethodConnection READ inputMethodConnection NOTIFY contextChanged) + +public: + explicit VirtualKeyboardAttached(QObject *attachedObject); + + InputEngine *inputEngine() const; + KeyboardController *keyboardController() const; + KeyboardPackageResolver *keyboardPackageResolver() const; + QObject *alternativeKeysPopup() const; + QObject *characterPopup() const; + QObject *flickPreviewPopup() const; + QObject *languagePopup() const; + QObject *inputMethodConnection() const; + +Q_SIGNALS: + void contextChanged(); + +private: + VirtualKeyboardContext *context() const; + QObject *attachedObjectProperty(const char *name) const; + + QObject *m_attachedObject = nullptr; +}; + +/** + * Provides virtual keyboard state and components as QML attached properties. + * + * Example Usage: VirtualKeyboard.inputEngine.anchorPosition + */ +class VirtualKeyboard : public QObject +{ + Q_OBJECT + QML_NAMED_ELEMENT(VirtualKeyboard) + QML_UNCREATABLE("VirtualKeyboard is an attached property provider") + QML_ATTACHED(VirtualKeyboardAttached) + +public: + using QObject::QObject; + + static VirtualKeyboardAttached *qmlAttachedProperties(QObject *object); +}; diff --git a/virtualkeyboard/virtualkeyboardcontext.cpp b/virtualkeyboard/virtualkeyboardcontext.cpp new file mode 100644 index 0000000..398cac6 --- /dev/null +++ b/virtualkeyboard/virtualkeyboardcontext.cpp @@ -0,0 +1,35 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "virtualkeyboardcontext.h" + +#include "inputbackend.h" +#include "inputengine.h" +#include "keyboardcontroller.h" +#include "keyboardpackageresolver.h" + +VirtualKeyboardContext::VirtualKeyboardContext(InputBackend *inputBackend, QObject *parent) + : QObject(parent) + , m_inputEngine(new InputEngine(inputBackend, this)) + , m_keyboardPackageResolver(new KeyboardPackageResolver(this)) + , m_keyboardController(new KeyboardController(m_inputEngine, m_keyboardPackageResolver, this)) +{ +} + +InputEngine *VirtualKeyboardContext::inputEngine() const +{ + return m_inputEngine; +} + +KeyboardController *VirtualKeyboardContext::keyboardController() const +{ + return m_keyboardController; +} + +KeyboardPackageResolver *VirtualKeyboardContext::keyboardPackageResolver() const +{ + return m_keyboardPackageResolver; +} diff --git a/virtualkeyboard/virtualkeyboardcontext.h b/virtualkeyboard/virtualkeyboardcontext.h new file mode 100644 index 0000000..67341db --- /dev/null +++ b/virtualkeyboard/virtualkeyboardcontext.h @@ -0,0 +1,39 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include +#include + +class InputBackend; +class InputEngine; +class KeyboardController; +class KeyboardPackageResolver; + +/** + * Owns the input and layout services for a virtual keyboard instance. + */ +class VirtualKeyboardContext : public QObject +{ + Q_OBJECT + QML_ANONYMOUS + Q_PROPERTY(InputEngine *inputEngine READ inputEngine CONSTANT) + Q_PROPERTY(KeyboardController *keyboardController READ keyboardController CONSTANT) + Q_PROPERTY(KeyboardPackageResolver *keyboardPackageResolver READ keyboardPackageResolver CONSTANT) + +public: + explicit VirtualKeyboardContext(InputBackend *inputBackend, QObject *parent = nullptr); + + InputEngine *inputEngine() const; + KeyboardController *keyboardController() const; + KeyboardPackageResolver *keyboardPackageResolver() const; + +private: + InputEngine *m_inputEngine = nullptr; + KeyboardPackageResolver *m_keyboardPackageResolver = nullptr; + KeyboardController *m_keyboardController = nullptr; +}; diff --git a/virtualkeyboard/wordcandidatelistmodel.cpp b/virtualkeyboard/wordcandidatelistmodel.cpp new file mode 100644 index 0000000..c9348f8 --- /dev/null +++ b/virtualkeyboard/wordcandidatelistmodel.cpp @@ -0,0 +1,80 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#include "wordcandidatelistmodel.h" + +#include "inputengine.h" + +WordCandidateListModel::WordCandidateListModel(InputEngine *inputEngine, QObject *parent) + : QAbstractListModel(parent) + , m_inputEngine(inputEngine) + , m_candidates(inputEngine ? inputEngine->candidates() : QStringList()) +{ + Q_ASSERT(m_inputEngine); + + connect(m_inputEngine, &InputEngine::candidatesChanged, this, &WordCandidateListModel::refresh); +} + +int WordCandidateListModel::rowCount(const QModelIndex &parent) const +{ + if (parent.isValid()) { + return 0; + } + + return m_candidates.size(); +} + +QVariant WordCandidateListModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid() || index.row() < 0 || index.row() >= m_candidates.size()) { + return {}; + } + + switch (role) { + case DisplayRole: + case Qt::DisplayRole: + return m_candidates.at(index.row()); + default: + return {}; + } +} + +QHash WordCandidateListModel::roleNames() const +{ + return { + {DisplayRole, "display"}, + }; +} + +int WordCandidateListModel::count() const +{ + return m_candidates.size(); +} + +void WordCandidateListModel::selectItem(int index) +{ + if (!m_inputEngine || index < 0 || index >= m_candidates.size()) { + return; + } + + m_inputEngine->selectCandidate(index); +} + +void WordCandidateListModel::refresh() +{ + const QStringList candidates = m_inputEngine ? m_inputEngine->candidates() : QStringList(); + if (m_candidates == candidates) { + return; + } + + const int oldCount = m_candidates.size(); + beginResetModel(); + m_candidates = candidates; + endResetModel(); + if (oldCount != m_candidates.size()) { + Q_EMIT countChanged(); + } +} diff --git a/virtualkeyboard/wordcandidatelistmodel.h b/virtualkeyboard/wordcandidatelistmodel.h new file mode 100644 index 0000000..59afe77 --- /dev/null +++ b/virtualkeyboard/wordcandidatelistmodel.h @@ -0,0 +1,45 @@ +/* + SPDX-FileCopyrightText: 2026 Devin Lin + + SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL +*/ + +#pragma once + +#include + +class InputEngine; + +/** + * Exposes the input engine's word candidates as a list model. + */ +class WordCandidateListModel : public QAbstractListModel +{ + Q_OBJECT + Q_PROPERTY(int count READ count NOTIFY countChanged) + +public: + enum Role { + DisplayRole = Qt::UserRole + 1, + }; + Q_ENUM(Role) + + explicit WordCandidateListModel(InputEngine *inputEngine, QObject *parent = nullptr); + + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QHash roleNames() const override; + + int count() const; + + Q_INVOKABLE void selectItem(int index); + +Q_SIGNALS: + void countChanged(); + +private: + void refresh(); + + InputEngine *m_inputEngine = nullptr; + QStringList m_candidates; +};