Debian Codegraph @

qt6/platforminputcontext/qfcitxplatforminputcontext.cpp

raw
1 /*
2 * SPDX-FileCopyrightText: 2011~2017 CSSlayer <[email protected]>
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 *
6 */
7
8 #include <QDBusConnection>
9 #include <QDebug>
10 #include <QInputMethod>
11 #include <QKeyEvent>
12 #include <QMetaMethod>
13 #include <QPalette>
14 #include <QTextCharFormat>
15 #include <QWidget>
16 #include <QWindow>
17 #include <qnamespace.h>
18 #include <qpa/qplatformcursor.h>
19 #include <qpa/qplatformnativeinterface.h>
20 #include <qpa/qplatformscreen.h>
21 #include <qpa/qwindowsysteminterface.h>
22
23 #include <cerrno>
24 #include <csignal>
25 #include <unistd.h>
26
27 #include "fcitx4watcher.h"
28 #include "fcitxcandidatewindow.h"
29 #include "fcitxflags.h"
30 #include "fcitxtheme.h"
31 #include "hybridinputcontext.h"
32 #include "qfcitxplatforminputcontext.h"
33 #include "qtkey.h"
34
35 #include <array>
36 #include <memory>
37 #ifdef ENABLE_X11
38 #include <xcb/xcb.h>
39 #endif
40
41 namespace fcitx {
42
43 namespace {
44
45 template <typename T>
46 using XCBReply = std::unique_ptr<T, decltype(&std::free)>;
47
48 template <typename T>
49 XCBReply<T> makeXCBReply(T *ptr) noexcept {
50 return {ptr, &std::free};
51 }
52
53 #ifdef ENABLE_X11
54 void setFocusGroupForX11(const QByteArray &uuid) {
55 if (uuid.size() != 16) {
56 return;
57 }
58
59 if (QGuiApplication::platformName() != QLatin1String("xcb")) {
60 return;
61 }
62
63 auto *native = QGuiApplication::platformNativeInterface();
64 if (!native) {
65 return;
66 }
67
68 auto *connection = static_cast<xcb_connection_t *>(
69 native->nativeResourceForIntegration(QByteArray("connection")));
70
71 if (!connection) {
72 return;
73 }
74
75 xcb_atom_t result = XCB_ATOM_NONE;
76 {
77 char atomName[] = "_FCITX_SERVER";
78 xcb_intern_atom_cookie_t cookie =
79 xcb_intern_atom(connection, false, strlen(atomName), atomName);
80 auto reply =
81 makeXCBReply(xcb_intern_atom_reply(connection, cookie, nullptr));
82 if (reply) {
83 result = reply->atom;
84 }
85
86 if (result == XCB_ATOM_NONE) {
87 return;
88 }
89 }
90
91 xcb_window_t owner = XCB_WINDOW_NONE;
92 {
93 auto cookie = xcb_get_selection_owner(connection, result);
94 auto reply = makeXCBReply(
95 xcb_get_selection_owner_reply(connection, cookie, nullptr));
96 if (reply) {
97 owner = reply->owner;
98 }
99 }
100 if (owner == XCB_WINDOW_NONE) {
101 return;
102 }
103
104 xcb_client_message_event_t ev;
105
106 memset(&ev, 0, sizeof(ev));
107 ev.response_type = XCB_CLIENT_MESSAGE;
108 ev.window = owner;
109 ev.type = result;
110 ev.format = 8;
111 memcpy(ev.data.data8, uuid.constData(), 16);
112
113 xcb_send_event(connection, false, owner, XCB_EVENT_MASK_NO_EVENT,
114 reinterpret_cast<char *>(&ev));
115 xcb_flush(connection);
116 }
117 #endif
118
119 bool get_boolean_env(const char *name, bool defval) {
120 const char *value = getenv(name);
121
122 if (value == nullptr) {
123 return defval;
124 }
125
126 if (strcmp(value, "") == 0 || strcmp(value, "0") == 0 ||
127 strcmp(value, "false") == 0 || strcmp(value, "False") == 0 ||
128 strcmp(value, "FALSE") == 0) {
129 return false;
130 }
131
132 return true;
133 }
134
135 inline const char *get_locale() {
136 const char *locale = getenv("LC_ALL");
137 if (!locale) {
138 locale = getenv("LC_CTYPE");
139 }
140 if (!locale) {
141 locale = getenv("LANG");
142 }
143 if (!locale) {
144 locale = "C";
145 }
146
147 return locale;
148 }
149
150 struct xkb_context *_xkb_context_new_helper() {
151 struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
152 if (context) {
153 xkb_context_set_log_level(context, XKB_LOG_LEVEL_CRITICAL);
154 }
155
156 return context;
157 }
158
159 QObject *deepestFocusProxy(QObject *object) {
160 auto *widget = qobject_cast<QWidget *>(object);
161 if (!widget) {
162 return object;
163 }
164
165 while (auto *proxy = widget->focusProxy()) {
166 widget = proxy;
167 }
168 return widget;
169 }
170
171 } // namespace
172
173 FcitxQtICData::FcitxQtICData(QFcitxPlatformInputContext *context,
174 QWindow *window)
175 : proxy(new HybridInputContext(context->watcher(), context->fcitx4Watcher(),
176 context)),
177 context_(context), window_(window) {
178 proxy->setProperty("icData",
179 QVariant::fromValue(static_cast<void *>(this)));
180 QObject::connect(window, &QWindow::visibilityChanged, proxy,
181 [this](bool visible) {
182 if (!visible) {
183 resetCandidateWindow();
184 }
185 });
186 QObject::connect(context_->watcher(), &FcitxQtWatcher::availabilityChanged,
187 proxy, [this](bool avail) {
188 if (!avail) {
189 resetCandidateWindow();
190 }
191 });
192 window->installEventFilter(this);
193 }
194 FcitxQtICData::~FcitxQtICData() {
195 if (window_) {
196 window_->removeEventFilter(this);
197 }
198 delete proxy;
199 resetCandidateWindow();
200 }
201
202 bool FcitxQtICData::eventFilter(QObject * /*watched*/, QEvent *event) {
203 if (event->type() != QMouseEvent::MouseButtonPress) {
204 return false;
205 }
206 auto *focusObject = context_->focusObjectWrapper();
207 if (!focusObject) {
208 return false;
209 }
210 if (!window_ || window_ != context_->focusWindowWrapper() ||
211 !context_->hasPreedit()) {
212 return false;
213 }
214 if (focusObject->metaObject()->className() ==
215 QLatin1String("KateViewInternal") ||
216 (focusObject->metaObject()->className() == QLatin1String("QtWidget") &&
217 QCoreApplication::applicationFilePath().endsWith("soffice.bin")) ||
218 focusObject->metaObject()->className() ==
219 QLatin1String("Konsole::TerminalDisplay")) {
220 if (context_->commitPreedit()) {
221 if (proxy->isValid()) {
222 proxy->reset();
223 }
224 }
225 }
226 return false;
227 }
228
229 FcitxCandidateWindow *FcitxQtICData::candidateWindow(bool create) {
230 if (!candidateWindow_ && create) {
231 candidateWindow_ = new FcitxCandidateWindow(window(), context_);
232 QObject::connect(
233 candidateWindow_, &FcitxCandidateWindow::candidateSelected, proxy,
234 [proxy = proxy](int index) { proxy->selectCandidate(index); });
235 QObject::connect(candidateWindow_, &FcitxCandidateWindow::prevClicked,
236 proxy, [proxy = proxy]() { proxy->prevPage(); });
237 QObject::connect(candidateWindow_, &FcitxCandidateWindow::nextClicked,
238 proxy, [proxy = proxy]() { proxy->nextPage(); });
239 }
240 return candidateWindow_;
241 }
242
243 void FcitxQtICData::resetCandidateWindow() {
244 if (auto *w = candidateWindow_.data()) {
245 candidateWindow_ = nullptr;
246 w->deleteLater();
247 return;
248 }
249 }
250
251 QFcitxPlatformInputContext::QFcitxPlatformInputContext()
252 : watcher_(new FcitxQtWatcher(
253 QDBusConnection::connectToBus(QDBusConnection::SessionBus, "fcitx"),
254 this)),
255 fcitx4Watcher_(new Fcitx4Watcher(watcher_->connection(), this)),
256 cursorPos_(0), useSurroundingText_(false),
257 syncMode_(get_boolean_env("FCITX_QT_USE_SYNC", false)), destroy_(false),
258 xkbContext_(_xkb_context_new_helper()),
259 xkbComposeTable_(xkbContext_ ? xkb_compose_table_new_from_locale(
260 xkbContext_.data(), get_locale(),
261 XKB_COMPOSE_COMPILE_NO_FLAGS)
262 : nullptr),
263 xkbComposeState_(xkbComposeTable_
264 ? xkb_compose_state_new(xkbComposeTable_.data(),
265 XKB_COMPOSE_STATE_NO_FLAGS)
266 : nullptr) {
267 registerFcitxQtDBusTypes();
268 watcher_->setWatchPortal(true);
269
270 // Input context may be created without QApplication with wayland, defer it
271 // to event loop to ensure event dispatcher is avaiable.
272 QTimer::singleShot(0, this, [this]() {
273 watcher_->watch();
274 fcitx4Watcher_->watch();
275 });
276 }
277
278 QFcitxPlatformInputContext::~QFcitxPlatformInputContext() {
279 destroy_ = true;
280 watcher_->unwatch();
281 fcitx4Watcher_->unwatch();
282 cleanUp();
283 delete watcher_;
284 delete fcitx4Watcher_;
285 }
286
287 bool QFcitxPlatformInputContext::objectAcceptsInputMethod() const {
288 bool enabled = false;
289 QObject *object = qGuiApp->focusObject();
290 if (object) {
291 QInputMethodQueryEvent query(Qt::ImEnabled);
292 QGuiApplication::sendEvent(object, &query);
293 enabled = query.value(Qt::ImEnabled).toBool();
294 }
295
296 QObject *realFocusObject = focusObjectWrapper();
297 // Make sure we don't query same object twice.
298 if (realFocusObject && realFocusObject != object && !enabled) {
299 QInputMethodQueryEvent query(Qt::ImEnabled);
300 QGuiApplication::sendEvent(realFocusObject, &query);
301 enabled = query.value(Qt::ImEnabled).toBool();
302 }
303
304 return enabled;
305 }
306
307 bool QFcitxPlatformInputContext::shouldDisableInputMethod() const {
308 return !inputMethodAccepted() && !objectAcceptsInputMethod();
309 }
310
311 void QFcitxPlatformInputContext::cleanUp() {
312 icMap_.clear();
313
314 if (!destroy_) {
315 commitPreedit();
316 }
317 }
318
319 bool QFcitxPlatformInputContext::isValid() const { return true; }
320
321 void QFcitxPlatformInputContext::invokeAction(QInputMethod::Action imAction,
322 int cursorPosition) {
323 unsigned int action;
324 if (imAction == QInputMethod::Click) {
325 action = 0;
326 } else if (imAction == QInputMethod::ContextMenu) {
327 action = 1;
328 } else {
329 return;
330 }
331 if (auto *proxy = validIC(); proxy->supportInvokeAction()) {
332 if (cursorPosition >= 0 && cursorPosition <= preedit_.length()) {
333 auto ucs4Cursor = preedit_.left(cursorPosition).toUcs4().length();
334 proxy->invokeAction(action, ucs4Cursor);
335 }
336 } else {
337 if (cursorPosition <= 0 || cursorPosition >= preedit_.length()) {
338 // qDebug() << action << cursorPosition;
339 reset();
340 }
341 }
342 }
343
344 bool QFcitxPlatformInputContext::commitPreedit(QPointer<QObject> input) {
345 if (!input) {
346 return false;
347 }
348 if (preeditList_.isEmpty()) {
349 return false;
350 }
351 QInputMethodEvent e;
352 if (!commitPreedit_.isEmpty()) {
353 e.setCommitString(commitPreedit_);
354 }
355 commitPreedit_.clear();
356 preeditList_.clear();
357 QCoreApplication::sendEvent(input, &e);
358 return true;
359 }
360
361 bool checkUtf8(const QByteArray &byteArray) {
362 QString s = QString::fromUtf8(byteArray);
363 return !s.contains(QChar::ReplacementCharacter);
364 }
365
366 void QFcitxPlatformInputContext::reset() {
367 commitPreedit();
368 if (auto *proxy = validIC()) {
369 proxy->reset();
370 }
371 if (xkbComposeState_) {
372 xkb_compose_state_reset(xkbComposeState_.data());
373 }
374 QPlatformInputContext::reset();
375 }
376
377 void QFcitxPlatformInputContext::update(Qt::InputMethodQueries queries) {
378 QWindow *window = focusWindowWrapper();
379 auto *proxy = validICByWindow(window);
380 if (!proxy) {
381 return;
382 }
383
384 FcitxQtICData &data = *static_cast<FcitxQtICData *>(
385 proxy->property("icData").value<void *>());
386
387 QObject *input = focusObjectWrapper();
388 if (!input) {
389 return;
390 }
391
392 // Limit the queries to the only ones we care about.
393 queries &=
394 (Qt::ImEnabled | Qt::ImHints | Qt::ImSurroundingText |
395 Qt::ImCursorPosition | Qt::ImAnchorPosition | Qt::ImCursorRectangle);
396
397 QInputMethodQueryEvent query(queries);
398 QGuiApplication::sendEvent(input, &query);
399
400 if (queries & Qt::ImCursorRectangle) {
401 cursorRectChanged();
402 }
403
404 if (queries & Qt::ImEnabled) {
405 if (shouldDisableInputMethod()) {
406 addCapability(data, FcitxCapabilityFlag_Disable);
407 } else {
408 removeCapability(data, FcitxCapabilityFlag_Disable);
409 }
410 }
411
412 if (queries & Qt::ImHints) {
413 Qt::InputMethodHints hints =
414 Qt::InputMethodHints(query.value(Qt::ImHints).toUInt());
415
416 #define CHECK_HINTS(_HINTS, _CAPABILITY) \
417 if (hints & (_HINTS)) \
418 addCapability(data, FcitxCapabilityFlag_##_CAPABILITY); \
419 else \
420 removeCapability(data, FcitxCapabilityFlag_##_CAPABILITY);
421
422 CHECK_HINTS(Qt::ImhHiddenText, Password)
423 CHECK_HINTS(Qt::ImhSensitiveData, Sensitive)
424 CHECK_HINTS(Qt::ImhNoAutoUppercase, NoAutoUpperCase)
425 CHECK_HINTS(Qt::ImhPreferNumbers, Number)
426 CHECK_HINTS(Qt::ImhPreferUppercase, Uppercase)
427 CHECK_HINTS(Qt::ImhPreferLowercase, Lowercase)
428 CHECK_HINTS(Qt::ImhNoPredictiveText, NoSpellCheck)
429 CHECK_HINTS(Qt::ImhDigitsOnly, Digit)
430 CHECK_HINTS(Qt::ImhFormattedNumbersOnly, Number)
431 CHECK_HINTS(Qt::ImhUppercaseOnly, Uppercase)
432 CHECK_HINTS(Qt::ImhLowercaseOnly, Lowercase)
433 CHECK_HINTS(Qt::ImhDialableCharactersOnly, Dialable)
434 CHECK_HINTS(Qt::ImhEmailCharactersOnly, Email)
435 CHECK_HINTS(Qt::ImhPreferLatin, Alpha)
436 CHECK_HINTS(Qt::ImhUrlCharactersOnly, Url)
437 CHECK_HINTS(Qt::ImhMultiLine, Multiline)
438 }
439
440 bool setSurrounding = false;
441 do {
442 if (!useSurroundingText_) {
443 break;
444 }
445 if (!(queries & (Qt::ImSurroundingText | Qt::ImCursorPosition |
446 Qt::ImAnchorPosition))) {
447 break;
448 }
449 if ((data.capability & FcitxCapabilityFlag_Password) ||
450 (data.capability & FcitxCapabilityFlag_Sensitive)) {
451 break;
452 }
453 QVariant var = query.value(Qt::ImSurroundingText);
454 QVariant var1 = query.value(Qt::ImCursorPosition);
455 QVariant var2 = query.value(Qt::ImAnchorPosition);
456 if (!var.isValid() || !var1.isValid()) {
457 break;
458 }
459 QString text = var.toString();
460 /* we don't want to waste too much memory here */
461 #define SURROUNDING_THRESHOLD 4096
462 if (text.length() < SURROUNDING_THRESHOLD) {
463 if (checkUtf8(text.toUtf8())) {
464 addCapability(data, FcitxCapabilityFlag_SurroundingText);
465
466 int cursor = var1.toInt();
467 int anchor;
468 if (var2.isValid()) {
469 anchor = var2.toInt();
470 } else {
471 anchor = cursor;
472 }
473
474 // adjust it to real character size
475 QVector<unsigned int> tempUCS4 = text.left(cursor).toUcs4();
476 cursor = tempUCS4.size();
477 tempUCS4 = text.left(anchor).toUcs4();
478 anchor = tempUCS4.size();
479 if (data.surroundingText != text) {
480 data.surroundingText = text;
481 proxy->setSurroundingText(text, cursor, anchor);
482 } else {
483 if (data.surroundingAnchor != anchor ||
484 data.surroundingCursor != cursor) {
485 proxy->setSurroundingTextPosition(cursor, anchor);
486 }
487 }
488 data.surroundingCursor = cursor;
489 data.surroundingAnchor = anchor;
490 setSurrounding = true;
491 }
492 }
493 if (!setSurrounding) {
494 data.surroundingAnchor = -1;
495 data.surroundingCursor = -1;
496 data.surroundingText = QString();
497 removeCapability(data, FcitxCapabilityFlag_SurroundingText);
498 }
499 } while (false);
500 }
501
502 void QFcitxPlatformInputContext::commit() {
503 auto *proxy = validICByWindow(lastWindow_);
504 commitPreedit(lastObject_);
505 if (proxy) {
506 proxy->reset();
507 FcitxQtICData &data = *static_cast<FcitxQtICData *>(
508 proxy->property("icData").value<void *>());
509 data.resetCandidateWindow();
510 }
511 }
512
513 void QFcitxPlatformInputContext::setFocusObject(QObject *object) {
514 Q_UNUSED(object);
515
516 // Since we have a wrapper, it's possible that real focus object is not
517 // changed. Do not emit focusOut and focusIn if:
518 // realFocusObject does not change.
519 QObject *realFocusObject = focusObjectWrapper();
520 if (lastObject_ == realFocusObject) {
521 return;
522 }
523
524 auto *proxy = validICByWindow(lastWindow_);
525 commitPreedit(lastObject_);
526 if (proxy) {
527 proxy->focusOut();
528 FcitxQtICData &data = *static_cast<FcitxQtICData *>(
529 proxy->property("icData").value<void *>());
530 data.resetCandidateWindow();
531 }
532
533 QWindow *window = focusWindowWrapper();
534 lastWindow_ = window;
535 lastObject_ = realFocusObject;
536 // Always create IC Data for window.
537 if (window) {
538 proxy = validICByWindow(window);
539 if (!proxy) {
540 createICData(window);
541 }
542 }
543 if (!window) {
544 lastWindow_ = nullptr;
545 lastObject_ = nullptr;
546 return;
547 }
548
549 if (proxy) {
550 proxy->focusIn();
551 // We need to delegate this otherwise it may cause self-recursion in
552 // certain application like libreoffice.
553 QTimer::singleShot(0, this,
554 [this, window = QPointer<QWindow>(lastWindow_)]() {
555 if (window != lastWindow_) {
556 return;
557 }
558 update(Qt::ImHints | Qt::ImEnabled);
559 updateCursorRect();
560 });
561 }
562
563 updateInputPanelVisible();
564 }
565
566 void QFcitxPlatformInputContext::updateCursorRect() {
567 if (validICByWindow(lastWindow_.data())) {
568 cursorRectChanged();
569 }
570 }
571
572 void QFcitxPlatformInputContext::windowDestroyed(QObject *object) {
573 /* access QWindow is not possible here, so we use our own map to do so */
574 icMap_.erase(static_cast<QWindow *>(object));
575 }
576
577 void QFcitxPlatformInputContext::cursorRectChanged() {
578 QWindow *inputWindow = focusWindowWrapper();
579 if (!inputWindow) {
580 return;
581 }
582 auto *proxy = validICByWindow(inputWindow);
583 if (!proxy) {
584 return;
585 }
586
587 FcitxQtICData &data = *static_cast<FcitxQtICData *>(
588 proxy->property("icData").value<void *>());
589
590 QRect r = cursorRectangleWrapper();
591 if (!r.isValid()) {
592 return;
593 }
594
595 if (auto *candidateWindow = data.candidateWindow(/*create=*/false)) {
596 if (candidateWindow->isVisible()) {
597 candidateWindow->updatePosition();
598 }
599 }
600
601 // not sure if this is necessary but anyway, qt's screen used to be buggy.
602 if (!inputWindow->screen()) {
603 return;
604 }
605
606 qreal scale = inputWindow->devicePixelRatio();
607 if (data.capability & FcitxCapabilityFlag_RelativeRect) {
608 auto margins = inputWindow->frameMargins();
609 r.translate(margins.left(), margins.top());
610 r = QRect(r.topLeft() * scale, r.size() * scale);
611 if (data.rect != r) {
612 data.rect = r;
613 proxy->setCursorRectV2(r.x(), r.y(), r.width(), r.height(), scale);
614 }
615 return;
616 }
617 auto screenGeometry = inputWindow->screen()->geometry();
618 auto point = inputWindow->mapToGlobal(r.topLeft());
619 auto native =
620 (point - screenGeometry.topLeft()) * scale + screenGeometry.topLeft();
621 QRect newRect(native, r.size() * scale);
622
623 if (data.rect != newRect) {
624 data.rect = newRect;
625 proxy->setCursorRect(newRect.x(), newRect.y(), newRect.width(),
626 newRect.height());
627 }
628 }
629
630 void QFcitxPlatformInputContext::createInputContextFinished(
631 const QByteArray &uuid) {
632 auto *proxy = qobject_cast<HybridInputContext *>(sender());
633 if (!proxy) {
634 return;
635 }
636 FcitxQtICData *data =
637 static_cast<FcitxQtICData *>(proxy->property("icData").value<void *>());
638 auto *w = data->window();
639 data->rect = QRect();
640
641 if (proxy->isValid() && !uuid.isEmpty()) {
642 QWindow *window = focusWindowWrapper();
643 #ifdef ENABLE_X11
644 setFocusGroupForX11(uuid);
645 #else
646 Q_UNUSED(uuid);
647 #endif
648 if (window && window == w) {
649 cursorRectChanged();
650 proxy->focusIn();
651 }
652 updateInputPanelVisible();
653 }
654
655 quint64 flag = 0;
656 flag |= FcitxCapabilityFlag_Preedit;
657 flag |= FcitxCapabilityFlag_FormattedPreedit;
658 flag |= FcitxCapabilityFlag_ClientUnfocusCommit;
659 flag |= FcitxCapabilityFlag_GetIMInfoOnFocus;
660 flag |= FcitxCapabilityFlag_KeyEventOrderFix;
661 flag |= FcitxCapabilityFlag_ReportKeyRepeat;
662 useSurroundingText_ =
663 get_boolean_env("FCITX_QT_ENABLE_SURROUNDING_TEXT", true);
664 if (useSurroundingText_) {
665 flag |= FcitxCapabilityFlag_SurroundingText;
666 }
667
668 if (QGuiApplication::platformName().startsWith("wayland")) {
669 flag |= FcitxCapabilityFlag_RelativeRect;
670 }
671 flag |= FcitxCapabilityFlag_ClientSideInputPanel;
672
673 if (shouldDisableInputMethod()) {
674 flag |= FcitxCapabilityFlag_Disable;
675 }
676
677 // Notify fcitx of the effective bits from 0bit to 40bit
678 // (FcitxCapabilityFlag_Disable)
679 data->proxy->setSupportedCapability(0x1ffffffffffULL);
680
681 addCapability(*data, flag, true);
682 }
683
684 void QFcitxPlatformInputContext::updateCapability(const FcitxQtICData &data) {
685 if (!data.proxy || !data.proxy->isValid()) {
686 return;
687 }
688 data.proxy->setCapability(data.capability);
689 }
690
691 void QFcitxPlatformInputContext::commitString(const QString &str) {
692 cursorPos_ = 0;
693 preeditList_.clear();
694 commitPreedit_.clear();
695 QObject *input = qGuiApp->focusObject();
696 if (!input) {
697 return;
698 }
699
700 QInputMethodEvent event;
701 event.setCommitString(str);
702 QCoreApplication::sendEvent(input, &event);
703 }
704
705 void QFcitxPlatformInputContext::updateFormattedPreedit(
706 const FcitxQtFormattedPreeditList &preeditList, int cursorPos) {
707 QObject *input = qGuiApp->focusObject();
708 if (!input) {
709 return;
710 }
711 if (cursorPos == cursorPos_ && preeditList == preeditList_) {
712 return;
713 }
714 preeditList_ = preeditList;
715 cursorPos_ = cursorPos;
716 QString str;
717 QString commitStr;
718 int pos = 0;
719 QList<QInputMethodEvent::Attribute> attrList;
720 Q_FOREACH (const FcitxQtFormattedPreedit &preedit, preeditList) {
721 str += preedit.string();
722 if (!(preedit.format() & FcitxTextFormatFlag_DontCommit)) {
723 commitStr += preedit.string();
724 }
725 QTextCharFormat format;
726 if (preedit.format() & FcitxTextFormatFlag_Underline) {
727 format.setUnderlineStyle(QTextCharFormat::DashUnderline);
728 }
729 if (preedit.format() & FcitxTextFormatFlag_Strike) {
730 format.setFontStrikeOut(true);
731 }
732 if (preedit.format() & FcitxTextFormatFlag_Bold) {
733 format.setFontWeight(QFont::Bold);
734 }
735 if (preedit.format() & FcitxTextFormatFlag_Italic) {
736 format.setFontItalic(true);
737 }
738 if (preedit.format() & FcitxTextFormatFlag_HighLight) {
739 QBrush brush;
740 QPalette palette;
741 palette = QGuiApplication::palette();
742 format.setBackground(QBrush(
743 QColor(palette.color(QPalette::Active, QPalette::Highlight))));
744 format.setForeground(QBrush(QColor(
745 palette.color(QPalette::Active, QPalette::HighlightedText))));
746 }
747 attrList.append(
748 QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, pos,
749 preedit.string().length(), format));
750 pos += preedit.string().length();
751 }
752
753 QByteArray array = str.toUtf8();
754 array.truncate(cursorPos);
755 cursorPos = QString::fromUtf8(array).length();
756
757 attrList.append(QInputMethodEvent::Attribute(QInputMethodEvent::Cursor,
758 cursorPos, 1, 0));
759 preedit_ = str;
760 commitPreedit_ = commitStr;
761 QInputMethodEvent event(str, attrList);
762 QCoreApplication::sendEvent(input, &event);
763 update(Qt::ImCursorRectangle);
764 }
765
766 void QFcitxPlatformInputContext::updateClientSideUI(
767 const FcitxQtFormattedPreeditList &preedit, int cursorpos,
768 const FcitxQtFormattedPreeditList &auxUp,
769 const FcitxQtFormattedPreeditList &auxDown,
770 const FcitxQtStringKeyValueList &candidates, int candidateIndex,
771 int layoutHint, bool hasPrev, bool hasNext) {
772 QObject *input = qGuiApp->focusObject();
773 if (!input) {
774 return;
775 }
776
777 auto *proxy = qobject_cast<HybridInputContext *>(sender());
778 if (!proxy) {
779 return;
780 }
781 FcitxQtICData *data =
782 static_cast<FcitxQtICData *>(proxy->property("icData").value<void *>());
783 auto *w = data->window();
784 auto *window = focusWindowWrapper();
785 if (window && w == window) {
786 data->candidateWindow(/*create=*/true)
787 ->updateClientSideUI(preedit, cursorpos, auxUp, auxDown, candidates,
788 candidateIndex, layoutHint, hasPrev, hasNext);
789 }
790 }
791
792 void QFcitxPlatformInputContext::deleteSurroundingText(int offset,
793 unsigned int _nchar) {
794 QObject *input = qGuiApp->focusObject();
795 if (!input) {
796 return;
797 }
798
799 QInputMethodEvent event;
800
801 auto *proxy = qobject_cast<HybridInputContext *>(sender());
802 if (!proxy) {
803 return;
804 }
805
806 FcitxQtICData *data =
807 static_cast<FcitxQtICData *>(proxy->property("icData").value<void *>());
808 auto ucsText = data->surroundingText.toStdU32String();
809
810 int cursor = data->surroundingCursor;
811 // make nchar signed so we are safer
812 int nchar = _nchar;
813 // Qt's reconvert semantics is different from gtk's. It doesn't count the
814 // current
815 // selection. Discard selection from nchar.
816 if (data->surroundingAnchor < data->surroundingCursor) {
817 nchar -= data->surroundingCursor - data->surroundingAnchor;
818 offset += data->surroundingCursor - data->surroundingAnchor;
819 cursor = data->surroundingAnchor;
820 } else if (data->surroundingAnchor > data->surroundingCursor) {
821 nchar -= data->surroundingAnchor - data->surroundingCursor;
822 cursor = data->surroundingCursor;
823 }
824
825 // validates
826 if (nchar >= 0 && cursor + offset >= 0 &&
827 cursor + offset + nchar <= static_cast<int>(ucsText.size())) {
828 // order matters
829 auto replacedChars = ucsText.substr(cursor + offset, nchar);
830 nchar = QString::fromUcs4(replacedChars.data(), replacedChars.size())
831 .size();
832
833 int start;
834 int len;
835 if (offset >= 0) {
836 start = cursor;
837 len = offset;
838 } else {
839 start = cursor + offset;
840 len = -offset;
841 }
842
843 auto prefixedChars = ucsText.substr(start, len);
844 offset = QString::fromUcs4(prefixedChars.data(), prefixedChars.size())
845 .size() *
846 (offset >= 0 ? 1 : -1);
847 event.setCommitString("", offset, nchar);
848 QCoreApplication::sendEvent(input, &event);
849 }
850 }
851
852 void QFcitxPlatformInputContext::forwardKey(unsigned int keyval,
853 unsigned int state, bool type) {
854 auto *proxy = qobject_cast<HybridInputContext *>(sender());
855 if (!proxy) {
856 return;
857 }
858 FcitxQtICData &data = *static_cast<FcitxQtICData *>(
859 proxy->property("icData").value<void *>());
860 auto *w = data.window();
861 QObject *input = qGuiApp->focusObject();
862 auto *window = focusWindowWrapper();
863 if (input && window && w == window) {
864 std::unique_ptr<QKeyEvent> keyevent{
865 createKeyEvent(keyval, state, type, data.event.get())};
866
867 forwardEvent(window, *keyevent);
868 }
869 }
870
871 void QFcitxPlatformInputContext::updateCurrentIM(const QString &name,
872 const QString &uniqueName,
873 const QString &langCode) {
874 Q_UNUSED(name);
875 Q_UNUSED(uniqueName);
876 QLocale newLocale(langCode);
877 if (locale_ != newLocale) {
878 locale_ = newLocale;
879 emitLocaleChanged();
880 }
881 }
882
883 void QFcitxPlatformInputContext::serverSideFocusOut() {
884 if (lastObject_ == focusObjectWrapper()) {
885 commitPreedit();
886 }
887 }
888
889 QLocale QFcitxPlatformInputContext::locale() const { return locale_; }
890
891 bool QFcitxPlatformInputContext::hasCapability(
892 Capability /*capability*/) const {
893 return true;
894 }
895
896 void QFcitxPlatformInputContext::showInputPanel() {
897 auto *proxy = validIC();
898 if (proxy == nullptr) {
899 return;
900 }
901 proxy->showVirtualKeyboard();
902 }
903
904 void QFcitxPlatformInputContext::hideInputPanel() {
905 auto *proxy = validIC();
906 if (proxy == nullptr) {
907 return;
908 }
909 proxy->hideVirtualKeyboard();
910 }
911
912 bool QFcitxPlatformInputContext::isInputPanelVisible() const {
913 return inputPanelVisible_;
914 }
915
916 void QFcitxPlatformInputContext::updateInputPanelVisible() {
917 // We have to use two levels of cache here, one level is from
918 // DBus to proxy, another level is from proxy to the one read by Qt.
919 //
920 // Because the API is designed in a way that "input panel" visibility is a
921 // per-input context thing. We have to update the value when focus is
922 // changed.
923 bool oldVisible = inputPanelVisible_;
924
925 bool newVisible = false;
926 if (auto *proxy = validIC()) {
927 newVisible = proxy->isVirtualKeyboardVisible();
928 }
929 if (newVisible != oldVisible) {
930 inputPanelVisible_ = newVisible;
931 emitInputPanelVisibleChanged();
932 }
933 }
934
935 void QFcitxPlatformInputContext::createICData(QWindow *w) {
936 auto iter = icMap_.find(w);
937 if (iter == icMap_.end()) {
938 auto result =
939 icMap_.emplace(std::piecewise_construct, std::forward_as_tuple(w),
940 std::forward_as_tuple(this, w));
941 connect(w, &QObject::destroyed, this,
942 &QFcitxPlatformInputContext::windowDestroyed);
943 iter = result.first;
944 auto &data = iter->second;
945
946 if (QGuiApplication::platformName() == QLatin1String("xcb")) {
947 data.proxy->setDisplay("x11:");
948 } else if (QGuiApplication::platformName().startsWith("wayland")) {
949 data.proxy->setDisplay("wayland:");
950 }
951 connect(data.proxy, &HybridInputContext::inputContextCreated, this,
952 &QFcitxPlatformInputContext::createInputContextFinished);
953 connect(data.proxy, &HybridInputContext::commitString, this,
954 &QFcitxPlatformInputContext::commitString);
955 connect(data.proxy, &HybridInputContext::forwardKey, this,
956 &QFcitxPlatformInputContext::forwardKey);
957 connect(data.proxy, &HybridInputContext::updateFormattedPreedit, this,
958 &QFcitxPlatformInputContext::updateFormattedPreedit);
959 connect(data.proxy, &HybridInputContext::deleteSurroundingText, this,
960 &QFcitxPlatformInputContext::deleteSurroundingText);
961 connect(data.proxy, &HybridInputContext::currentIM, this,
962 &QFcitxPlatformInputContext::updateCurrentIM);
963 connect(data.proxy, &HybridInputContext::updateClientSideUI, this,
964 &QFcitxPlatformInputContext::updateClientSideUI);
965 connect(data.proxy, &HybridInputContext::notifyFocusOut, this,
966 &QFcitxPlatformInputContext::serverSideFocusOut);
967 connect(data.proxy,
968 &HybridInputContext::virtualKeyboardVisibilityChanged, this,
969 [this]() {
970 if (validIC() == sender()) {
971 updateInputPanelVisible();
972 }
973 });
974 }
975 }
976
977 QKeyEvent *QFcitxPlatformInputContext::createKeyEvent(unsigned int keyval,
978 unsigned int state,
979 bool isRelease,
980 const QKeyEvent *event) {
981 QKeyEvent *newEvent = nullptr;
982 state &= (~(1U << 31));
983 if (event && event->nativeVirtualKey() == keyval &&
984 event->nativeModifiers() == state &&
985 isRelease == (event->type() == QEvent::KeyRelease)) {
986 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
987 newEvent = new QKeyEvent(
988 event->type(), event->key(), event->modifiers(),
989 event->nativeScanCode(), event->nativeVirtualKey(),
990 event->nativeModifiers(), event->text(), event->isAutoRepeat(),
991 event->count(), event->device());
992 #else
993 newEvent = new QKeyEvent(*event);
994 #endif
995 } else {
996 Qt::KeyboardModifiers qstate = Qt::NoModifier;
997
998 int count = 1;
999 if (state & FcitxKeyState_Alt) {
1000 qstate |= Qt::AltModifier;
1001 count++;
1002 }
1003
1004 if (state & FcitxKeyState_Shift) {
1005 qstate |= Qt::ShiftModifier;
1006 count++;
1007 }
1008
1009 if (state & FcitxKeyState_Ctrl) {
1010 qstate |= Qt::ControlModifier;
1011 count++;
1012 }
1013
1014 char32_t unicode = xkb_keysym_to_utf32(keyval);
1015 QString text;
1016 if (unicode) {
1017 text = QString::fromUcs4(&unicode, 1);
1018 }
1019
1020 int key = keysymToQtKey(keyval, text);
1021
1022 newEvent =
1023 new QKeyEvent(isRelease ? (QEvent::KeyRelease) : (QEvent::KeyPress),
1024 key, qstate, 0, keyval, state, text, false, count);
1025 if (event) {
1026 newEvent->setTimestamp(event->timestamp());
1027 }
1028 }
1029
1030 return newEvent;
1031 }
1032
1033 void QFcitxPlatformInputContext::forwardEvent(QWindow *window,
1034 const QKeyEvent &keyEvent) {
1035 // use same variable name as in QXcbKeyboard::handleKeyEvent
1036 QEvent::Type type = keyEvent.type();
1037 int qtcode = keyEvent.key();
1038 Qt::KeyboardModifiers modifiers = keyEvent.modifiers();
1039 quint32 code = keyEvent.nativeScanCode();
1040 quint32 sym = keyEvent.nativeVirtualKey();
1041 quint32 state = keyEvent.nativeModifiers();
1042 QString string = keyEvent.text();
1043 bool isAutoRepeat = keyEvent.isAutoRepeat();
1044 ulong time = keyEvent.timestamp();
1045 // copied from QXcbKeyboard::handleKeyEvent()
1046 if (type == QEvent::KeyPress && qtcode == Qt::Key_Menu) {
1047 QPoint globalPos;
1048 QPoint pos;
1049 if (window->screen()) {
1050 globalPos = window->screen()->handle()->cursor()->pos();
1051 pos = window->mapFromGlobal(globalPos);
1052 }
1053 QWindowSystemInterface::handleContextMenuEvent(window, false, pos,
1054 globalPos, modifiers);
1055 }
1056 QWindowSystemInterface::handleExtendedKeyEvent(window, time, type, qtcode,
1057 modifiers, code, sym, state,
1058 string, isAutoRepeat);
1059 }
1060
1061 bool QFcitxPlatformInputContext::filterEvent(const QEvent *event) {
1062 do {
1063 if (event->type() != QEvent::KeyPress &&
1064 event->type() != QEvent::KeyRelease) {
1065 break;
1066 }
1067
1068 const auto *keyEvent = static_cast<const QKeyEvent *>(event);
1069 quint32 keyval = keyEvent->nativeVirtualKey();
1070 quint32 keycode = keyEvent->nativeScanCode();
1071 quint32 state = keyEvent->nativeModifiers();
1072 bool isRelease = keyEvent->type() == QEvent::KeyRelease;
1073
1074 if (shouldDisableInputMethod()) {
1075 break;
1076 }
1077
1078 QObject *input = qGuiApp->focusObject();
1079
1080 if (!input) {
1081 break;
1082 }
1083
1084 auto *proxy = validICByWindow(focusWindowWrapper());
1085
1086 if (!proxy) {
1087 if (filterEventFallback(keyval, keycode, state, isRelease)) {
1088 return true;
1089 }
1090 break;
1091 }
1092
1093 update(Qt::ImHints | Qt::ImEnabled);
1094 proxy->focusIn();
1095 updateInputPanelVisible();
1096
1097 auto stateToFcitx = state;
1098 if (keyEvent->isAutoRepeat()) {
1099 // KeyState::Repeat
1100 stateToFcitx |= (1U << 31);
1101 }
1102 auto reply = proxy->processKeyEvent(keyval, keycode, stateToFcitx,
1103 isRelease, keyEvent->timestamp());
1104
1105 if (Q_UNLIKELY(syncMode_)) {
1106 reply.waitForFinished();
1107
1108 if (reply.isError() ||
1109 !HybridInputContext::processKeyEventResult(reply)) {
1110 if (filterEventFallback(keyval, keycode, state, isRelease)) {
1111 return true;
1112 }
1113 break;
1114 }
1115 update(Qt::ImCursorRectangle);
1116 return true;
1117 }
1118 auto *watcher = new ProcessKeyWatcher(*keyEvent, focusWindowWrapper(),
1119 reply, proxy);
1120 connect(watcher, &QDBusPendingCallWatcher::finished, this,
1121 &QFcitxPlatformInputContext::processKeyEventFinished);
1122 return true;
1123
1124 } while (false);
1125 return QPlatformInputContext::filterEvent(event);
1126 }
1127
1128 void QFcitxPlatformInputContext::processKeyEventFinished(
1129 QDBusPendingCallWatcher *w) {
1130 auto *watcher = static_cast<ProcessKeyWatcher *>(w);
1131 bool filtered = false;
1132
1133 QWindow *window = watcher->window();
1134 // if window is already destroyed, we can only throw this event away.
1135 if (!window) {
1136 delete watcher;
1137 return;
1138 }
1139
1140 const QKeyEvent &keyEvent = watcher->keyEvent();
1141
1142 // use same variable name as in QXcbKeyboard::handleKeyEvent
1143 QEvent::Type type = keyEvent.type();
1144 quint32 code = keyEvent.nativeScanCode();
1145 quint32 sym = keyEvent.nativeVirtualKey();
1146 quint32 state = keyEvent.nativeModifiers();
1147 QString string = keyEvent.text();
1148
1149 if (watcher->isError() ||
1150 !HybridInputContext::processKeyEventResult(*watcher)) {
1151 filtered =
1152 filterEventFallback(sym, code, state, type == QEvent::KeyRelease);
1153 } else {
1154 filtered = true;
1155 }
1156
1157 if (!watcher->isError()) {
1158 update(Qt::ImCursorRectangle);
1159 }
1160
1161 if (!filtered) {
1162 forwardEvent(window, keyEvent);
1163 } else {
1164 auto *proxy = qobject_cast<HybridInputContext *>(watcher->parent());
1165 if (proxy) {
1166 FcitxQtICData &data = *static_cast<FcitxQtICData *>(
1167 proxy->property("icData").value<void *>());
1168 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
1169 data.event = std::make_unique<QKeyEvent>(
1170 keyEvent.type(), keyEvent.key(), keyEvent.modifiers(),
1171 keyEvent.nativeScanCode(), keyEvent.nativeVirtualKey(),
1172 keyEvent.nativeModifiers(), keyEvent.text(),
1173 keyEvent.isAutoRepeat(), keyEvent.count(), keyEvent.device());
1174 #else
1175 data.event = std::make_unique<QKeyEvent>(keyEvent);
1176 #endif
1177 }
1178 }
1179
1180 delete watcher;
1181 }
1182
1183 bool QFcitxPlatformInputContext::filterEventFallback(unsigned int keyval,
1184 unsigned int keycode,
1185 unsigned int state,
1186 bool isRelease) {
1187 Q_UNUSED(keycode);
1188 return processCompose(keyval, state, isRelease);
1189 }
1190
1191 HybridInputContext *QFcitxPlatformInputContext::validIC() const {
1192 if (icMap_.empty()) {
1193 return nullptr;
1194 }
1195 QWindow *window = focusWindowWrapper();
1196 return validICByWindow(window);
1197 }
1198
1199 HybridInputContext *
1200 QFcitxPlatformInputContext::validICByWindow(QWindow *w) const {
1201 if (!w) {
1202 return nullptr;
1203 }
1204
1205 if (icMap_.empty()) {
1206 return nullptr;
1207 }
1208 auto iter = icMap_.find(w);
1209 if (iter == icMap_.end()) {
1210 return nullptr;
1211 }
1212 const auto &data = iter->second;
1213 if (!data.proxy || !data.proxy->isValid()) {
1214 return nullptr;
1215 }
1216 return data.proxy;
1217 }
1218
1219 bool QFcitxPlatformInputContext::processCompose(unsigned int keyval,
1220 unsigned int state,
1221 bool isRelease) {
1222 Q_UNUSED(state);
1223
1224 if (!xkbComposeTable_ || isRelease) {
1225 return false;
1226 }
1227
1228 struct xkb_compose_state *xkbComposeState = xkbComposeState_.data();
1229
1230 enum xkb_compose_feed_result result =
1231 xkb_compose_state_feed(xkbComposeState, keyval);
1232 if (result == XKB_COMPOSE_FEED_IGNORED) {
1233 return false;
1234 }
1235
1236 enum xkb_compose_status status =
1237 xkb_compose_state_get_status(xkbComposeState);
1238 if (status == XKB_COMPOSE_NOTHING) {
1239 return false;
1240 }
1241 if (status == XKB_COMPOSE_COMPOSED) {
1242 std::array<char, 256> buffer;
1243 int length = xkb_compose_state_get_utf8(xkbComposeState, buffer.data(),
1244 buffer.size());
1245 xkb_compose_state_reset(xkbComposeState);
1246 if (length != 0) {
1247 commitString(QString::fromUtf8(buffer.data(), length));
1248 }
1249 } else if (status == XKB_COMPOSE_CANCELLED) {
1250 xkb_compose_state_reset(xkbComposeState);
1251 }
1252
1253 return true;
1254 }
1255
1256 QWindow *QFcitxPlatformInputContext::focusWindowWrapper() const {
1257 QWindow *focusWindow = qGuiApp->focusWindow();
1258 do {
1259 if (!focusWindow) {
1260 break;
1261 }
1262 QObject *realFocusObject = focusObjectWrapper();
1263 auto *widget = qobject_cast<QWidget *>(realFocusObject);
1264 if (!widget) {
1265 break;
1266 }
1267 auto *window = widget->topLevelWidget()->windowHandle();
1268 if (!window) {
1269 break;
1270 }
1271 focusWindow = window;
1272 } while (false);
1273 return focusWindow;
1274 }
1275
1276 QObject *QFcitxPlatformInputContext::focusObjectWrapper() const {
1277 return deepestFocusProxy(qGuiApp->focusObject());
1278 }
1279
1280 QRect QFcitxPlatformInputContext::cursorRectangleWrapper() const {
1281 QObject *object = focusObjectWrapper();
1282 QRect r;
1283 if (object && object != qGuiApp->focusObject() && object->isWidgetType()) {
1284 // Logic is borrowed from QWidgetPrivate::updateWidgetTransform.
1285 // If focusObject mismatches, the inputItemTransform will also mismatch,
1286 // so we need to do our own calculation.
1287 auto *widget = qobject_cast<QWidget *>(object);
1288 QTransform t;
1289 const QPoint p = widget->mapTo(widget->topLevelWidget(), QPoint(0, 0));
1290 t.translate(p.x(), p.y());
1291 r = widget->inputMethodQuery(Qt::ImCursorRectangle).toRect();
1292 if (r.isValid()) {
1293 r = t.mapRect(r);
1294 }
1295 } else {
1296 r = qGuiApp->inputMethod()->cursorRectangle().toRect();
1297 }
1298 return r;
1299 }
1300
1301 FcitxTheme *QFcitxPlatformInputContext::theme() {
1302 if (!theme_) {
1303 theme_ = new FcitxTheme(this);
1304 }
1305 return theme_;
1306 }
1307
1308 } // namespace fcitx