Debian Codegraph @

qt4/inputcontext/qfcitxinputcontext.cpp

raw
1 /*
2 * SPDX-FileCopyrightText: 2012~2017 CSSlayer <[email protected]>
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 *
6 */
7
8 #include <QApplication>
9 #include <QDBusConnection>
10 #include <QDateTime>
11 #include <QDebug>
12 #include <QKeyEvent>
13 #include <QPalette>
14 #include <QTextCharFormat>
15 #include <QTextCodec>
16 #include <QWidget>
17 #ifdef ENABLE_X11
18 #include <QX11Info>
19 #endif
20 #include <array>
21 #include <errno.h>
22 #include <signal.h>
23 #include <unistd.h>
24
25 #include "qtkey.h"
26
27 #include "fcitxflags.h"
28 #include "fcitxqtinputcontextproxy.h"
29 #include "fcitxqtwatcher.h"
30 #include "qfcitxinputcontext.h"
31
32 #ifdef ENABLE_X11
33 #include <X11/Xlib.h>
34 #endif
35 #include <memory>
36 #undef KeyPress
37 #undef KeyRelease
38 #undef FocusIn
39 #undef FocusOut
40
41 namespace fcitx {
42
43 #ifdef ENABLE_X11
44 void setFocusGroupForX11(const QByteArray &uuid) {
45 if (uuid.size() != 16) {
46 return;
47 }
48
49 Display *xdisplay = QX11Info::display();
50 if (!xdisplay) {
51 return;
52 }
53
54 Atom atom = XInternAtom(xdisplay, "_FCITX_SERVER", False);
55 if (!atom) {
56 return;
57 }
58 Window window = XGetSelectionOwner(xdisplay, atom);
59 if (!window) {
60 return;
61 }
62 XEvent ev;
63
64 memset(&ev, 0, sizeof(ev));
65 ev.xclient.type = ClientMessage;
66 ev.xclient.window = window;
67 ev.xclient.message_type = atom;
68 ev.xclient.format = 8;
69 memcpy(ev.xclient.data.b, uuid.constData(), 16);
70
71 XSendEvent(xdisplay, window, False, NoEventMask, &ev);
72 XSync(xdisplay, False);
73 }
74 #endif
75
76 static bool key_filtered = false;
77
78 static bool get_boolean_env(const char *name, bool defval) {
79 const char *value = getenv(name);
80
81 if (value == nullptr)
82 return defval;
83
84 if (strcmp(value, "") == 0 || strcmp(value, "0") == 0 ||
85 strcmp(value, "false") == 0 || strcmp(value, "False") == 0 ||
86 strcmp(value, "FALSE") == 0)
87 return false;
88
89 return true;
90 }
91
92 static inline const char *get_locale() {
93 const char *locale = getenv("LC_ALL");
94 if (!locale)
95 locale = getenv("LC_CTYPE");
96 if (!locale)
97 locale = getenv("LANG");
98 if (!locale)
99 locale = "C";
100
101 return locale;
102 }
103
104 struct xkb_context *_xkb_context_new_helper() {
105 struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
106 if (context) {
107 xkb_context_set_log_level(context, XKB_LOG_LEVEL_CRITICAL);
108 }
109
110 return context;
111 }
112
113 QFcitxInputContext::QFcitxInputContext()
114 : watcher_(new FcitxQtWatcher(
115 QDBusConnection::connectToBus(QDBusConnection::SessionBus, "fcitx"),
116 this)),
117 cursorPos_(0), useSurroundingText_(false),
118 syncMode_(get_boolean_env("FCITX_QT_USE_SYNC", false)), destroy_(false),
119 xkbContext_(_xkb_context_new_helper()),
120 xkbComposeTable_(xkbContext_ ? xkb_compose_table_new_from_locale(
121 xkbContext_.data(), get_locale(),
122 XKB_COMPOSE_COMPILE_NO_FLAGS)
123 : 0),
124 xkbComposeState_(xkbComposeTable_
125 ? xkb_compose_state_new(xkbComposeTable_.data(),
126 XKB_COMPOSE_STATE_NO_FLAGS)
127 : 0) {
128 registerFcitxQtDBusTypes();
129 watcher_->setWatchPortal(true);
130 watcher_->watch();
131 }
132
133 QFcitxInputContext::~QFcitxInputContext() {
134 destroy_ = true;
135 watcher_->unwatch();
136 cleanUp();
137 delete watcher_;
138 }
139
140 void QFcitxInputContext::cleanUp() {
141 icMap_.clear();
142
143 if (!destroy_) {
144 commitPreedit();
145 }
146 }
147
148 void QFcitxInputContext::mouseHandler(int cursorPosition, QMouseEvent *event) {
149 if (event->type() != QEvent::MouseButtonRelease) {
150 return;
151 }
152
153 unsigned int action;
154 if (event->button() == Qt::LeftButton) {
155 action = 0;
156 } else if (event->button() == Qt::RightButton) {
157 action = 1;
158 } else {
159 return;
160 }
161 if (FcitxQtInputContextProxy *proxy = validIC();
162 proxy->supportInvokeAction()) {
163 proxy->invokeAction(action, cursorPosition);
164 } else {
165 if (cursorPosition <= 0 || cursorPosition >= preedit_.length()) {
166 // qDebug() << action << cursorPosition;
167 reset();
168 }
169 }
170 }
171
172 void QFcitxInputContext::commitPreedit(QPointer<QWidget> input) {
173 if (!input)
174 return;
175 if (commitPreedit_.length() <= 0)
176 return;
177 QInputMethodEvent e;
178 e.setCommitString(commitPreedit_);
179 QCoreApplication::sendEvent(input, &e);
180 commitPreedit_.clear();
181 preeditList_.clear();
182 }
183
184 bool checkUtf8(const QByteArray &byteArray) {
185 QTextCodec::ConverterState state;
186 QTextCodec *codec = QTextCodec::codecForName("UTF-8");
187 const QString text =
188 codec->toUnicode(byteArray.constData(), byteArray.size(), &state);
189 return state.invalidChars == 0;
190 }
191
192 void QFcitxInputContext::reset() {
193 commitPreedit();
194 if (FcitxQtInputContextProxy *proxy = validIC()) {
195 proxy->reset();
196 }
197 if (xkbComposeState_) {
198 xkb_compose_state_reset(xkbComposeState_.data());
199 }
200 }
201
202 void QFcitxInputContext::update() {
203 QWidget *window = qApp->focusWidget();
204 FcitxQtInputContextProxy *proxy = validICByWindow(window);
205 if (!proxy)
206 return;
207
208 FcitxQtICData &data = *static_cast<FcitxQtICData *>(
209 proxy->property("icData").value<void *>());
210
211 QWidget *input = qApp->focusWidget();
212 if (!input)
213 return;
214
215 cursorRectChanged();
216
217 if (true) {
218 Qt::InputMethodHints hints = input->inputMethodHints();
219
220 #define CHECK_HINTS(_HINTS, _CAPABILITY) \
221 if (hints & _HINTS) \
222 addCapability(data, FcitxCapabilityFlag_##_CAPABILITY); \
223 else \
224 removeCapability(data, FcitxCapabilityFlag_##_CAPABILITY);
225
226 CHECK_HINTS(Qt::ImhHiddenText, Password)
227 CHECK_HINTS(Qt::ImhNoAutoUppercase, NoAutoUpperCase)
228 CHECK_HINTS(Qt::ImhPreferNumbers, Number)
229 CHECK_HINTS(Qt::ImhPreferUppercase, Uppercase)
230 CHECK_HINTS(Qt::ImhPreferLowercase, Lowercase)
231 CHECK_HINTS(Qt::ImhNoPredictiveText, NoSpellCheck)
232 CHECK_HINTS(Qt::ImhDigitsOnly, Digit)
233 CHECK_HINTS(Qt::ImhFormattedNumbersOnly, Number)
234 CHECK_HINTS(Qt::ImhUppercaseOnly, Uppercase)
235 CHECK_HINTS(Qt::ImhLowercaseOnly, Lowercase)
236 CHECK_HINTS(Qt::ImhDialableCharactersOnly, Dialable)
237 CHECK_HINTS(Qt::ImhEmailCharactersOnly, Email)
238 CHECK_HINTS(Qt::ImhUrlCharactersOnly, Url)
239 }
240
241 bool setSurrounding = false;
242 do {
243 if (!useSurroundingText_)
244 break;
245 if ((data.capability & FcitxCapabilityFlag_Password) ||
246 (data.capability & FcitxCapabilityFlag_Sensitive))
247 break;
248 QVariant var = input->inputMethodQuery(Qt::ImSurroundingText);
249 QVariant var1 = input->inputMethodQuery(Qt::ImCursorPosition);
250 QVariant var2 = input->inputMethodQuery(Qt::ImAnchorPosition);
251 if (!var.isValid() || !var1.isValid())
252 break;
253 QString text = var.toString();
254 /* we don't want to waste too much memory here */
255 #define SURROUNDING_THRESHOLD 4096
256 if (text.length() < SURROUNDING_THRESHOLD) {
257 if (checkUtf8(text.toUtf8())) {
258 addCapability(data, FcitxCapabilityFlag_SurroundingText);
259
260 int cursor = var1.toInt();
261 int anchor;
262 if (var2.isValid()) {
263 anchor = var2.toInt();
264 } else {
265 anchor = cursor;
266 }
267
268 // adjust it to real character size
269 #if QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)
270 QVector<unsigned int> tempUCS4 = text.leftRef(cursor).toUcs4();
271 #else
272 QVector<unsigned int> tempUCS4 = text.left(cursor).toUcs4();
273 #endif
274 cursor = tempUCS4.size();
275 #if QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)
276 tempUCS4 = text.leftRef(anchor).toUcs4();
277 #else
278 tempUCS4 = text.left(anchor).toUcs4();
279 #endif
280 anchor = tempUCS4.size();
281 if (data.surroundingText != text) {
282 data.surroundingText = text;
283 proxy->setSurroundingText(text, cursor, anchor);
284 } else {
285 if (data.surroundingAnchor != anchor ||
286 data.surroundingCursor != cursor)
287 proxy->setSurroundingTextPosition(cursor, anchor);
288 }
289 data.surroundingCursor = cursor;
290 data.surroundingAnchor = anchor;
291 setSurrounding = true;
292 }
293 }
294 if (!setSurrounding) {
295 data.surroundingAnchor = -1;
296 data.surroundingCursor = -1;
297 data.surroundingText = QString();
298 removeCapability(data, FcitxCapabilityFlag_SurroundingText);
299 }
300 } while (0);
301 }
302
303 void QFcitxInputContext::setFocusWidget(QWidget *object) {
304 Q_UNUSED(object);
305 FcitxQtInputContextProxy *proxy = validICByWindow(lastWindow_);
306 if (proxy) {
307 proxy->focusOut();
308 }
309
310 QWidget *window = qApp->focusWidget();
311 lastWindow_ = window;
312 if (!window) {
313 return;
314 }
315 proxy = validICByWindow(window);
316 if (proxy) {
317 cursorRectChanged();
318 proxy->focusIn();
319 } else {
320 createICData(window);
321 }
322 QInputContext::setFocusWidget(object);
323 }
324
325 void QFcitxInputContext::widgetDestroyed(QWidget *w) {
326 QInputContext::widgetDestroyed(w);
327
328 icMap_.erase(w);
329 }
330
331 void QFcitxInputContext::windowDestroyed(QObject *object) {
332 /* access QWindow is not possible here, so we use our own map to do so */
333 icMap_.erase(reinterpret_cast<QWidget *>(object));
334 // qDebug() << "Window Destroyed and we destroy IC correctly, horray!";
335 }
336
337 void QFcitxInputContext::cursorRectChanged() {
338 QWidget *inputWindow = qApp->focusWidget();
339 if (!inputWindow)
340 return;
341 FcitxQtInputContextProxy *proxy = validICByWindow(inputWindow);
342 if (!proxy)
343 return;
344
345 FcitxQtICData &data = *static_cast<FcitxQtICData *>(
346 proxy->property("icData").value<void *>());
347
348 QRect r = inputWindow->inputMethodQuery(Qt::ImMicroFocus).toRect();
349
350 auto point = inputWindow->mapToGlobal(r.topLeft());
351 QRect newRect(point, r.size());
352
353 if (data.rect != newRect) {
354 data.rect = newRect;
355 proxy->setCursorRect(newRect.x(), newRect.y(), newRect.width(),
356 newRect.height());
357 }
358 }
359
360 void QFcitxInputContext::createInputContextFinished(const QByteArray &uuid) {
361 auto proxy = qobject_cast<FcitxQtInputContextProxy *>(sender());
362 if (!proxy) {
363 return;
364 }
365 auto w =
366 reinterpret_cast<QWidget *>(proxy->property("wid").value<void *>());
367 FcitxQtICData *data =
368 static_cast<FcitxQtICData *>(proxy->property("icData").value<void *>());
369 data->rect = QRect();
370
371 if (proxy->isValid()) {
372 QWidget *window = qApp->focusWidget();
373 #ifdef ENABLE_X11
374 setFocusGroupForX11(uuid);
375 #else
376 Q_UNUSED(uuid);
377 #endif
378 if (window && window == w) {
379 cursorRectChanged();
380 proxy->focusIn();
381 }
382 }
383
384 quint64 flag = 0;
385 flag |= FcitxCapabilityFlag_Preedit;
386 flag |= FcitxCapabilityFlag_FormattedPreedit;
387 flag |= FcitxCapabilityFlag_ClientUnfocusCommit;
388 flag |= FcitxCapabilityFlag_GetIMInfoOnFocus;
389 flag |= FcitxCapabilityFlag_KeyEventOrderFix;
390 flag |= FcitxCapabilityFlag_ReportKeyRepeat;
391 useSurroundingText_ =
392 get_boolean_env("FCITX_QT_ENABLE_SURROUNDING_TEXT", true);
393 if (useSurroundingText_)
394 flag |= FcitxCapabilityFlag_SurroundingText;
395
396 addCapability(*data, flag, true);
397 }
398
399 void QFcitxInputContext::updateCapability(const FcitxQtICData &data) {
400 if (!data.proxy || !data.proxy->isValid())
401 return;
402
403 QDBusPendingReply<void> result = data.proxy->setCapability(data.capability);
404 }
405
406 void QFcitxInputContext::commitString(const QString &str) {
407 cursorPos_ = 0;
408 preeditList_.clear();
409 commitPreedit_.clear();
410 QWidget *input = qApp->focusWidget();
411 if (!input)
412 return;
413
414 QInputMethodEvent event;
415 event.setCommitString(str);
416 QCoreApplication::sendEvent(input, &event);
417 }
418
419 void QFcitxInputContext::updateFormattedPreedit(
420 const FcitxQtFormattedPreeditList &preeditList, int cursorPos) {
421 QWidget *input = qApp->focusWidget();
422 if (!input)
423 return;
424 if (cursorPos == cursorPos_ && preeditList == preeditList_)
425 return;
426 preeditList_ = preeditList;
427 cursorPos_ = cursorPos;
428 QString str, commitStr;
429 int pos = 0;
430 QList<QInputMethodEvent::Attribute> attrList;
431 Q_FOREACH (const FcitxQtFormattedPreedit &preedit, preeditList) {
432 str += preedit.string();
433 if (!(preedit.format() & FcitxTextFormatFlag_DontCommit))
434 commitStr += preedit.string();
435 QTextCharFormat format;
436 if (preedit.format() & FcitxTextFormatFlag_Underline) {
437 format.setUnderlineStyle(QTextCharFormat::DashUnderline);
438 }
439 if (preedit.format() & FcitxTextFormatFlag_Strike) {
440 format.setFontStrikeOut(true);
441 }
442 if (preedit.format() & FcitxTextFormatFlag_Bold) {
443 format.setFontWeight(QFont::Bold);
444 }
445 if (preedit.format() & FcitxTextFormatFlag_Italic) {
446 format.setFontItalic(true);
447 }
448 if (preedit.format() & FcitxTextFormatFlag_HighLight) {
449 QBrush brush;
450 QPalette palette;
451 palette = QApplication::palette();
452 format.setBackground(QBrush(
453 QColor(palette.color(QPalette::Active, QPalette::Highlight))));
454 format.setForeground(QBrush(QColor(
455 palette.color(QPalette::Active, QPalette::HighlightedText))));
456 }
457 attrList.append(
458 QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, pos,
459 preedit.string().length(), format));
460 pos += preedit.string().length();
461 }
462
463 QByteArray array = str.toUtf8();
464 array.truncate(cursorPos);
465 cursorPos = QString::fromUtf8(array).length();
466
467 attrList.append(QInputMethodEvent::Attribute(QInputMethodEvent::Cursor,
468 cursorPos, 1, 0));
469 preedit_ = str;
470 commitPreedit_ = commitStr;
471 QInputMethodEvent event(str, attrList);
472 QCoreApplication::sendEvent(input, &event);
473 update();
474 }
475
476 void QFcitxInputContext::deleteSurroundingText(int offset,
477 unsigned int _nchar) {
478 QWidget *input = qApp->focusWidget();
479 if (!input)
480 return;
481
482 QInputMethodEvent event;
483
484 FcitxQtInputContextProxy *proxy =
485 qobject_cast<FcitxQtInputContextProxy *>(sender());
486 if (!proxy) {
487 return;
488 }
489
490 FcitxQtICData *data =
491 static_cast<FcitxQtICData *>(proxy->property("icData").value<void *>());
492 QVector<unsigned int> ucsText = data->surroundingText.toUcs4();
493
494 int cursor = data->surroundingCursor;
495 // make nchar signed so we are safer
496 int nchar = _nchar;
497 // Qt's reconvert semantics is different from gtk's. It doesn't count the
498 // current
499 // selection. Discard selection from nchar.
500 if (data->surroundingAnchor < data->surroundingCursor) {
501 nchar -= data->surroundingCursor - data->surroundingAnchor;
502 offset += data->surroundingCursor - data->surroundingAnchor;
503 cursor = data->surroundingAnchor;
504 } else if (data->surroundingAnchor > data->surroundingCursor) {
505 nchar -= data->surroundingAnchor - data->surroundingCursor;
506 cursor = data->surroundingCursor;
507 }
508
509 // validates
510 if (nchar >= 0 && cursor + offset >= 0 &&
511 cursor + offset + nchar <= ucsText.size()) {
512 // order matters
513 QVector<unsigned int> replacedChars =
514 ucsText.mid(cursor + offset, nchar);
515 nchar = QString::fromUcs4(replacedChars.data(), replacedChars.size())
516 .size();
517
518 int start, len;
519 if (offset >= 0) {
520 start = cursor;
521 len = offset;
522 } else {
523 start = cursor + offset;
524 len = -offset;
525 }
526
527 QVector<unsigned int> prefixedChars = ucsText.mid(start, len);
528 offset = QString::fromUcs4(prefixedChars.data(), prefixedChars.size())
529 .size() *
530 (offset >= 0 ? 1 : -1);
531 event.setCommitString("", offset, nchar);
532 QCoreApplication::sendEvent(input, &event);
533 }
534 }
535
536 void QFcitxInputContext::forwardKey(unsigned int keyval, unsigned int state,
537 bool type) {
538 auto proxy = qobject_cast<FcitxQtInputContextProxy *>(sender());
539 if (!proxy) {
540 return;
541 }
542 FcitxQtICData &data = *static_cast<FcitxQtICData *>(
543 proxy->property("icData").value<void *>());
544 QWidget *input = qApp->focusWidget();
545 if (input != nullptr) {
546 key_filtered = true;
547 QKeyEvent *keyevent =
548 createKeyEvent(keyval, state, type, data.event.get());
549
550 QCoreApplication::sendEvent(input, keyevent);
551 delete keyevent;
552 key_filtered = false;
553 }
554 }
555
556 void QFcitxInputContext::serverSideFocusOut() {
557 if (lastWindow_ == qApp->focusWidget()) {
558 commitPreedit();
559 }
560 }
561
562 void QFcitxInputContext::createICData(QWidget *w) {
563 auto iter = icMap_.find(w);
564 if (iter == icMap_.end()) {
565 auto result =
566 icMap_.emplace(std::piecewise_construct, std::forward_as_tuple(w),
567 std::forward_as_tuple(watcher_));
568 iter = result.first;
569 auto &data = iter->second;
570
571 data.proxy->setDisplay("x11:");
572 data.proxy->setProperty("wid",
573 qVariantFromValue(static_cast<void *>(w)));
574 data.proxy->setProperty("icData",
575 qVariantFromValue(static_cast<void *>(&data)));
576 connect(data.proxy, SIGNAL(inputContextCreated(QByteArray)), this,
577 SLOT(createInputContextFinished(QByteArray)));
578 connect(data.proxy, SIGNAL(commitString(QString)), this,
579 SLOT(commitString(QString)));
580 connect(data.proxy,
581 SIGNAL(forwardKey(unsigned int, unsigned int, bool)), this,
582 SLOT(forwardKey(unsigned int, unsigned int, bool)));
583 connect(
584 data.proxy,
585 SIGNAL(updateFormattedPreedit(FcitxQtFormattedPreeditList, int)),
586 this,
587 SLOT(updateFormattedPreedit(FcitxQtFormattedPreeditList, int)));
588 connect(data.proxy, SIGNAL(deleteSurroundingText(int, uint)), this,
589 SLOT(deleteSurroundingText(int, uint)));
590 connect(data.proxy, SIGNAL(notifyFocusOut()), this,
591 SLOT(serverSideFocusOut()));
592 }
593 }
594
595 QKeyEvent *QFcitxInputContext::createKeyEvent(unsigned int keyval,
596 unsigned int state,
597 bool isRelease,
598 const QKeyEvent *event) {
599 QKeyEvent *newEvent = nullptr;
600 if (event && event->nativeVirtualKey() == keyval &&
601 event->nativeModifiers() == state &&
602 isRelease == (event->type() == QEvent::KeyRelease)) {
603 newEvent = new QKeyEvent(*event);
604 } else {
605 Qt::KeyboardModifiers qstate = Qt::NoModifier;
606
607 int count = 1;
608 if (state & FcitxKeyState_Alt) {
609 qstate |= Qt::AltModifier;
610 count++;
611 }
612
613 if (state & FcitxKeyState_Shift) {
614 qstate |= Qt::ShiftModifier;
615 count++;
616 }
617
618 if (state & FcitxKeyState_Ctrl) {
619 qstate |= Qt::ControlModifier;
620 count++;
621 }
622
623 auto unicode = xkb_keysym_to_utf32(keyval);
624 QString text;
625 if (unicode) {
626 text = QString::fromUcs4(&unicode, 1);
627 }
628
629 int key = keysymToQtKey(keyval, text);
630
631 newEvent = QKeyEvent::createExtendedKeyEvent(
632 isRelease ? (QEvent::KeyRelease) : (QEvent::KeyPress), key, qstate,
633 0, keyval, state, text, false, count);
634 }
635
636 return newEvent;
637 }
638
639 bool QFcitxInputContext::filterEvent(const QEvent *event) {
640 do {
641 if (event->type() != QEvent::KeyPress &&
642 event->type() != QEvent::KeyRelease) {
643 break;
644 }
645
646 const QKeyEvent *keyEvent = static_cast<const QKeyEvent *>(event);
647 quint32 keyval = keyEvent->nativeVirtualKey();
648 quint32 keycode = keyEvent->nativeScanCode();
649 quint32 state = keyEvent->nativeModifiers();
650 bool isRelease = keyEvent->type() == QEvent::KeyRelease;
651
652 if (key_filtered) {
653 break;
654 }
655
656 QWidget *input = qApp->focusWidget();
657
658 if (!input) {
659 break;
660 }
661
662 FcitxQtInputContextProxy *proxy = validICByWindow(input);
663
664 if (!proxy) {
665 if (filterEventFallback(keyval, keycode, state, isRelease)) {
666 return true;
667 } else {
668 break;
669 }
670 }
671
672 proxy->focusIn();
673 update();
674
675 auto stateToFcitx = state;
676 if (keyEvent->isAutoRepeat()) {
677 // KeyState::Repeat
678 stateToFcitx |= (1u << 31);
679 }
680 auto reply =
681 proxy->processKeyEvent(keyval, keycode, stateToFcitx, isRelease,
682 QDateTime::currentDateTime().toTime_t());
683
684 #if QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)
685 if (Q_UNLIKELY(syncMode_)) {
686 #else
687 if (syncMode_) {
688 #endif
689 reply.waitForFinished();
690
691 if (reply.isError() || !reply.value()) {
692 if (filterEventFallback(keyval, keycode, state, isRelease)) {
693 return true;
694 } else {
695 break;
696 }
697 } else {
698 update();
699 return true;
700 }
701 } else {
702 ProcessKeyWatcher *watcher = new ProcessKeyWatcher(
703 *keyEvent, qApp->focusWidget(), reply, proxy);
704 connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher *)), this,
705 SLOT(processKeyEventFinished(QDBusPendingCallWatcher *)));
706 return true;
707 }
708 } while (0);
709 return QInputContext::filterEvent(event);
710 }
711
712 void QFcitxInputContext::processKeyEventFinished(QDBusPendingCallWatcher *w) {
713 ProcessKeyWatcher *watcher = static_cast<ProcessKeyWatcher *>(w);
714 QDBusPendingReply<bool> result(*watcher);
715 bool filtered = false;
716
717 QWidget *window = watcher->window();
718 // if window is already destroyed, we can only throw this event away.
719 if (!window) {
720 delete watcher;
721 return;
722 }
723
724 QKeyEvent &keyEvent = watcher->keyEvent();
725
726 // use same variable name as in QXcbKeyboard::handleKeyEvent
727 QEvent::Type type = keyEvent.type();
728 quint32 code = keyEvent.nativeScanCode();
729 quint32 sym = keyEvent.nativeVirtualKey();
730 quint32 state = keyEvent.nativeModifiers();
731 QString string = keyEvent.text();
732
733 if (result.isError() || !result.value()) {
734 filtered =
735 filterEventFallback(sym, code, state, type == QEvent::KeyRelease);
736 } else {
737 filtered = true;
738 }
739
740 if (!watcher->isError()) {
741 update();
742 }
743
744 if (!filtered) {
745 key_filtered = true;
746 QCoreApplication::sendEvent(window, &keyEvent);
747 key_filtered = false;
748 } else {
749 auto proxy =
750 qobject_cast<FcitxQtInputContextProxy *>(watcher->parent());
751 if (proxy) {
752 FcitxQtICData &data = *static_cast<FcitxQtICData *>(
753 proxy->property("icData").value<void *>());
754 data.event = std::make_unique<QKeyEvent>(keyEvent);
755 }
756 }
757
758 delete watcher;
759 }
760
761 bool QFcitxInputContext::filterEventFallback(unsigned int keyval,
762 unsigned int keycode,
763 unsigned int state,
764 bool isRelease) {
765 Q_UNUSED(keycode);
766 if (processCompose(keyval, state, isRelease)) {
767 return true;
768 }
769 return false;
770 }
771
772 FcitxQtInputContextProxy *QFcitxInputContext::validIC() {
773 if (icMap_.empty()) {
774 return nullptr;
775 }
776 QWidget *window = qApp->focusWidget();
777 return validICByWindow(window);
778 }
779
780 FcitxQtInputContextProxy *QFcitxInputContext::validICByWindow(QWidget *w) {
781 if (!w) {
782 return nullptr;
783 }
784
785 if (icMap_.empty()) {
786 return nullptr;
787 }
788 auto iter = icMap_.find(w);
789 if (iter == icMap_.end())
790 return nullptr;
791 auto &data = iter->second;
792 if (!data.proxy || !data.proxy->isValid()) {
793 return nullptr;
794 }
795 return data.proxy;
796 }
797
798 bool QFcitxInputContext::processCompose(unsigned int keyval, unsigned int state,
799 bool isRelease) {
800 Q_UNUSED(state);
801
802 if (!xkbComposeTable_ || isRelease)
803 return false;
804
805 struct xkb_compose_state *xkbComposeState = xkbComposeState_.data();
806
807 enum xkb_compose_feed_result result =
808 xkb_compose_state_feed(xkbComposeState, keyval);
809 if (result == XKB_COMPOSE_FEED_IGNORED) {
810 return false;
811 }
812
813 enum xkb_compose_status status =
814 xkb_compose_state_get_status(xkbComposeState);
815 if (status == XKB_COMPOSE_NOTHING) {
816 return 0;
817 } else if (status == XKB_COMPOSE_COMPOSED) {
818 std::array<char, 256> buffer;
819 int length = xkb_compose_state_get_utf8(xkbComposeState, buffer.data(),
820 buffer.size());
821 xkb_compose_state_reset(xkbComposeState);
822 if (length != 0) {
823 commitString(QString::fromUtf8(buffer.data(), length));
824 }
825 } else if (status == XKB_COMPOSE_CANCELLED) {
826 xkb_compose_state_reset(xkbComposeState);
827 }
828
829 return true;
830 }
831
832 QString QFcitxInputContext::identifierName() { return "fcitx5"; }
833
834 QString QFcitxInputContext::language() { return ""; }
835 } // namespace fcitx
836
837 // kate: indent-mode cstyle; space-indent on; indent-width 0;