Fix keysequence strings for Mac again
[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   QString s = _keySequence.toString(QKeySequence::NativeText);
244   s.replace('&', QLatin1String("&&"));
245
246   if(_isRecording) {
247     if(_modifierKeys) {
248 #ifdef Q_WS_MAC
249       if(_modifierKeys & Qt::META)  s += QChar(kControlUnicode);
250       if(_modifierKeys & Qt::ALT)   s += QChar(kOptionUnicode);
251       if(_modifierKeys & Qt::SHIFT) s += QChar(kShiftUnicode);
252       if(_modifierKeys & Qt::CTRL)  s += QChar(kCommandUnicode);
253 #else
254       if(_modifierKeys & Qt::META)  s += tr("Meta", "Meta key") + '+';
255       if(_modifierKeys & Qt::CTRL)  s += tr("Ctrl", "Ctrl key") + '+';
256       if(_modifierKeys & Qt::ALT)   s += tr("Alt", "Alt key") + '+';
257       if(_modifierKeys & Qt::SHIFT) s += tr("Shift", "Shift key") + '+';
258 #endif
259     } else {
260       s = tr("Input", "What the user inputs now will be taken as the new shortcut");
261     }
262     // make it clear that input is still going on
263     s.append(" ...");
264   }
265
266   if(s.isEmpty()) {
267     s = tr("None", "No shortcut defined");
268   }
269
270   s.prepend(' ');
271   s.append(' ');
272   _keyButton->setText(s);
273 }
274
275 void KeySequenceWidget::startRecording() {
276   _modifierKeys = 0;
277   _oldKeySequence = _keySequence;
278   _keySequence = QKeySequence();
279   _conflictingIndex = QModelIndex();
280   _isRecording = true;
281   _keyButton->grabKeyboard();
282
283   if(!QWidget::keyboardGrabber()) {
284     qWarning() << "Failed to grab the keyboard! Most likely qt's nograb option is active";
285   }
286
287   _keyButton->setDown(true);
288   updateShortcutDisplay();
289 }
290
291
292 void KeySequenceWidget::doneRecording() {
293   bool wasRecording = _isRecording;
294   _isRecording = false;
295   _keyButton->releaseKeyboard();
296   _keyButton->setDown(false);
297
298   if(!wasRecording || _keySequence == _oldKeySequence) {
299     // The sequence hasn't changed
300     updateShortcutDisplay();
301     return;
302   }
303
304   if(!isKeySequenceAvailable(_keySequence)) {
305     _keySequence = _oldKeySequence;
306   } else if(wasRecording) {
307     emit keySequenceChanged(_keySequence, _conflictingIndex);
308   }
309   updateShortcutDisplay();
310 }
311
312 void KeySequenceWidget::cancelRecording() {
313   _keySequence = _oldKeySequence;
314   doneRecording();
315 }
316
317 void KeySequenceWidget::setKeySequence(const QKeySequence &seq) {
318   // oldKeySequence holds the key sequence before recording started, if setKeySequence()
319   // is called while not recording then set oldKeySequence to the existing sequence so
320   // that the keySequenceChanged() signal is emitted if the new and previous key
321   // sequences are different
322   if(!isRecording())
323     _oldKeySequence = _keySequence;
324
325   _keySequence = seq;
326   _clearButton->setVisible(!_keySequence.isEmpty());
327   doneRecording();
328 }
329
330 void KeySequenceWidget::clear() {
331   setKeySequence(QKeySequence());
332   // setKeySequence() won't emit a signal when we're not recording
333   emit keySequenceChanged(QKeySequence());
334 }
335
336 bool KeySequenceWidget::isKeySequenceAvailable(const QKeySequence &seq) {
337   if(seq.isEmpty())
338     return true;
339
340   // We need to access the root model, not the filtered one
341   for(int cat = 0; cat < _shortcutsModel->rowCount(); cat++) {
342     QModelIndex catIdx = _shortcutsModel->index(cat, 0);
343     for(int r = 0; r < _shortcutsModel->rowCount(catIdx); r++) {
344       QModelIndex actIdx = _shortcutsModel->index(r, 0, catIdx);
345       Q_ASSERT(actIdx.isValid());
346       if(actIdx.data(ShortcutsModel::ActiveShortcutRole).value<QKeySequence>() != seq)
347         continue;
348
349       if(!actIdx.data(ShortcutsModel::IsConfigurableRole).toBool()) {
350         QMessageBox::warning(this, tr("Shortcut Conflict"),
351                              tr("The \"%1\" shortcut is already in use, and cannot be configured.\nPlease choose another one.").arg(seq.toString(QKeySequence::NativeText)),
352                              QMessageBox::Ok);
353         return false;
354       }
355
356       QMessageBox box(QMessageBox::Warning, tr("Shortcut Conflict"),
357                       (tr("The \"%1\" shortcut is ambiguous with the shortcut for the following action:")
358                        + "<br><ul><li>%2</li></ul><br>"
359                        + tr("Do you want to reassign this shortcut to the selected action?")
360                        ).arg(seq.toString(QKeySequence::NativeText), actIdx.data().toString()),
361                       QMessageBox::Cancel, this);
362       box.addButton(tr("Reassign"), QMessageBox::AcceptRole);
363       if(box.exec() == QMessageBox::Cancel)
364         return false;
365
366       _conflictingIndex = actIdx;
367       return true;
368     }
369   }
370   return true;
371 }