Debian Codegraph @

qt6/widgetsaddons/fcitxqtkeysequencewidget.cpp

raw
1 /*
2 * SPDX-FileCopyrightText: 2013~2020 CSSlayer <[email protected]>
3 *
4 * This library is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; see the file COPYING. If not,
16 * see <http://www.gnu.org/licenses/>.
17 */
18
19 /* this is forked from kdelibs/kdeui/kkeysequencewidget.cpp */
20
21 /*
22 Original Copyright header
23 SPDX-FileCopyrightText: 1998 Mark Donohoe <[email protected]>
24 SPDX-FileCopyrightText: 2001 Ellis Whitehead <[email protected]>
25 SPDX-FileCopyrightText: 2007 Andreas Hartmetz <[email protected]>
26
27 This library is free software; you can redistribute it and/or
28 modify it under the terms of the GNU Library General Public
29 License as published by the Free Software Foundation; either
30 version 2 of the License, or (at your option) any later version.
31
32 This library is distributed in the hope that it will be useful,
33 but WITHOUT ANY WARRANTY; without even the implied warranty of
34 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
35 Library General Public License for more details.
36
37 You should have received a copy of the GNU Library General Public License
38 along with this library; see the file COPYING.LIB. If not, write to
39 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
40 Boston, MA 02110-1301, USA.
41 */
42
43 #include "fcitxqtkeysequencewidget.h"
44 #include "fcitxqtkeysequencewidget_p.h"
45
46 #include <QApplication>
47 #include <QHBoxLayout>
48 #include <QHash>
49 #include <QKeyEvent>
50 #include <QLoggingCategory>
51 #include <QMessageBox>
52 #include <QTimer>
53 #include <QToolButton>
54 #include <fcitx-utils/i18n.h>
55 #include <fcitx-utils/key.h>
56
57 Q_LOGGING_CATEGORY(fcitx5qtKeysequenceWidget, "fcitx5.qt.keysequencewidget")
58
59 namespace fcitx {
60
61 namespace {
62
63 bool isX11LikePlatform() {
64 return QGuiApplication::platformName() == "xcb" ||
65 QGuiApplication::platformName().startsWith("wayland");
66 }
67
68 } // namespace
69
70 class FcitxQtKeySequenceWidgetPrivate {
71 public:
72 FcitxQtKeySequenceWidgetPrivate(FcitxQtKeySequenceWidget *q);
73
74 void init();
75
76 static bool isOkWhenModifierless(int keyQt);
77
78 void updateShortcutDisplay();
79 void startRecording();
80
81 void controlModifierlessTimout() {
82 if (keySequence_.size() != 0 && !modifierKeys_) {
83 // No modifier key pressed currently. Start the timout
84 modifierlessTimeout_.start(600);
85 } else {
86 // A modifier is pressed. Stop the timeout
87 modifierlessTimeout_.stop();
88 }
89 }
90
91 void cancelRecording() {
92 keySequence_ = oldKeySequence_;
93 doneRecording();
94 }
95
96 // private slot
97 void doneRecording();
98
99 // members
100 FcitxQtKeySequenceWidget *const q;
101 QHBoxLayout *layout_ = nullptr;
102 FcitxQtKeySequenceButton *keyButton_ = nullptr;
103 QToolButton *clearButton_ = nullptr;
104 QAction *keyCodeModeAction_ = nullptr;
105
106 QList<Key> keySequence_;
107 QList<Key> oldKeySequence_;
108 QTimer modifierlessTimeout_;
109 bool allowModifierless_ = false;
110 KeyStates modifierKeys_;
111 unsigned int qtModifierKeys_ = 0;
112 bool isRecording_ = false;
113 bool multiKeyShortcutsAllowed_ = false;
114 bool allowModifierOnly_ = false;
115 bool modifierAllowed_ = true;
116 bool keycodeAllowed_ = true;
117 };
118
119 FcitxQtKeySequenceWidgetPrivate::FcitxQtKeySequenceWidgetPrivate(
120 FcitxQtKeySequenceWidget *q)
121 : q(q) {}
122
123 FcitxQtKeySequenceWidget::FcitxQtKeySequenceWidget(QWidget *parent)
124 : QWidget(parent), d(new FcitxQtKeySequenceWidgetPrivate(this)) {
125 d->init();
126 setFocusProxy(d->keyButton_);
127 connect(d->keyButton_, &QPushButton::clicked, this,
128 &FcitxQtKeySequenceWidget::captureKeySequence);
129 connect(d->clearButton_, &QPushButton::clicked, this,
130 &FcitxQtKeySequenceWidget::clearKeySequence);
131 connect(&d->modifierlessTimeout_, &QTimer::timeout, this,
132 [this]() { d->doneRecording(); });
133 d->updateShortcutDisplay();
134 }
135
136 void FcitxQtKeySequenceWidgetPrivate::init() {
137 layout_ = new QHBoxLayout(q);
138 layout_->setContentsMargins(0, 0, 0, 0);
139
140 keyButton_ = new FcitxQtKeySequenceButton(this, q);
141 keyButton_->setFocusPolicy(Qt::StrongFocus);
142 keyButton_->setIcon(QIcon::fromTheme("configure"));
143 layout_->addWidget(keyButton_);
144
145 clearButton_ = new QToolButton(q);
146 layout_->addWidget(clearButton_);
147
148 keyCodeModeAction_ = new QAction(_("Key code mode"));
149 keyCodeModeAction_->setCheckable(true);
150 keyCodeModeAction_->setEnabled(isX11LikePlatform());
151 q->setContextMenuPolicy(Qt::ActionsContextMenu);
152 q->addAction(keyCodeModeAction_);
153
154 if (qApp->isLeftToRight())
155 clearButton_->setIcon(QIcon::fromTheme("edit-clear-locationbar-rtl"));
156 else
157 clearButton_->setIcon(QIcon::fromTheme("edit-clear-locationbar-ltr"));
158
159 q->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
160 }
161
162 FcitxQtKeySequenceWidget::~FcitxQtKeySequenceWidget() { delete d; }
163
164 bool FcitxQtKeySequenceWidget::multiKeyShortcutsAllowed() const {
165 return d->multiKeyShortcutsAllowed_;
166 }
167
168 void FcitxQtKeySequenceWidget::setMultiKeyShortcutsAllowed(bool allowed) {
169 d->multiKeyShortcutsAllowed_ = allowed;
170 }
171
172 bool FcitxQtKeySequenceWidget::isModifierAllowed() const {
173 return d->modifierAllowed_;
174 }
175
176 void FcitxQtKeySequenceWidget::setModifierAllowed(bool allowed) {
177 d->modifierAllowed_ = allowed;
178 }
179
180 bool FcitxQtKeySequenceWidget::isKeycodeAllowed() const {
181 return d->keycodeAllowed_;
182 }
183
184 void FcitxQtKeySequenceWidget::setKeycodeAllowed(bool allowed) {
185 if (d->keycodeAllowed_ == allowed) {
186 return;
187 }
188 d->keycodeAllowed_ = allowed;
189 if (allowed) {
190 d->keyCodeModeAction_->setChecked(false);
191 addAction(d->keyCodeModeAction_);
192 } else {
193 removeAction(d->keyCodeModeAction_);
194 }
195 }
196
197 void FcitxQtKeySequenceWidget::setModifierlessAllowed(bool allow) {
198 d->allowModifierless_ = allow;
199 }
200
201 bool FcitxQtKeySequenceWidget::isModifierlessAllowed() {
202 return d->allowModifierless_;
203 }
204
205 bool FcitxQtKeySequenceWidget::isModifierOnlyAllowed() {
206 return d->allowModifierOnly_;
207 }
208
209 bool FcitxQtKeySequenceWidget::isModifierlessAllowed() const {
210 return d->allowModifierless_;
211 }
212
213 bool FcitxQtKeySequenceWidget::isModifierOnlyAllowed() const {
214 return d->allowModifierOnly_;
215 }
216
217 void FcitxQtKeySequenceWidget::setModifierOnlyAllowed(bool allow) {
218 d->allowModifierOnly_ = allow;
219 }
220
221 void FcitxQtKeySequenceWidget::setClearButtonShown(bool show) {
222 d->clearButton_->setVisible(show);
223 }
224
225 bool FcitxQtKeySequenceWidget::isClearButtonVisible() const {
226 return d->clearButton_->isVisible();
227 }
228
229 // slot
230 void FcitxQtKeySequenceWidget::captureKeySequence() { d->startRecording(); }
231
232 const QList<Key> &FcitxQtKeySequenceWidget::keySequence() const {
233 return d->keySequence_;
234 }
235
236 // slot
237 void FcitxQtKeySequenceWidget::setKeySequence(const QList<Key> &seq) {
238 // oldKeySequence holds the key sequence before recording started, if
239 // setKeySequence()
240 // is called while not recording then set oldKeySequence to the existing
241 // sequence so
242 // that the keySequenceChanged() signal is emitted if the new and previous
243 // key
244 // sequences are different
245 if (!d->isRecording_) {
246 d->oldKeySequence_ = d->keySequence_;
247 }
248
249 d->keySequence_ = QList<Key>();
250 for (auto key : seq) {
251 d->keySequence_ << key;
252 }
253 d->doneRecording();
254 }
255
256 // slot
257 void FcitxQtKeySequenceWidget::clearKeySequence() {
258 setKeySequence(QList<Key>());
259 }
260
261 void FcitxQtKeySequenceWidgetPrivate::startRecording() {
262 modifierKeys_ = 0;
263 oldKeySequence_ = keySequence_;
264 keySequence_ = QList<Key>();
265 isRecording_ = true;
266 keyButton_->grabKeyboard();
267
268 if (!QWidget::keyboardGrabber()) {
269 qWarning() << "Failed to grab the keyboard! Most likely qt's nograb "
270 "option is active";
271 }
272
273 keyButton_->setDown(true);
274 updateShortcutDisplay();
275 }
276
277 void FcitxQtKeySequenceWidgetPrivate::doneRecording() {
278 modifierlessTimeout_.stop();
279 isRecording_ = false;
280 keyButton_->releaseKeyboard();
281 keyButton_->setDown(false);
282
283 if (keySequence_ == oldKeySequence_ && !allowModifierOnly_) {
284 // The sequence hasn't changed
285 updateShortcutDisplay();
286 return;
287 }
288
289 Q_EMIT q->keySequenceChanged(keySequence_);
290
291 updateShortcutDisplay();
292 }
293
294 void FcitxQtKeySequenceWidgetPrivate::updateShortcutDisplay() {
295 QString s = QString::fromUtf8(
296 Key::keyListToString(keySequence_, KeyStringFormat::Localized).c_str());
297 s.replace('&', QLatin1String("&&"));
298
299 if (isRecording_) {
300 if (modifierKeys_) {
301 if (!s.isEmpty())
302 s.append(",");
303 if (modifierKeys_ & KeyState::Super)
304 s += "Super+";
305 if (modifierKeys_ & KeyState::Ctrl)
306 s += "Control+";
307 if (modifierKeys_ & KeyState::Alt)
308 s += "Alt+";
309 if (modifierKeys_ & KeyState::Shift)
310 s += "Shift+";
311 if (modifierKeys_ & KeyState::Hyper)
312 s += "Hyper+";
313
314 } else if (keySequence_.size() == 0) {
315 s = "...";
316 }
317 // make it clear that input is still going on
318 s.append(" ...");
319 }
320
321 if (s.isEmpty()) {
322 s = _("Empty");
323 }
324
325 s.prepend(' ');
326 s.append(' ');
327 keyButton_->setText(s);
328 }
329
330 FcitxQtKeySequenceButton::~FcitxQtKeySequenceButton() {}
331
332 // prevent Qt from special casing Tab and Backtab
333 bool FcitxQtKeySequenceButton::event(QEvent *e) {
334 if (d->isRecording_ && e->type() == QEvent::KeyPress) {
335 keyPressEvent(static_cast<QKeyEvent *>(e));
336 return true;
337 }
338
339 // The shortcut 'alt+c' ( or any other dialog local action shortcut )
340 // ended the recording and triggered the action associated with the
341 // action. In case of 'alt+c' ending the dialog. It seems that those
342 // ShortcutOverride events get sent even if grabKeyboard() is active.
343 if (d->isRecording_ && e->type() == QEvent::ShortcutOverride) {
344 e->accept();
345 return true;
346 }
347
348 return QPushButton::event(e);
349 }
350
351 void FcitxQtKeySequenceButton::keyPressEvent(QKeyEvent *e) {
352 int keyQt = e->key();
353 if (keyQt == -1) {
354 // Qt sometimes returns garbage keycodes, I observed -1, if it doesn't
355 // know a key. We cannot do anything useful with those (several keys
356 // have -1, indistinguishable) and QKeySequence.toString() will also
357 // yield a garbage string.
358 QMessageBox::warning(
359 this, _("The key you just pressed is not supported by Qt."),
360 _("Unsupported Key"));
361 return d->cancelRecording();
362 }
363
364 // Same as Key::normalize();
365 unsigned int newQtModifiers =
366 e->modifiers() & (Qt::META | Qt::ALT | Qt::CTRL | Qt::SHIFT);
367 KeyStates newModifiers;
368 if (isX11LikePlatform()) {
369 newModifiers = KeyStates(e->nativeModifiers()) &
370 KeyStates{KeyState::Ctrl_Alt_Shift, KeyState::Hyper,
371 KeyState::Super};
372 newModifiers |=
373 Key::keySymToStates(static_cast<KeySym>(e->nativeVirtualKey()));
374 } else {
375 if (newQtModifiers & Qt::META) {
376 newModifiers |= KeyState::Super;
377 }
378 if (newQtModifiers & Qt::ALT) {
379 newModifiers |= KeyState::Alt;
380 }
381 if (newQtModifiers & Qt::CTRL) {
382 newModifiers |= KeyState::Ctrl;
383 }
384 if (newQtModifiers & Qt::SHIFT) {
385 newModifiers |= KeyState::Shift;
386 }
387 }
388
389 // don't have the return or space key appear as first key of the sequence
390 // when they
391 // were pressed to start editing - catch and them and imitate their effect
392 if (!d->isRecording_ &&
393 ((keyQt == Qt::Key_Return || keyQt == Qt::Key_Space))) {
394 d->startRecording();
395 d->modifierKeys_ = newModifiers;
396 d->qtModifierKeys_ = newQtModifiers;
397 d->updateShortcutDisplay();
398 return;
399 }
400
401 // We get events even if recording isn't active.
402 if (!d->isRecording_)
403 return QPushButton::keyPressEvent(e);
404
405 e->accept();
406 d->modifierKeys_ = newModifiers;
407 d->qtModifierKeys_ = newQtModifiers;
408
409 switch (keyQt) {
410 case Qt::Key_AltGr: // or else we get unicode salad
411 return;
412 case Qt::Key_Shift:
413 case Qt::Key_Control:
414 case Qt::Key_Alt:
415 case Qt::Key_Super_L:
416 case Qt::Key_Super_R:
417 case Qt::Key_Hyper_L:
418 case Qt::Key_Hyper_R:
419 case Qt::Key_Meta:
420 case Qt::Key_Menu: // unused (yes, but why?)
421 d->controlModifierlessTimout();
422 d->updateShortcutDisplay();
423 break;
424 default:
425 // We now have a valid key press.
426 if (keyQt) {
427 if ((keyQt == Qt::Key_Backtab) &&
428 d->modifierKeys_.test(KeyState::Shift)) {
429 keyQt = Qt::Key_Tab | d->qtModifierKeys_;
430 } else {
431 keyQt |= d->qtModifierKeys_;
432 }
433
434 Key key;
435 if (d->keyCodeModeAction_->isChecked()) {
436 key = Key::fromKeyCode(e->nativeScanCode(), d->modifierKeys_);
437 } else {
438 if (isX11LikePlatform()) {
439 key = Key(static_cast<KeySym>(e->nativeVirtualKey()),
440 KeyStates(e->nativeModifiers()))
441 .normalize();
442 } else {
443 qCWarning(fcitx5qtKeysequenceWidget)
444 << "Unsupported platform";
445 }
446 }
447
448 // Check the first key.
449 if (d->keySequence_.size() == 0) {
450 if (!d->allowModifierless_ && key.states() == 0) {
451 return;
452 }
453 if (!d->modifierAllowed_ && key.states() != 0) {
454 return;
455 }
456 }
457
458 if (key.isValid()) {
459 d->keySequence_ << key;
460 }
461
462 if ((!d->multiKeyShortcutsAllowed_) ||
463 (d->keySequence_.size() >= 4)) {
464 d->doneRecording();
465 return;
466 }
467 d->controlModifierlessTimout();
468 d->updateShortcutDisplay();
469 }
470 }
471 }
472
473 void FcitxQtKeySequenceButton::keyReleaseEvent(QKeyEvent *e) {
474 if (e->key() == -1) {
475 // ignore garbage, see keyPressEvent()
476 return;
477 }
478
479 if (!d->isRecording_)
480 return QPushButton::keyReleaseEvent(e);
481
482 e->accept();
483
484 if (!d->multiKeyShortcutsAllowed_ && d->allowModifierOnly_ &&
485 (e->key() == Qt::Key_Shift || e->key() == Qt::Key_Control ||
486 e->key() == Qt::Key_Meta || e->key() == Qt::Key_Alt)) {
487
488 Key key;
489 if (isX11LikePlatform()) {
490 if (d->keyCodeModeAction_->isChecked()) {
491 key = Key::fromKeyCode(e->nativeScanCode(), key.states());
492 } else {
493 key = Key(static_cast<KeySym>(e->nativeVirtualKey()),
494 KeyStates(e->nativeModifiers()))
495 .normalize();
496 }
497 d->keySequence_ = QList<Key>({key});
498 }
499 d->doneRecording();
500 return;
501 }
502
503 unsigned int newQtModifiers =
504 e->modifiers() & (Qt::META | Qt::ALT | Qt::CTRL | Qt::SHIFT);
505 KeyStates newModifiers;
506 if (isX11LikePlatform()) {
507 newModifiers = KeyStates(e->nativeModifiers()) &
508 KeyStates{KeyState::Ctrl_Alt_Shift, KeyState::Hyper,
509 KeyState::Super};
510 newModifiers &=
511 ~Key::keySymToStates(static_cast<KeySym>(e->nativeVirtualKey()));
512 } else {
513 if (newQtModifiers & Qt::META) {
514 newModifiers |= KeyState::Super;
515 }
516 if (newQtModifiers & Qt::ALT) {
517 newModifiers |= KeyState::Alt;
518 }
519 if (newQtModifiers & Qt::CTRL) {
520 newModifiers |= KeyState::Ctrl;
521 }
522 if (newQtModifiers & Qt::SHIFT) {
523 newModifiers |= KeyState::Shift;
524 }
525 }
526
527 // if a modifier that belongs to the shortcut was released...
528 if ((newModifiers & d->modifierKeys_) < d->modifierKeys_) {
529 d->modifierKeys_ = newModifiers;
530 d->controlModifierlessTimout();
531 d->updateShortcutDisplay();
532 }
533 }
534
535 // static
536 bool FcitxQtKeySequenceWidgetPrivate::isOkWhenModifierless(int keyQt) {
537 // this whole function is a hack, but especially the first line of code
538 if (QKeySequence(keyQt).toString().length() == 1)
539 return false;
540
541 switch (keyQt) {
542 case Qt::Key_Return:
543 case Qt::Key_Space:
544 case Qt::Key_Tab:
545 case Qt::Key_Backtab: // does this ever happen?
546 case Qt::Key_Backspace:
547 case Qt::Key_Delete:
548 return false;
549 default:
550 return true;
551 }
552 }
553 } // namespace fcitx
554
555 #include "moc_fcitxqtkeysequencewidget.cpp"