Debian Codegraph @

src/Gui/Dialogs/DlgKeyboardImp.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net> *
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 <boost/signals2/connection.hpp>
24
25 #include <QAction>
26 #include <QHeaderView>
27 #include <QMessageBox>
28 #include <QTimer>
29
30 #include <Base/Parameter.h>
31 #include <Base/Tools.h>
32 #include <Base/Console.h>
33
34 #include "Dialogs/DlgKeyboardImp.h"
35 #include "ui_DlgKeyboard.h"
36 #include "Action.h"
37 #include "Application.h"
38 #include "BitmapFactory.h"
39 #include "Command.h"
40 #include "Window.h"
41 #include "PrefWidgets.h"
42 #include "ShortcutManager.h"
43 #include "CommandCompleter.h"
44
45
46 using namespace Gui::Dialog;
47
48 namespace Gui
49 {
50 namespace Dialog
51 {
52 using GroupMap = std::vector<std::pair<QLatin1String, QString>>;
53
54 struct GroupMap_find
55 {
56 const QLatin1String& item;
57 explicit GroupMap_find(const QLatin1String& item)
58 : item(item)
59 {}
60 bool operator()(const std::pair<QLatin1String, QString>& elem) const
61 {
62 return elem.first == item;
63 }
64 };
65 } // namespace Dialog
66 } // namespace Gui
67
68 /* TRANSLATOR Gui::Dialog::DlgCustomKeyboardImp */
69
70 /**
71 * Constructs a DlgCustomKeyboardImp which is a child of 'parent', with the
72 * name 'name' and widget flags set to 'f'
73 *
74 * The dialog will by default be modeless, unless you set 'modal' to
75 * true to construct a modal dialog.
76 */
77 DlgCustomKeyboardImp::DlgCustomKeyboardImp(QWidget* parent)
78 : CustomizeActionPage(parent)
79 , ui(new Ui_DlgCustomKeyboard)
80 , firstShow(true)
81 {
82 ui->setupUi(this);
83 setupConnections();
84
85 // Force create actions for all commands with shortcut to register with ShortcutManager
86 for (auto cmd : Application::Instance->commandManager().getAllCommands()) {
87 if (cmd->getShortcut().size()) {
88 cmd->initAction();
89 }
90 }
91 QObject::connect(
92 ShortcutManager::instance(),
93 &ShortcutManager::shortcutChanged,
94 this,
95 [](const char* cmdName) {
96 if (auto cmd = Application::Instance->commandManager().getCommandByName(cmdName)) {
97 cmd->initAction();
98 }
99 }
100 );
101
102 conn = initCommandWidgets(
103 ui->commandTreeWidget,
104 nullptr,
105 ui->categoryBox,
106 ui->editCommand,
107 ui->assignedTreeWidget,
108 ui->buttonUp,
109 ui->buttonDown,
110 ui->editShortcut,
111 ui->accelLineEditShortcut
112 );
113
114 ui->shortcutTimeout->onRestore();
115 QTimer* timer = new QTimer(this);
116 QObject::connect(ui->shortcutTimeout, qOverload<int>(&QSpinBox::valueChanged), timer, [=](int) {
117 timer->start(100);
118 });
119 QObject::connect(timer, &QTimer::timeout, [this]() { ui->shortcutTimeout->onSave(); });
120 }
121
122 /** Destroys the object and frees any allocated resources */
123 DlgCustomKeyboardImp::~DlgCustomKeyboardImp() = default;
124
125 void DlgCustomKeyboardImp::setupConnections()
126 {
127 // clang-format off
128 connect(ui->categoryBox, qOverload<int>(&QComboBox::activated),
129 this, &DlgCustomKeyboardImp::onCategoryBoxActivated);
130 connect(ui->commandTreeWidget, &QTreeWidget::currentItemChanged,
131 this, &DlgCustomKeyboardImp::onCommandTreeWidgetCurrentItemChanged);
132 connect(ui->buttonAssign, &QPushButton::clicked,
133 this, &DlgCustomKeyboardImp::onButtonAssignClicked);
134 connect(ui->buttonClear, &QPushButton::clicked,
135 this, &DlgCustomKeyboardImp::onButtonClearClicked);
136 connect(ui->buttonReset, &QPushButton::clicked,
137 this, &DlgCustomKeyboardImp::onButtonResetClicked);
138 connect(ui->buttonResetAll, &QPushButton::clicked,
139 this, &DlgCustomKeyboardImp::onButtonResetAllClicked);
140 connect(ui->editShortcut, &AccelLineEdit::keySequenceChanged,
141 this, &DlgCustomKeyboardImp::onEditShortcutTextChanged);
142 // clang-format on
143 }
144
145 void DlgCustomKeyboardImp::initCommandCompleter(
146 QLineEdit* edit,
147 QComboBox* combo,
148 QTreeWidget* commandTreeWidget,
149 QTreeWidgetItem* separatorItem
150 )
151 {
152 edit->setPlaceholderText(tr("Type to search…"));
153 auto completer = new CommandCompleter(edit, edit);
154
155 QObject::connect(completer, &CommandCompleter::commandActivated, [=](const QByteArray& name) {
156 CommandManager& cCmdMgr = Application::Instance->commandManager();
157 Command* cmd = cCmdMgr.getCommandByName(name.constData());
158 if (!cmd) {
159 return;
160 }
161
162 QString group = QString::fromLatin1(cmd->getGroupName());
163 int index = combo->findData(group);
164 if (index < 0) {
165 return;
166 }
167 if (index != combo->currentIndex()) {
168 QSignalBlocker blocker(combo);
169 combo->setCurrentIndex(index);
170 populateCommandList(commandTreeWidget, separatorItem, combo);
171 }
172 for (int i = 0; i < commandTreeWidget->topLevelItemCount(); ++i) {
173 QTreeWidgetItem* item = commandTreeWidget->topLevelItem(i);
174 if (item->data(1, Qt::UserRole).toByteArray() == name) {
175 commandTreeWidget->setCurrentItem(item);
176 return;
177 }
178 }
179 });
180 }
181
182 void DlgCustomKeyboardImp::populateCommandList(
183 QTreeWidget* commandTreeWidget,
184 QTreeWidgetItem* separatorItem,
185 QComboBox* combo
186 )
187 {
188 QByteArray current;
189 if (auto item = commandTreeWidget->currentItem()) {
190 current = item->data(1, Qt::UserRole).toByteArray();
191 }
192
193 if (separatorItem) {
194 commandTreeWidget->takeTopLevelItem(commandTreeWidget->indexOfTopLevelItem(separatorItem));
195 }
196 commandTreeWidget->clear();
197 if (separatorItem) {
198 commandTreeWidget->addTopLevelItem(separatorItem);
199 }
200
201 CommandManager& cCmdMgr = Application::Instance->commandManager();
202 auto group = combo->itemData(combo->currentIndex(), Qt::UserRole).toByteArray();
203 auto cmds = group == "All" ? cCmdMgr.getAllCommands()
204 : cCmdMgr.getGroupCommands(group.constData());
205 QTreeWidgetItem* currentItem = nullptr;
206 for (const Command* cmd : cmds) {
207 QTreeWidgetItem* item = new QTreeWidgetItem(commandTreeWidget);
208 item->setText(1, Action::commandMenuText(cmd));
209 item->setToolTip(1, Action::commandToolTip(cmd));
210 item->setData(1, Qt::UserRole, QByteArray(cmd->getName()));
211 item->setSizeHint(0, QSize(32, 32));
212 if (auto pixmap = cmd->getPixmap()) {
213 item->setIcon(0, BitmapFactory().iconFromTheme(pixmap));
214 }
215 item->setText(2, cmd->getShortcut());
216 if (auto accel = cmd->getAccel()) {
217 item->setText(3, QKeySequence(QString::fromLatin1(accel)).toString());
218 }
219
220 if (current == cmd->getName()) {
221 currentItem = item;
222 }
223 }
224 if (currentItem) {
225 commandTreeWidget->setCurrentItem(currentItem);
226 }
227 commandTreeWidget->resizeColumnToContents(2);
228 commandTreeWidget->resizeColumnToContents(3);
229 }
230
231 boost::signals2::connection DlgCustomKeyboardImp::initCommandList(
232 QTreeWidget* commandTreeWidget,
233 QTreeWidgetItem* separatorItem,
234 QComboBox* combo
235 )
236 {
237 QStringList labels;
238 labels << tr("Icon") << tr("Command") << tr("Shortcut") << tr("Default");
239 commandTreeWidget->setHeaderLabels(labels);
240 commandTreeWidget->setIconSize(QSize(32, 32));
241 commandTreeWidget->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
242 commandTreeWidget->header()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
243 commandTreeWidget->header()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
244
245 populateCommandGroups(combo);
246
247 // Using a timer to respond to command change for performance, and also
248 // because macro command may be added before proper initialization (null
249 // menu text, etc.)
250 QTimer* timer = new QTimer(combo);
251 timer->setSingleShot(true);
252
253 QObject::connect(timer, &QTimer::timeout, [=]() {
254 populateCommandGroups(combo);
255 populateCommandList(commandTreeWidget, separatorItem, combo);
256 });
257
258 QObject::connect(ShortcutManager::instance(), &ShortcutManager::shortcutChanged, timer, [timer]() {
259 timer->start(100);
260 });
261
262 QObject::connect(combo, qOverload<int>(&QComboBox::activated), timer, [timer]() {
263 timer->start(100);
264 });
265
266 return Application::Instance->commandManager().signalChanged.connect([timer]() {
267 timer->start(100);
268 });
269 }
270
271 void DlgCustomKeyboardImp::initPriorityList(
272 QTreeWidget* priorityList,
273 QAbstractButton* buttonUp,
274 QAbstractButton* buttonDown
275 )
276 {
277 QStringList labels;
278 labels << tr("Name") << tr("Title");
279 priorityList->setHeaderLabels(labels);
280 priorityList->header()->hide();
281 priorityList->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
282 priorityList->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
283
284 auto updatePriorityList = [priorityList](bool up) {
285 auto item = priorityList->currentItem();
286 if (!item) {
287 return;
288 }
289
290 int index = priorityList->indexOfTopLevelItem(item);
291 if (index < 0) {
292 return;
293 }
294 if ((index == 0 && up) || (index == priorityList->topLevelItemCount() - 1 && !up)) {
295 return;
296 }
297
298 std::vector<QByteArray> actions;
299 for (int i = 0; i < priorityList->topLevelItemCount(); ++i) {
300 auto item = priorityList->topLevelItem(i);
301 actions.push_back(item->data(0, Qt::UserRole).toByteArray());
302 }
303
304 auto it = actions.begin() + index;
305 auto itNext = up ? it - 1 : it + 1;
306 std::swap(*it, *itNext);
307 ShortcutManager::instance()->setPriorities(actions);
308 };
309
310 QObject::connect(buttonUp, &QAbstractButton::clicked, [=]() { updatePriorityList(true); });
311 QObject::connect(buttonDown, &QAbstractButton::clicked, [=]() { updatePriorityList(false); });
312 QObject::connect(priorityList, &QTreeWidget::currentItemChanged, [=](QTreeWidgetItem* item) {
313 buttonUp->setEnabled(item != nullptr);
314 buttonDown->setEnabled(item != nullptr);
315 });
316 }
317
318 boost::signals2::connection DlgCustomKeyboardImp::initCommandWidgets(
319 QTreeWidget* commandTreeWidget,
320 QTreeWidgetItem* separatorItem,
321 QComboBox* comboGroups,
322 QLineEdit* editCommand,
323 QTreeWidget* priorityList,
324 QAbstractButton* buttonUp,
325 QAbstractButton* buttonDown,
326 Gui::AccelLineEdit* editShortcut,
327 Gui::AccelLineEdit* currentShortcut
328 )
329 {
330 initCommandCompleter(editCommand, comboGroups, commandTreeWidget, separatorItem);
331 auto conn = initCommandList(commandTreeWidget, separatorItem, comboGroups);
332
333 if (priorityList && buttonUp && buttonDown) {
334 initPriorityList(priorityList, buttonUp, buttonDown);
335
336 auto timer = new QTimer(priorityList);
337 timer->setSingleShot(true);
338 if (currentShortcut) {
339 QObject::connect(currentShortcut, &AccelLineEdit::keySequenceChanged, timer, [timer]() {
340 timer->start(200);
341 });
342 }
343 QObject::connect(editShortcut, &AccelLineEdit::keySequenceChanged, timer, [timer]() {
344 timer->start(200);
345 });
346 QObject::connect(
347 ShortcutManager::instance(),
348 &ShortcutManager::priorityChanged,
349 timer,
350 [timer]() { timer->start(200); }
351 );
352 QObject::connect(timer, &QTimer::timeout, [=]() {
353 populatePriorityList(priorityList, editShortcut, currentShortcut);
354 });
355 }
356
357 return conn;
358 }
359
360 void DlgCustomKeyboardImp::populatePriorityList(
361 QTreeWidget* priorityList,
362 Gui::AccelLineEdit* editor,
363 Gui::AccelLineEdit* curShortcut
364 )
365 {
366 QByteArray current;
367 if (auto currentItem = priorityList->currentItem()) {
368 current = currentItem->data(0, Qt::UserRole).toByteArray();
369 }
370
371 priorityList->clear();
372 QString sc;
373 if (!editor->isEmpty()) {
374 sc = editor->text();
375 }
376 else if (curShortcut && !curShortcut->isEmpty()) {
377 sc = curShortcut->text();
378 }
379
380 auto actionList = ShortcutManager::instance()->getActionsByShortcut(sc);
381 QTreeWidgetItem* currentItem = nullptr;
382 for (const auto& info : actionList) {
383 if (!info.second) {
384 continue;
385 }
386 QTreeWidgetItem* item = new QTreeWidgetItem(priorityList);
387 item->setText(0, QString::fromUtf8(info.first));
388 item->setText(1, Action::cleanTitle(info.second->text()));
389 item->setToolTip(0, info.second->toolTip());
390 item->setIcon(0, info.second->icon());
391 item->setData(0, Qt::UserRole, info.first);
392 if (current == info.first) {
393 currentItem = item;
394 }
395 }
396 priorityList->resizeColumnToContents(0);
397 priorityList->resizeColumnToContents(1);
398 if (currentItem) {
399 priorityList->setCurrentItem(currentItem);
400 }
401 }
402
403 void DlgCustomKeyboardImp::populateCommandGroups(QComboBox* combo)
404 {
405 CommandManager& cCmdMgr = Application::Instance->commandManager();
406 std::map<std::string, Command*> sCommands = cCmdMgr.getCommands();
407
408 GroupMap groupMap;
409 groupMap.push_back(std::make_pair(QLatin1String("File"), QString()));
410 groupMap.push_back(std::make_pair(QLatin1String("Edit"), QString()));
411 groupMap.push_back(std::make_pair(QLatin1String("View"), QString()));
412 groupMap.push_back(std::make_pair(QLatin1String("Standard-View"), QString()));
413 groupMap.push_back(std::make_pair(QLatin1String("Tools"), QString()));
414 groupMap.push_back(std::make_pair(QLatin1String("Window"), QString()));
415 groupMap.push_back(std::make_pair(QLatin1String("Help"), QString()));
416 groupMap.push_back(
417 std::make_pair(QLatin1String("Macros"), qApp->translate("Gui::MacroCommand", "Macros"))
418 );
419
420 for (const auto& sCommand : sCommands) {
421 QLatin1String group(sCommand.second->getGroupName());
422 QString text = sCommand.second->translatedGroupName();
423 GroupMap::iterator jt;
424 jt = std::find_if(groupMap.begin(), groupMap.end(), GroupMap_find(group));
425 if (jt != groupMap.end()) {
426 if (jt->second.isEmpty()) {
427 jt->second = text;
428 }
429 }
430 else {
431 groupMap.push_back(std::make_pair(group, text));
432 }
433 }
434 groupMap.push_back(std::make_pair(QLatin1String("All"), tr("All")));
435
436 for (const auto& it : groupMap) {
437 if (combo->findData(it.first) < 0) {
438 combo->addItem(it.second);
439 combo->setItemData(combo->count() - 1, QVariant(it.first), Qt::UserRole);
440 }
441 }
442 }
443
444 void DlgCustomKeyboardImp::showEvent(QShowEvent* e)
445 {
446 Q_UNUSED(e);
447 // If we did this already in the constructor we wouldn't get the vertical scrollbar if needed.
448 // The problem was noticed with Qt 4.1.4 but may arise with any later version.
449 if (firstShow) {
450 ui->categoryBox->activated(ui->categoryBox->currentIndex());
451 firstShow = false;
452 }
453 }
454
455 /** Shows the description for the corresponding command */
456 void DlgCustomKeyboardImp::onCommandTreeWidgetCurrentItemChanged(QTreeWidgetItem* item)
457 {
458 if (!item) {
459 return;
460 }
461
462 QVariant data = item->data(1, Qt::UserRole);
463 QByteArray name = data.toByteArray(); // command name
464
465 CommandManager& cCmdMgr = Application::Instance->commandManager();
466 Command* cmd = cCmdMgr.getCommandByName(name.constData());
467 if (cmd) {
468 QKeySequence ks = ShortcutManager::instance()->getShortcut(cmd->getName(), cmd->getAccel());
469 QKeySequence ks2 = QString::fromLatin1(cmd->getAccel());
470 QKeySequence ks3 = ui->editShortcut->text();
471 if (ks.isEmpty()) {
472 ui->accelLineEditShortcut->clear();
473 }
474 else {
475 ui->accelLineEditShortcut->setKeySequence(ks);
476 }
477
478 ui->buttonAssign->setEnabled(!ui->editShortcut->text().isEmpty() && (ks != ks3));
479 ui->buttonReset->setEnabled((ks != ks2));
480 }
481 }
482
483 /** Shows all commands of this category */
484 void DlgCustomKeyboardImp::onCategoryBoxActivated(int)
485 {
486 ui->buttonAssign->setEnabled(false);
487 ui->buttonReset->setEnabled(false);
488 ui->accelLineEditShortcut->clear();
489 ui->editShortcut->clear();
490 }
491
492 void DlgCustomKeyboardImp::setShortcutOfCurrentAction(const QString& accelText)
493 {
494 QTreeWidgetItem* item = ui->commandTreeWidget->currentItem();
495 if (!item) {
496 return;
497 }
498
499 QVariant data = item->data(1, Qt::UserRole);
500 QByteArray name = data.toByteArray(); // command name
501
502 QString portableText;
503 if (!accelText.isEmpty()) {
504 QKeySequence shortcut = accelText;
505 portableText = shortcut.toString(QKeySequence::PortableText);
506 ui->accelLineEditShortcut->setKeySequence(shortcut);
507 ui->editShortcut->clear();
508 }
509 else {
510 ui->accelLineEditShortcut->clear();
511 ui->editShortcut->clear();
512 }
513 ShortcutManager::instance()->setShortcut(name, portableText.toLatin1());
514
515 ui->buttonAssign->setEnabled(false);
516 ui->buttonReset->setEnabled(true);
517 }
518
519 /** Assigns a new accelerator to the selected command. */
520 void DlgCustomKeyboardImp::onButtonAssignClicked()
521 {
522 setShortcutOfCurrentAction(ui->editShortcut->text());
523 }
524
525 /** Clears the accelerator of the selected command. */
526 void DlgCustomKeyboardImp::onButtonClearClicked()
527 {
528 setShortcutOfCurrentAction(QString());
529 }
530
531 /** Resets the accelerator of the selected command to the default. */
532 void DlgCustomKeyboardImp::onButtonResetClicked()
533 {
534 QTreeWidgetItem* item = ui->commandTreeWidget->currentItem();
535 if (!item) {
536 return;
537 }
538
539 QVariant data = item->data(1, Qt::UserRole);
540 QByteArray name = data.toByteArray(); // command name
541 ShortcutManager::instance()->reset(name);
542
543 QString txt = ShortcutManager::instance()->getShortcut(name);
544 ui->accelLineEditShortcut->setKeySequence(QKeySequence(txt));
545 ui->buttonReset->setEnabled(false);
546 }
547
548 /** Resets the accelerator of all commands to the default. */
549 void DlgCustomKeyboardImp::onButtonResetAllClicked()
550 {
551 ShortcutManager::instance()->resetAll();
552 ui->buttonReset->setEnabled(false);
553 }
554
555 /** Checks for an already occupied shortcut. */
556 void DlgCustomKeyboardImp::onEditShortcutTextChanged(const QKeySequence&)
557 {
558 QTreeWidgetItem* item = ui->commandTreeWidget->currentItem();
559 if (item) {
560 QVariant data = item->data(1, Qt::UserRole);
561 QByteArray name = data.toByteArray(); // command name
562
563 CommandManager& cCmdMgr = Application::Instance->commandManager();
564 Command* cmd = cCmdMgr.getCommandByName(name.constData());
565
566 if (!ui->editShortcut->isEmpty()) {
567 ui->buttonAssign->setEnabled(true);
568 }
569 else {
570 if (cmd && cmd->getAction() && cmd->getAction()->shortcut().isEmpty()) {
571 ui->buttonAssign->setEnabled(false); // both key sequences are empty
572 }
573 }
574 }
575 }
576
577 void DlgCustomKeyboardImp::onAddMacroAction(const QByteArray&)
578 {}
579
580 void DlgCustomKeyboardImp::onRemoveMacroAction(const QByteArray&)
581 {}
582
583 void DlgCustomKeyboardImp::onModifyMacroAction(const QByteArray&)
584 {
585 QVariant data = ui->categoryBox->itemData(ui->categoryBox->currentIndex(), Qt::UserRole);
586 QString group = data.toString();
587 if (group == QLatin1String("Macros")) {
588 ui->categoryBox->activated(ui->categoryBox->currentIndex());
589 }
590 }
591
592 void DlgCustomKeyboardImp::changeEvent(QEvent* e)
593 {
594 if (e->type() == QEvent::LanguageChange) {
595 ui->retranslateUi(this);
596 int count = ui->categoryBox->count();
597
598 CommandManager& cCmdMgr = Application::Instance->commandManager();
599 for (int i = 0; i < count; i++) {
600 QVariant data = ui->categoryBox->itemData(i, Qt::UserRole);
601 std::vector<Command*> aCmds = cCmdMgr.getGroupCommands(data.toByteArray());
602 if (!aCmds.empty()) {
603 QString text = aCmds[0]->translatedGroupName();
604 ui->categoryBox->setItemText(i, text);
605 }
606 }
607 ui->categoryBox->activated(ui->categoryBox->currentIndex());
608 }
609 else if (e->type() == QEvent::StyleChange) {
610 ui->categoryBox->activated(ui->categoryBox->currentIndex());
611 }
612
613 QWidget::changeEvent(e);
614 }
615
616 #include "moc_DlgKeyboardImp.cpp"