Introduce new input engine and framework to replace Qt VKBD

This commit is contained in:
Devin Lin committed 2026-10-14 20:00:54 -04:00
1 parent 481e6a3af1
commit d2a622c8b4
124 files changed
+8542 -2403

No files matched your search

+1
View File
@@ -28,4 +28,5 @@ compile_commands.json
.cache
Testing/
/.vscode/
/flatpak/flatpak-builder-tools/
.qtcreator/
+9 -1
View File
@@ -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)
+13 -6
View File
@@ -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.
+9
View File
@@ -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 \"$<TARGET_FILE:plasma-keyboard>\"\n"
+424
View File
@@ -0,0 +1,424 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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 <QLoggingCategory>
#include <QSignalSpy>
#include <QTest>
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<QPair<int, int>> deleteRequests;
QList<int> keyClickRequests;
QList<QPair<int, bool>> 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<Qt::Key> 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<int>(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<int>{Qt::Key_Q});
QVERIFY(backend->commitRequests.isEmpty());
QCOMPARE(engine.pressedKeys(), QList<int>{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<QString>("text");
QTest::addColumn<uint32_t>("cursorPositionUtf8");
QTest::addColumn<bool>("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"
+87 -4
View File
@@ -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<QVariant> &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<QVariant> &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. */
+10
View File
@@ -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
+244
View File
@@ -0,0 +1,244 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "keyboardlayoutgroupmodel.h"
#include "keyboardlayoutmetadata.h"
#include <QHash>
#include <algorithm>
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<int, QByteArray> 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<QString, int> groupIndexByPackageId;
QList<KeyboardLayoutModel::Layout> flatLayouts;
QList<QList<KeyboardLayoutModel::Layout>> 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<KeyboardLayoutModel::Layout>{});
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<KeyboardLayoutModel::Layout> 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});
}
+74
View File
@@ -0,0 +1,74 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#pragma once
#include "keyboardlayoutmodel.h"
#include <QAbstractListModel>
#include <QStringList>
/**
* 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<int, QByteArray> 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<Group> m_groups;
KeyboardLayoutModel *m_flatLayouts = nullptr;
QStringList m_formFactorFilter;
QString m_filterText;
QStringList m_enabledLayoutIds;
QStringList m_expandedGroupIds;
};
+156
View File
@@ -0,0 +1,156 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "keyboardlayoutmodel.h"
#include <QLocale>
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<int, QByteArray> 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<Layout> 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(", "));
}
+57
View File
@@ -0,0 +1,57 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#pragma once
#include <QAbstractListModel>
#include <QStringList>
/**
* 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<int, QByteArray> 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<Layout> layouts);
static QString descriptionForLocales(const QStringList &locales);
static bool matchesFilter(const Layout &layout, const QString &filterText);
private:
void emitDataChanged();
QList<Layout> m_layouts;
QString m_filterText;
QStringList m_enabledLayoutIds;
};
+85 -21
View File
@@ -6,7 +6,10 @@
*/
#include "plasmakeyboardkcm.h"
#include "../src/layoutpathhelper.h"
#include "keyboardlayoutmetadata.h"
#include <KRuntimePlatform>
#include <qqml.h>
@@ -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<PlasmaKeyboardSettings>("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"
+25 -2
View File
@@ -9,21 +9,44 @@
#include <KQuickManagedConfigModule>
#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;
};
+183
View File
@@ -0,0 +1,183 @@
/*
SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
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);
}
}
}
}
}
}
}
+51
View File
@@ -0,0 +1,51 @@
/*
SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
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);
}
}
}
}
}
}
-101
View File
@@ -1,101 +0,0 @@
/*
SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
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);
}
}
}
}
-77
View File
@@ -1,77 +0,0 @@
/*
SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
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);
}
}
}
}
}
}
+26 -12
View File
@@ -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:")
+17 -6
View File
@@ -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 {}
}
}
}
+27 -30
View File
@@ -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()
}
}
}
+6
View File
@@ -0,0 +1,6 @@
# SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
# SPDX-License-Identifier: BSD-2-Clause
add_subdirectory(defaultplugin)
plasma_install_package(en org.kde.plasma.keyboard.en keyboard/keyboardpackages)
+32
View File
@@ -0,0 +1,32 @@
# SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
# 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)
+104
View File
@@ -0,0 +1,104 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 }
}
}
+22
View File
@@ -0,0 +1,22 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 {} }
}
}
+30
View File
@@ -0,0 +1,30 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 {}
}
}
}
+68
View File
@@ -0,0 +1,68 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 }
}
}
+206
View File
@@ -0,0 +1,206 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 }
}
}
+39
View File
@@ -0,0 +1,39 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 {}
}
}
}
}
+56
View File
@@ -0,0 +1,56 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 }
}
}
+120
View File
@@ -0,0 +1,120 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 }
}
}
}
}
@@ -0,0 +1,6 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 {}
@@ -0,0 +1,6 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 {}
@@ -0,0 +1,6 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 {}
@@ -0,0 +1,6 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 {}
@@ -0,0 +1,6 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 {}
@@ -0,0 +1,6 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 {}
@@ -0,0 +1,6 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 {}
@@ -0,0 +1,6 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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 {}
+74
View File
@@ -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"
]
}
]
}
}
+26 -12
View File
@@ -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})
+1 -1
View File
@@ -6,5 +6,5 @@
#pragma once
#cmakedefine01 PLASMA_KEYBOARD_SOUND_ENABLED
#cmakedefine01 PLASMA_KEYBOARD_SOUNDS_ENABLED
#cmakedefine01 PLASMA_KEYBOARD_VIBRATION_ENABLED
+73
View File
@@ -0,0 +1,73 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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 <QDBusConnection>
#include <QDBusMetaType>
#include <QUrl>
using namespace Qt::StringLiterals;
Feedback::Feedback(QObject *parent)
: QObject(parent)
{
#if PLASMA_KEYBOARD_VIBRATION_ENABLED
qDBusRegisterMetaType<VibrationEvent>();
qDBusRegisterMetaType<VibrationEventList>();
#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<quint32>(durationMs)};
const VibrationEventList pattern = {vibrationEvent};
m_hapticInterface->Vibrate(u"org.kde.plasma.keyboard"_s, pattern);
}
#endif
+54
View File
@@ -0,0 +1,54 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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 <QObject>
#include <qqmlintegration.h>
#if PLASMA_KEYBOARD_SOUNDS_ENABLED
#include <QSoundEffect>
#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
};
-432
View File
@@ -1,432 +0,0 @@
/*
SPDX-FileCopyrightText: 2024 Aleix Pol i Gonzalez <aleixpol@kde.org>
SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
SPDX-FileCopyrightText: 2026 Kristen McWilliam <kristen@kde.org>
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 <QLoggingCategory>
#include <QTextFormat>
#include <set>
#include <QtWaylandClient/private/qwaylandwindow_p.h>
#include <qpa/qwindowsysteminterface.h>
Q_GLOBAL_STATIC(InputMethod, s_im)
Q_GLOBAL_STATIC_WITH_ARGS(const std::set<int>,
IGNORED_KEYS,
{
Qt::Key_Context1 // Triggered by "special keys" button
});
// Keys to always capture for keyboard navigation
QList<Qt::Key> initCapture()
{
return {
Qt::Key_Left,
Qt::Key_Right,
Qt::Key_Up,
Qt::Key_Down,
};
}
Q_GLOBAL_STATIC_WITH_ARGS(const QList<Qt::Key>, KEYBOARD_NAVIGATION_CAPTURE_KEYS, (initCapture()));
// Keys to capture when keyboard navigation is active
Q_GLOBAL_STATIC_WITH_ARGS(const QList<Qt::Key>, KEYBOARD_NAVIGATION_ACTIVE_CAPTURE_KEYS, (initCapture() + QList<Qt::Key>{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<int>(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<xkb_keysym_t> 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<xkb_keysym_t> 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<QTextFormat>().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"
-61
View File
@@ -1,61 +0,0 @@
/*
SPDX-FileCopyrightText: 2024 Aleix Pol i Gonzalez <aleixpol@kde.org>
SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
SPDX-FileCopyrightText: 2025 Kristen McWilliam <kristen@kde.org>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#pragma once
#include <QQuickItem>
#include <QQuickWindow>
#include <QVirtualKeyboardInputEngine>
#include <qqmlintegration.h>
#include <xkbcommon/xkbcommon.h>
#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;
};
+346
View File
@@ -0,0 +1,346 @@
/*
SPDX-FileCopyrightText: 2024 Aleix Pol i Gonzalez <aleixpol@kde.org>
SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
SPDX-FileCopyrightText: 2025 Kristen McWilliam <kristen@kde.org>
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 <QElapsedTimer>
#include <QtWaylandClient/private/qwayland-text-input-unstable-v1.h>
#include <xkbcommon/xkbcommon-keysyms.h>
Q_GLOBAL_STATIC(InputMethod, s_im)
static QList<Qt::Key> initCapture()
{
return {
Qt::Key_Left,
Qt::Key_Right,
Qt::Key_Up,
Qt::Key_Down,
};
}
Q_GLOBAL_STATIC_WITH_ARGS(const QList<Qt::Key>, KEYBOARD_NAVIGATION_CAPTURE_KEYS, (initCapture()));
Q_GLOBAL_STATIC_WITH_ARGS(const QList<Qt::Key>,
KEYBOARD_NAVIGATION_ACTIVE_CAPTURE_KEYS,
(initCapture() + QList<Qt::Key>{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"
+80
View File
@@ -0,0 +1,80 @@
/*
SPDX-FileCopyrightText: 2024 Aleix Pol i Gonzalez <aleixpol@kde.org>
SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
SPDX-FileCopyrightText: 2025 Kristen McWilliam <kristen@kde.org>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#pragma once
#include <QObject>
#include <QPointer>
#include <QWindow>
#include <qqmlintegration.h>
#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<QWindow> m_window;
bool m_hidden = false;
bool m_keyboardNavigationAvailable = false;
bool m_keyboardNavigationActive = false;
};
+77
View File
@@ -0,0 +1,77 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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;
}
+16
View File
@@ -0,0 +1,16 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#pragma once
#include "inputplugin.h"
#include <Qt>
/**
* Converts compositor content metadata to Qt input method hints.
*/
Qt::InputMethodHints mapInputMethodHints(InputPlugin::ContentHint contentHints, InputPlugin::ContentPurpose contentPurpose, bool autoCapitalizationEnabled);
+29
View File
@@ -0,0 +1,29 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#pragma once
#include <QObject>
#include <qqmlintegration.h>
/**
* 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)
};
+219
View File
@@ -0,0 +1,219 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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 <QDebug>
#include <QHash>
#include <QSet>
#include <QTimer>
#include <QWaylandClientExtensionTemplate>
#include <linux/input-event-codes.h>
class FakeInput : public QWaylandClientExtensionTemplate<FakeInput>, public QtWayland::org_kde_kwin_fake_input
{
public:
FakeInput()
: QWaylandClientExtensionTemplate<FakeInput>(ORG_KDE_KWIN_FAKE_INPUT_KEYBOARD_KEY_SINCE_VERSION)
{
initialize();
}
};
static const QHash<int, int> 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<int> 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<int> 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<int> 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<FakeInput *>(m_fakeInput)->keyboard_key(QT_KEY_TO_LINUX.value(key), pressed);
}
+37
View File
@@ -0,0 +1,37 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#pragma once
#include <QObject>
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;
};
-43
View File
@@ -1,43 +0,0 @@
/*
SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
SPDX-FileCopyrightText: 2026 Kristen McWilliam <kristen@kde.org>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#pragma once
#include <QDir>
#include <QStandardPaths>
/**
* 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;
}
}
}
}
+1 -7
View File
@@ -7,7 +7,6 @@
#include "config-plasma-keyboard.h"
#include "inputpanelintegration.h"
#include "layoutpathhelper.h"
#include "logging.h"
#include "plasmakeyboardsettings.h"
#include <plasma_keyboard_version.h>
@@ -19,7 +18,6 @@
#include <KLocalizedString>
#include <QCommandLineParser>
#include <QDir>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickWindow>
@@ -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);
}
+21 -8
View File
@@ -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"
+7 -1
View File
@@ -10,8 +10,11 @@
#include "overlaytrigger.h"
#include <QHash>
#include <QStringList>
#include <QTimer>
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<QChar, QStringList> m_diacriticsMap;
+1 -1
View File
@@ -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
+7
View File
@@ -19,6 +19,13 @@
<entry key="vibrationMs" type="Int">
<default>10</default>
</entry>
<entry key="characterPopupEnabled" type="Bool">
<label>Whether pressing a text key shows a character popup.</label>
<default>true</default>
</entry>
<entry key="enabledKeyboardLayoutIds" type="StringList">
<default></default>
</entry>
<entry key="enabledLocales" type="StringList">
<default></default>
</entry>
+130
View File
@@ -0,0 +1,130 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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();
}
}
}
-124
View File
@@ -1,124 +0,0 @@
/*
SPDX-FileCopyrightText: 2025 Aleix Pol i Gonzalez <aleixpol@kde.org>
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();
}
}
}
}
}
-84
View File
@@ -1,84 +0,0 @@
/*
SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
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
}
}
}
}
+45 -122
View File
@@ -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();
}
}
-59
View File
@@ -1,59 +0,0 @@
// SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
// 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);
}
}
}
}
-27
View File
@@ -1,27 +0,0 @@
# SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
# 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)
-18
View File
@@ -1,18 +0,0 @@
# SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
# 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)
File diff suppressed because it is too large. Load diff
-28
View File
@@ -1,28 +0,0 @@
// SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
// 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<VibrationEvent>();
qDBusRegisterMetaType<VibrationEventList>();
}
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<quint32>(durationMs)};
const VibrationEventList pattern = {event};
m_interface->Vibrate(appId, pattern);
}
#include "moc_vibration.cpp"
-26
View File
@@ -1,26 +0,0 @@
// SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
// SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
#pragma once
#include <QList>
#include <QObject>
#include <qqmlregistration.h>
#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};
};
+101
View File
@@ -0,0 +1,101 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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();
}
+51
View File
@@ -0,0 +1,51 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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;
};
+112
View File
@@ -0,0 +1,112 @@
# SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
# 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)
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-FileCopyrightText: 2020-2022 Harald Sitter <sitter@kde.org>
# 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
@@ -0,0 +1,180 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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)
}
}
}
}
}
}
@@ -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
@@ -0,0 +1,80 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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
}
}
@@ -0,0 +1,129 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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
}
}
+150
View File
@@ -0,0 +1,150 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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);
}
}
}
}
}
@@ -0,0 +1,33 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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
}
@@ -0,0 +1,76 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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 {}
}
}
@@ -0,0 +1,38 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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()
}
@@ -0,0 +1,349 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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();
}
}
}
@@ -0,0 +1,44 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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
}
@@ -0,0 +1,141 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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);
}
}
}
}
}
@@ -0,0 +1,239 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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()
}
}
}
}
}
}
@@ -1,5 +1,8 @@
// SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
// SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
import QtQuick
import QtQuick.Layouts
@@ -0,0 +1,66 @@
/*
SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
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)
}
}
}
@@ -0,0 +1,238 @@
// SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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
}
}
}
}
@@ -0,0 +1,18 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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();
}
}
}
@@ -0,0 +1,14 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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
}
@@ -0,0 +1,24 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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)
}
}
}
@@ -0,0 +1,13 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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
}
@@ -0,0 +1,18 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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
}
@@ -0,0 +1,251 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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)
}
@@ -0,0 +1,27 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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;
}
}
}
@@ -0,0 +1,19 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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()
}
@@ -0,0 +1,59 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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;
}
}
}
+124
View File
@@ -0,0 +1,124 @@
// SPDX-FileCopyrightText: 2025 Devin Lin <devin@kde.org>
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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;
}
}
}
}
@@ -0,0 +1,154 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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();
}
}
@@ -0,0 +1,74 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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()
}
}
}
@@ -0,0 +1,98 @@
// SPDX-FileCopyrightText: 2026 Devin Lin <devin@kde.org>
// 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();
}
}
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more