Debian Codegraph @

src/Gui/ShortcutManager.cpp

raw
1 /****************************************************************************
2 * Copyright (c) 2022 Zheng Lei (realthunder) <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ****************************************************************************/
22
23 #include <limits>
24 #include <QShortcutEvent>
25 #include <QApplication>
26
27 #include <boost/algorithm/string/predicate.hpp>
28
29 #include <Base/Console.h>
30 #include <Base/Tools.h>
31 #include "ShortcutManager.h"
32 #include "Command.h"
33 #include "Window.h"
34 #include "Action.h"
35
36 using namespace Gui;
37
38 ShortcutManager::ShortcutManager()
39 {
40 hShortcuts = WindowParameter::getDefaultParameter()->GetGroup("Shortcut");
41 hShortcuts->Attach(this);
42 hPriorities = hShortcuts->GetGroup("Priorities");
43 hPriorities->Attach(this);
44 hSetting = hShortcuts->GetGroup("Settings");
45 hSetting->Attach(this);
46 timeout = hSetting->GetInt("ShortcutTimeout", 300);
47 timer.setSingleShot(true);
48
49 QObject::connect(&timer, &QTimer::timeout, [this]() { onTimer(); });
50
51 topPriority = 0;
52 for (const auto& v : hPriorities->GetIntMap()) {
53 priorities[v.first] = v.second;
54 if (topPriority < v.second) {
55 topPriority = v.second;
56 }
57 }
58 if (topPriority == 0) {
59 topPriority = 100;
60 }
61
62 QApplication::instance()->installEventFilter(this);
63 }
64
65 ShortcutManager::~ShortcutManager()
66 {
67 hShortcuts->Detach(this);
68 hSetting->Detach(this);
69 hPriorities->Detach(this);
70 }
71
72 static ShortcutManager* Instance;
73 ShortcutManager* ShortcutManager::instance()
74 {
75 if (!Instance) {
76 Instance = new ShortcutManager;
77 }
78 return Instance;
79 }
80
81 void ShortcutManager::destroy()
82 {
83 delete Instance;
84 Instance = nullptr;
85 }
86
87 void ShortcutManager::OnChange(Base::Subject<const char*>& src, const char* reason)
88 {
89 if (hSetting == &src) {
90 if (boost::equals(reason, "ShortcutTimeout")) {
91 timeout = hSetting->GetInt("ShortcutTimeout");
92 }
93 return;
94 }
95
96 if (busy) {
97 return;
98 }
99
100 if (hPriorities == &src) {
101 int p = hPriorities->GetInt(reason, 0);
102 if (p == 0) {
103 priorities.erase(reason);
104 }
105 else {
106 priorities[reason] = p;
107 }
108 if (topPriority < p) {
109 topPriority = p;
110 }
111 priorityChanged(reason, p);
112 return;
113 }
114
115 Base::StateLocker lock(busy);
116 auto cmd = Application::Instance->commandManager().getCommandByName(reason);
117 if (cmd) {
118 auto accel = cmd->getAccel();
119 if (!accel) {
120 accel = "";
121 }
122 QKeySequence oldShortcut = cmd->getShortcut();
123 QKeySequence newShortcut = getShortcut(reason, accel);
124 if (oldShortcut != newShortcut) {
125 cmd->setShortcut(newShortcut.toString());
126 shortcutChanged(reason, oldShortcut);
127 }
128 }
129 }
130
131 void ShortcutManager::reset(const char* cmd)
132 {
133 if (!Base::Tools::isNullOrEmpty(cmd)) {
134 QKeySequence oldShortcut = getShortcut(cmd);
135 hShortcuts->RemoveASCII(cmd);
136 if (oldShortcut != getShortcut(cmd)) {
137 shortcutChanged(cmd, oldShortcut);
138 }
139
140 int oldPriority = getPriority(cmd);
141 hPriorities->RemoveInt(cmd);
142 if (oldPriority != getPriority(cmd)) {
143 priorityChanged(cmd, oldPriority);
144 }
145 }
146 }
147
148 void ShortcutManager::resetAll()
149 {
150 {
151 Base::StateLocker lock(busy);
152 hShortcuts->Clear();
153 hPriorities->Clear();
154 for (auto cmd : Application::Instance->commandManager().getAllCommands()) {
155 if (cmd->getAction()) {
156 auto accel = cmd->getAccel();
157 if (!accel) {
158 accel = "";
159 }
160 cmd->setShortcut(getShortcut(nullptr, accel));
161 }
162 }
163 }
164 shortcutChanged("", QKeySequence());
165 priorityChanged("", 0);
166 }
167
168 QString ShortcutManager::getShortcut(const char* cmdName, const char* accel)
169 {
170 if (!accel) {
171 if (auto cmd = Application::Instance->commandManager().getCommandByName(cmdName)) {
172 accel = cmd->getAccel();
173 if (!accel) {
174 accel = "";
175 }
176 }
177 }
178 QString shortcut;
179 if (cmdName) {
180 shortcut = QString::fromLatin1(hShortcuts->GetASCII(cmdName, accel).c_str());
181 }
182 else {
183 shortcut = QString::fromLatin1(accel);
184 }
185 return QKeySequence(shortcut).toString(QKeySequence::NativeText);
186 }
187
188 void ShortcutManager::setShortcut(const char* cmdName, const char* accel)
189 {
190 if (!Base::Tools::isNullOrEmpty(cmdName)) {
191 setTopPriority(cmdName);
192 if (!accel) {
193 accel = "";
194 }
195 if (auto cmd = Application::Instance->commandManager().getCommandByName(cmdName)) {
196 auto defaultAccel = cmd->getAccel();
197 if (!defaultAccel) {
198 defaultAccel = "";
199 }
200 if (QKeySequence(QString::fromLatin1(accel))
201 == QKeySequence(QString::fromLatin1(defaultAccel))) {
202 hShortcuts->RemoveASCII(cmdName);
203 return;
204 }
205 }
206 hShortcuts->SetASCII(cmdName, accel);
207 }
208 }
209
210 bool ShortcutManager::checkShortcut(QObject* o, const QKeySequence& key)
211 {
212 auto focus = QApplication::focusWidget();
213 if (!focus) {
214 return false;
215 }
216 auto action = qobject_cast<QAction*>(o);
217 if (!action) {
218 return false;
219 }
220
221 const auto& index = actionMap.get<1>();
222 auto iter = index.lower_bound(ActionKey(key));
223 if (iter == index.end()) {
224 return false;
225 }
226
227 // disable and enqueue the action in order to try other alternativeslll
228 action->setEnabled(false);
229 pendingActions.emplace_back(action, key.count(), 0);
230
231 // check for potential partial match, i.e. longer key sequences
232 bool flush = true;
233 bool found = false;
234 for (auto it = iter; it != index.end(); ++it) {
235 if (key.matches(it->key.shortcut) == QKeySequence::NoMatch) {
236 break;
237 }
238 if (action == it->action) {
239 // There maybe more than one action with the exact same shortcut.
240 // However, we only disable and enqueue the triggered action.
241 // Because, QAction::isEnabled() does not check if the action is
242 // active under its current ShortcutContext. We would have to check
243 // its parent widgets visibility which may or may not be reliable.
244 // Instead, we rely on QEvent::Shortcut to be sure to enqueue only
245 // active shortcuts. We'll fake the current key sequence below,
246 // which will trigger all possible matches one by one.
247 pendingActions.back().priority = getPriority(it->key.name);
248 found = true;
249 }
250 else if (it->action && it->action->isEnabled()) {
251 flush = false;
252 if (found) {
253 break;
254 }
255 }
256 }
257
258 if (flush) {
259 // We'll flush now because there is no potential match with further
260 // keystrokes, so no need to wait for timer.
261 lastFocus = nullptr;
262 onTimer();
263 return true;
264 }
265
266 lastFocus = focus;
267 pendingSequence = key;
268
269 // Qt's shortcut state machine favors shortest match (which is ridiculous,
270 // unless I'm mistaken?). We'll do longest match. We've disabled all
271 // shortcuts that can match the current key sequence. Now replay the sequence
272 // and wait for the next keystroke.
273 for (int i = 0; i < key.count(); ++i) {
274 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
275 int k = key[i];
276 #else
277 int k = key[i].key();
278 #endif
279 Qt::KeyboardModifiers modifiers;
280 if ((k & Qt::SHIFT) == Qt::SHIFT) {
281 modifiers |= Qt::ShiftModifier;
282 }
283 if ((k & Qt::CTRL) == Qt::CTRL) {
284 modifiers |= Qt::ControlModifier;
285 }
286 if ((k & Qt::ALT) == Qt::ALT) {
287 modifiers |= Qt::AltModifier;
288 }
289 if ((k & Qt::META) == Qt::META) {
290 modifiers |= Qt::MetaModifier;
291 }
292 k &= ~(Qt::SHIFT | Qt::CTRL | Qt::ALT | Qt::META);
293 QKeyEvent* kev = new QKeyEvent(QEvent::KeyPress, k, modifiers, 0, 0, 0);
294 QApplication::postEvent(focus, kev);
295 kev = new QKeyEvent(QEvent::KeyRelease, k, modifiers, 0, 0, 0);
296 QApplication::postEvent(focus, kev);
297 }
298 timer.start(timeout);
299 return true;
300 }
301
302 bool ShortcutManager::eventFilter(QObject* o, QEvent* ev)
303 {
304 switch (ev->type()) {
305 case QEvent::KeyPress:
306 lastFocus = nullptr;
307 break;
308 case QEvent::ShortcutOverride: {
309 auto kev = static_cast<QKeyEvent*>(ev);
310 if (!kev) {
311 break;
312 }
313 // don't process application shortcuts if we are editing a text widget
314 if (auto* focus = QApplication::focusWidget()) {
315 auto* maybeProxy = focus->focusProxy();
316 auto* focusOrProxy = maybeProxy ? maybeProxy : focus;
317
318 if (focusOrProxy->inherits("QLineEdit")) {
319 ev->accept();
320 return true;
321 }
322 }
323 break;
324 }
325 case QEvent::Shortcut:
326 if (timeout > 0) {
327 auto sev = static_cast<QShortcutEvent*>(ev);
328 if (checkShortcut(o, sev->key())) {
329 // shortcut event handled here, so filter out the event
330 return true;
331 }
332 else {
333 // Not handled. Clear any existing pending actions.
334 timer.stop();
335 for (const auto& info : pendingActions) {
336 if (info.action) {
337 info.action->setEnabled(true);
338 }
339 }
340 pendingActions.clear();
341 lastFocus = nullptr;
342 }
343 }
344 break;
345 case QEvent::ActionChanged:
346 if (auto action = qobject_cast<QAction*>(o)) {
347 auto& index = actionMap.get<0>();
348 auto it = index.find(reinterpret_cast<intptr_t>(action));
349 if (action->shortcut().isEmpty()) {
350 if (it != index.end()) {
351 QKeySequence oldShortcut = it->key.shortcut;
352 index.erase(it);
353 actionShortcutChanged(action, oldShortcut);
354 }
355 break;
356 }
357
358 QByteArray name;
359 if (auto fcAction = qobject_cast<Action*>(action->parent())) {
360 if (fcAction->command() && fcAction->command()->getName()) {
361 name = fcAction->command()->getName();
362 }
363 }
364 if (name.isEmpty()) {
365 name = action->objectName().size() ? action->objectName().toUtf8()
366 : action->text().toUtf8();
367 if (name.isEmpty()) {
368 name = "~";
369 }
370 else {
371 name = QByteArray("~ ") + name;
372 }
373 }
374 if (it != index.end()) {
375 if (it->key.shortcut == action->shortcut() && it->key.name == name) {
376 break;
377 }
378 QKeySequence oldShortcut = it->key.shortcut;
379 index.replace(it, ActionData {action, name});
380 actionShortcutChanged(action, oldShortcut);
381 }
382 else {
383 index.insert(ActionData {action, name});
384 actionShortcutChanged(action, QKeySequence());
385 }
386 }
387 break;
388 default:
389 break;
390 }
391 return false;
392 }
393
394 std::vector<std::pair<QByteArray, QAction*>> ShortcutManager::getActionsByShortcut(
395 const QKeySequence& shortcut
396 )
397 {
398 const auto& index = actionMap.get<1>();
399 std::vector<std::pair<QByteArray, QAction*>> res;
400 std::multimap<int, const ActionData*, std::greater<>> map;
401 for (auto it = index.lower_bound(ActionKey(shortcut)); it != index.end(); ++it) {
402 if (it->key.shortcut != shortcut) {
403 break;
404 }
405 if (it->key.name != "~" && it->action) {
406 map.emplace(getPriority(it->key.name), &(*it));
407 }
408 }
409 for (const auto& v : map) {
410 res.emplace_back(v.second->key.name, v.second->action);
411 }
412 return res;
413 }
414
415 void ShortcutManager::setPriorities(const std::vector<QByteArray>& actions)
416 {
417 if (actions.empty()) {
418 return;
419 }
420 // Keep the same top priority of the given action, and adjust the rest. Can
421 // go negative if necessary
422 int current = 0;
423 for (const auto& name : actions) {
424 current = std::max(current, getPriority(name));
425 }
426 if (current == 0) {
427 current = (int)actions.size();
428 }
429 setPriority(actions.front(), current);
430 ++current;
431 for (const auto& name : actions) {
432 int p = getPriority(name);
433 if (p <= 0 || p >= current) {
434 if (--current == 0) {
435 --current;
436 }
437 setPriority(name, current);
438 }
439 else {
440 current = p;
441 }
442 }
443 }
444
445 int ShortcutManager::getPriority(const char* cmdName)
446 {
447 if (!cmdName) {
448 return 0;
449 }
450 auto it = priorities.find(cmdName);
451 if (it == priorities.end()) {
452 return 0;
453 }
454 return it->second;
455 }
456
457 void ShortcutManager::setPriority(const char* cmdName, int p)
458 {
459 if (p == 0) {
460 hPriorities->RemoveInt(cmdName);
461 }
462 else {
463 hPriorities->SetInt(cmdName, p);
464 }
465 }
466
467 void ShortcutManager::setTopPriority(const char* cmdName)
468 {
469 ++topPriority;
470 hPriorities->SetInt(cmdName, topPriority);
471 }
472
473 void ShortcutManager::onTimer()
474 {
475 timer.stop();
476
477 QAction* found = nullptr;
478 int priority = -std::numeric_limits<int>::max();
479 int seq_length = 0;
480 for (const auto& info : pendingActions) {
481 if (info.action) {
482 info.action->setEnabled(true);
483 if (info.seq_length > seq_length
484 || (info.seq_length == seq_length && info.priority > priority)) {
485 priority = info.priority;
486 seq_length = info.seq_length;
487 found = info.action;
488 }
489 }
490 }
491 if (found) {
492 found->activate(QAction::Trigger);
493 }
494 pendingActions.clear();
495
496 if (lastFocus && lastFocus == QApplication::focusWidget()) {
497 // We are here because we have withheld some previous triggered action.
498 // We then disabled the action, and faked the same key strokes in order
499 // to wait for more potential match of longer key sequence. We use
500 // a timer to end the wait and trigger the pending action.
501 //
502 // However, Qt's internal shorcutmap state machine is still armed with
503 // our fake key strokes. So we try to fake some more obscure symbol key
504 // stroke below, hoping to reset Qt's state machine.
505
506 const auto& index = actionMap.get<1>();
507 static const std::string symbols = "~!@#$%^&*()_+";
508 QString shortcut = pendingSequence.toString() + QStringLiteral(", Ctrl+");
509 for (int s : symbols) {
510 QKeySequence k(shortcut + QLatin1Char(s));
511 auto it = index.lower_bound(ActionKey(k));
512 if (it->key.shortcut != k) {
513 QKeyEvent* kev = new QKeyEvent(QEvent::KeyPress, s, Qt::ControlModifier, 0, 0, 0);
514 QApplication::postEvent(lastFocus, kev);
515 kev = new QKeyEvent(QEvent::KeyRelease, s, Qt::ControlModifier, 0, 0, 0);
516 QApplication::postEvent(lastFocus, kev);
517 break;
518 }
519 }
520 }
521 }
522
523 #include "moc_ShortcutManager.cpp"