Fix modifier names for Mac
[quassel.git] / src / qtui / settingspages / keysequencewidget.cpp
1 /***************************************************************************
2  *   Copyright (C) 2010 by the Quassel Project                             *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This class has been inspired by KDE's KKeySequenceWidget and uses     *
6  *   some code snippets of its implementation, part of kdelibs.            *
7  *   The original file is                                                  *
8  *       Copyright (C) 1998 Mark Donohoe <donohoe@kde.org>                 *
9  *       Copyright (C) 2001 Ellis Whitehead <ellis@kde.org>                *
10  *       Copyright (C) 2007 Andreas Hartmetz <ahartmetz@gmail.com>         *
11  *                                                                         *
12  *   This program is free software; you can redistribute it and/or modify  *
13  *   it under the terms of the GNU General Public License as published by  *
14  *   the Free Software Foundation; either version 2 of the License, or     *
15  *   (at your option) any later version.                                   *
16  *                                                                         *
17  *   This program is distributed in the hope that it will be useful,       *
18  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
19  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
20  *   GNU General Public License for more details.                          *
21  *                                                                         *
22  *   You should have received a copy of the GNU General Public License     *
23  *   along with this program; if not, write to the                         *
24  *   Free Software Foundation, Inc.,                                       *
25  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
26  ***************************************************************************/
27
28 #include <QApplication>
29 #include <QDebug>
30 #include <QKeyEvent>
31 #include <QHBoxLayout>
32 #include <QMessageBox>
33 #include <QToolButton>
34
35 #include "action.h"
36 #include "actioncollection.h"
37 #include "iconloader.h"
38 #include "keysequencewidget.h"
39
40 KeySequenceButton::KeySequenceButton(KeySequenceWidget *d_, QWidget *parent)
41   : QPushButton(parent),
42   d(d_)
43 {
44
45 }
46
47 bool KeySequenceButton::event(QEvent *e) {
48   if(d->isRecording() && e->type() == QEvent::KeyPress) {
49     keyPressEvent(static_cast<QKeyEvent *>(e));
50     return true;
51   }
52
53   // The shortcut 'alt+c' ( or any other dialog local action shortcut )
54   // ended the recording and triggered the action associated with the
55   // action. In case of 'alt+c' ending the dialog.  It seems that those
56   // ShortcutOverride events get sent even if grabKeyboard() is active.
57   if(d->isRecording() && e->type() == QEvent::ShortcutOverride) {
58     e->accept();
59     return true;
60   }
61
62   return QPushButton::event(e);
63 }
64
65 void KeySequenceButton::keyPressEvent(QKeyEvent *e) {
66   int keyQt = e->key();
67   if(keyQt == -1) {
68     // Qt sometimes returns garbage keycodes, I observed -1, if it doesn't know a key.
69     // We cannot do anything useful with those (several keys have -1, indistinguishable)
70     // and QKeySequence.toString() will also yield a garbage string.
71     QMessageBox::information(this,
72                              tr("The key you just pressed is not supported by Qt."),
73                              tr("Unsupported Key"));
74     return d->cancelRecording();
75   }
76
77   uint newModifiers = e->modifiers() & (Qt::SHIFT | Qt::CTRL | Qt::ALT | Qt::META);
78
79   //don't have the return or space key appear as first key of the sequence when they
80   //were pressed to start editing - catch and them and imitate their effect
81   if(!d->isRecording() && ((keyQt == Qt::Key_Return || keyQt == Qt::Key_Space))) {
82     d->startRecording();
83     d->_modifierKeys = newModifiers;
84     d->updateShortcutDisplay();
85     return;
86   }
87
88   // We get events even if recording isn't active.
89   if(!d->isRecording())
90     return QPushButton::keyPressEvent(e);
91
92   e->accept();
93   d->_modifierKeys = newModifiers;
94
95   switch(keyQt) {
96   case Qt::Key_AltGr: //or else we get unicode salad
97     return;
98   case Qt::Key_Shift:
99   case Qt::Key_Control:
100   case Qt::Key_Alt:
101   case Qt::Key_Meta:
102   case Qt::Key_Menu: //unused (yes, but why?)
103     d->updateShortcutDisplay();
104     break;
105
106   default:
107     if(!(d->_modifierKeys & ~Qt::SHIFT)) {
108       // It's the first key and no modifier pressed. Check if this is
109       // allowed
110       if(!d->isOkWhenModifierless(keyQt))
111         return;
112     }
113
114     // We now have a valid key press.
115     if(keyQt) {
116       if((keyQt == Qt::Key_Backtab) && (d->_modifierKeys & Qt::SHIFT)) {
117         keyQt = Qt::Key_Tab | d->_modifierKeys;
118       }
119       else if(d->isShiftAsModifierAllowed(keyQt)) {
120         keyQt |= d->_modifierKeys;
121       } else
122         keyQt |= (d->_modifierKeys & ~Qt::SHIFT);
123
124       d->_keySequence = QKeySequence(keyQt);
125       d->doneRecording();
126     }
127   }
128 }
129
130 void KeySequenceButton::keyReleaseEvent(QKeyEvent *e) {
131   if(e->key() == -1) {
132     // ignore garbage, see keyPressEvent()
133     return;
134   }
135
136   if(!d->isRecording())
137     return QPushButton::keyReleaseEvent(e);
138
139   e->accept();
140
141   uint newModifiers = e->modifiers() & (Qt::SHIFT | Qt::CTRL | Qt::ALT | Qt::META);
142
143   // if a modifier that belongs to the shortcut was released...
144   if((newModifiers & d->_modifierKeys) < d->_modifierKeys) {
145     d->_modifierKeys = newModifiers;
146     d->updateShortcutDisplay();
147   }
148 }
149
150 /******************************************************************************/
151
152 KeySequenceWidget::KeySequenceWidget(QWidget *parent)
153   : QWidget(parent),
154   _shortcutsModel(0),
155   _isRecording(false),
156   _modifierKeys(0)
157 {
158   QHBoxLayout *layout = new QHBoxLayout(this);
159   layout->setMargin(0);
160
161   _keyButton = new KeySequenceButton(this, this);
162   _keyButton->setFocusPolicy(Qt::StrongFocus);
163   _keyButton->setIcon(SmallIcon("configure"));
164   _keyButton->setToolTip(tr("Click on the button, then enter the shortcut like you would in the program.\nExample for Ctrl+a: hold the Ctrl key and press a."));
165   layout->addWidget(_keyButton);
166
167   _clearButton = new QToolButton(this);
168   layout->addWidget(_clearButton);
169
170   if(qApp->isLeftToRight())
171     _clearButton->setIcon(SmallIcon("edit-clear-locationbar-rtl"));
172   else
173     _clearButton->setIcon(SmallIcon("edit-clear-locationbar-ltr"));
174
175   setLayout(layout);
176
177   connect(_keyButton, SIGNAL(clicked()), SLOT(startRecording()));
178   connect(_keyButton, SIGNAL(clicked()), SIGNAL(clicked()));
179   connect(_clearButton, SIGNAL(clicked()), SLOT(clear()));
180   connect(_clearButton, SIGNAL(clicked()), SIGNAL(clicked()));
181 }
182
183 void KeySequenceWidget::setModel(ShortcutsModel *model) {
184   Q_ASSERT(!_shortcutsModel);
185   _shortcutsModel = model;
186 }
187
188 bool KeySequenceWidget::isOkWhenModifierless(int keyQt) const {
189   //this whole function is a hack, but especially the first line of code
190   if(QKeySequence(keyQt).toString().length() == 1)
191     return false;
192
193   switch(keyQt) {
194   case Qt::Key_Return:
195   case Qt::Key_Space:
196   case Qt::Key_Tab:
197   case Qt::Key_Backtab: //does this ever happen?
198   case Qt::Key_Backspace:
199   case Qt::Key_Delete:
200     return false;
201   default:
202     return true;
203   }
204 }
205
206 bool KeySequenceWidget::isShiftAsModifierAllowed(int keyQt) const {
207   // Shift only works as a modifier with certain keys. It's not possible
208   // to enter the SHIFT+5 key sequence for me because this is handled as
209   // '%' by qt on my keyboard.
210   // The working keys are all hardcoded here :-(
211   if(keyQt >= Qt::Key_F1 && keyQt <= Qt::Key_F35)
212     return true;
213
214   if(QChar(keyQt).isLetter())
215     return true;
216
217   switch(keyQt) {
218   case Qt::Key_Return:
219   case Qt::Key_Space:
220   case Qt::Key_Backspace:
221   case Qt::Key_Escape:
222   case Qt::Key_Print:
223   case Qt::Key_ScrollLock:
224   case Qt::Key_Pause:
225   case Qt::Key_PageUp:
226   case Qt::Key_PageDown:
227   case Qt::Key_Insert:
228   case Qt::Key_Delete:
229   case Qt::Key_Home:
230   case Qt::Key_End:
231   case Qt::Key_Up:
232   case Qt::Key_Down:
233   case Qt::Key_Left:
234   case Qt::Key_Right:
235     return true;
236
237   default:
238     return false;
239   }
240 }
241
242 void KeySequenceWidget::updateShortcutDisplay() {
243   // make translators happy
244 #if defined(Q_WS_MAC)
245   static QString metaKey = tr("Ctrl", "Ctrl key on Mac");
246   static QString ctrlKey = tr("⌘", "Cmd key on Mac");
247 #else
248   static QString metaKey = tr("Meta", "Meta key");
249   static QString ctrlKey = tr("Ctrl", "Ctrl key");
250 #endif
251   static QString altKey = tr("Alt", "Alt key");
252   static QString shiftKey = tr("Shift", "Shift key");
253
254   QString s = _keySequence.toString(QKeySequence::NativeText);
255   s.replace('&', QLatin1String("&&"));
256
257   if(_isRecording) {
258     if(_modifierKeys) {
259       if(_modifierKeys & Qt::META)  s += metaKey + '+';
260       if(_modifierKeys & Qt::CTRL)  s += ctrlKey + '+';
261       if(_modifierKeys & Qt::ALT)   s += altKey + '+';
262       if(_modifierKeys & Qt::SHIFT) s += shiftKey + '+';
263
264     } else {
265       s = tr("Input", "What the user inputs now will be taken as the new shortcut");
266     }
267     // make it clear that input is still going on
268     s.append(" ...");
269   }
270
271   if(s.isEmpty()) {
272     s = tr("None", "No shortcut defined");
273   }
274
275   s.prepend(' ');
276   s.append(' ');
277   _keyButton->setText(s);
278 }
279
280 void KeySequenceWidget::startRecording() {
281   _modifierKeys = 0;
282   _oldKeySequence = _keySequence;
283   _keySequence = QKeySequence();
284   _conflictingIndex = QModelIndex();
285   _isRecording = true;
286   _keyButton->grabKeyboard();
287
288   if(!QWidget::keyboardGrabber()) {
289     qWarning() << "Failed to grab the keyboard! Most likely qt's nograb option is active";
290   }
291
292   _keyButton->setDown(true);
293   updateShortcutDisplay();
294 }
295
296
297 void KeySequenceWidget::doneRecording() {
298   bool wasRecording = _isRecording;
299   _isRecording = false;
300   _keyButton->releaseKeyboard();
301   _keyButton->setDown(false);
302
303   if(!wasRecording || _keySequence == _oldKeySequence) {
304     // The sequence hasn't changed
305     updateShortcutDisplay();
306     return;
307   }
308
309   if(!isKeySequenceAvailable(_keySequence)) {
310     _keySequence = _oldKeySequence;
311   } else if(wasRecording) {
312     emit keySequenceChanged(_keySequence, _conflictingIndex);
313   }
314   updateShortcutDisplay();
315 }
316
317 void KeySequenceWidget::cancelRecording() {
318   _keySequence = _oldKeySequence;
319   doneRecording();
320 }
321
322 void KeySequenceWidget::setKeySequence(const QKeySequence &seq) {
323   // oldKeySequence holds the key sequence before recording started, if setKeySequence()
324   // is called while not recording then set oldKeySequence to the existing sequence so
325   // that the keySequenceChanged() signal is emitted if the new and previous key
326   // sequences are different
327   if(!isRecording())
328     _oldKeySequence = _keySequence;
329
330   _keySequence = seq;
331   _clearButton->setVisible(!_keySequence.isEmpty());
332   doneRecording();
333 }
334
335 void KeySequenceWidget::clear() {
336   setKeySequence(QKeySequence());
337   // setKeySequence() won't emit a signal when we're not recording
338   emit keySequenceChanged(QKeySequence());
339 }
340
341 bool KeySequenceWidget::isKeySequenceAvailable(const QKeySequence &seq) {
342   if(seq.isEmpty())
343     return true;
344
345   // We need to access the root model, not the filtered one
346   for(int cat = 0; cat < _shortcutsModel->rowCount(); cat++) {
347     QModelIndex catIdx = _shortcutsModel->index(cat, 0);
348     for(int r = 0; r < _shortcutsModel->rowCount(catIdx); r++) {
349       QModelIndex actIdx = _shortcutsModel->index(r, 0, catIdx);
350       Q_ASSERT(actIdx.isValid());
351       if(actIdx.data(ShortcutsModel::ActiveShortcutRole).value<QKeySequence>() != seq)
352         continue;
353
354       if(!actIdx.data(ShortcutsModel::IsConfigurableRole).toBool()) {
355         QMessageBox::warning(this, tr("Shortcut Conflict"),
356                              tr("The \"%1\" shortcut is already in use, and cannot be configured.\nPlease choose another one.").arg(seq.toString()),
357                              QMessageBox::Ok);
358         return false;
359       }
360
361       QMessageBox box(QMessageBox::Warning, tr("Shortcut Conflict"),
362                       (tr("The \"%1\" shortcut is ambiguous with the shortcut for the following action:")
363                        + "<br><ul><li>%2</li></ul><br>"
364                        + tr("Do you want to reassign this shortcut to the selected action?")
365                        ).arg(seq.toString(), actIdx.data().toString()),
366                       QMessageBox::Cancel, this);
367       box.addButton(tr("Reassign"), QMessageBox::AcceptRole);
368       if(box.exec() == QMessageBox::Cancel)
369         return false;
370
371       _conflictingIndex = actIdx;
372       return true;
373     }
374   }
375   return true;
376 }