/
shortcuts.py
872 lines (743 loc) · 32.7 KB
/
shortcuts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""Shortcut management"""
# Standard library imports
from __future__ import print_function
import re
# Third party imports
from qtpy import PYQT5
from qtpy.compat import from_qvariant, to_qvariant
from qtpy.QtCore import QAbstractTableModel, QModelIndex, Qt, Slot, QEvent
from qtpy.QtGui import QKeySequence, QIcon
from qtpy.QtWidgets import (QAbstractItemView, QApplication, QDialog,
QGridLayout, QHBoxLayout, QLabel,
QLineEdit, QMessageBox, QPushButton, QSpacerItem,
QTableView, QVBoxLayout, QKeySequenceEdit)
# Local imports
from spyder.config.base import _
from spyder.config.manager import CONF
from spyder.preferences.configdialog import GeneralConfigPage
from spyder.utils import icon_manager as ima
from spyder.utils.qthelpers import get_std_icon, create_toolbutton
from spyder.utils.stringmatching import get_search_scores
from spyder.widgets.helperwidgets import (CustomSortFilterProxy,
FinderLineEdit, HelperToolButton,
HTMLDelegate, VALID_FINDER_CHARS)
# Valid shortcut keys
SINGLE_KEYS = ["F{}".format(_i) for _i in range(1, 36)] + ["Del", "Esc"]
EDITOR_SINGLE_KEYS = SINGLE_KEYS + ["Home", "End", "Ins", "Enter",
"Return", "Backspace", "Tab",
"PageUp", "PageDown", "Clear", "Pause",
"Left", "Up", "Right", "Down"]
# Key sequences blacklist for the shortcut editor dialog
BLACKLIST = {}
# Error codes for the shortcut editor dialog
NO_WARNING = 0
SEQUENCE_EMPTY = 1
SEQUENCE_CONFLICT = 2
INVALID_KEY = 3
IN_BLACKLIST = 4
class ShortcutTranslator(QKeySequenceEdit):
"""
A QKeySequenceEdit that is not meant to be shown and is used only
to convert QKeyEvent into QKeySequence. To our knowledge, this is
the only way to do this within the Qt framework, because the code that does
this in Qt is protected. Porting the code to Python would be nearly
impossible because it relies on low level and OS-dependent Qt libraries
that are not public for the most part.
"""
def __init__(self):
super(ShortcutTranslator, self).__init__()
self.hide()
def keyevent_to_keyseq(self, event):
"""Return a QKeySequence representation of the provided QKeyEvent."""
self.keyPressEvent(event)
event.accept()
return self.keySequence()
def keyReleaseEvent(self, event):
"""Qt Override"""
return False
def timerEvent(self, event):
"""Qt Override"""
return False
def event(self, event):
"""Qt Override"""
return False
class ShortcutLineEdit(QLineEdit):
"""QLineEdit that filters its key press and release events."""
def __init__(self, parent):
super(ShortcutLineEdit, self).__init__(parent)
self.setReadOnly(True)
tw = self.fontMetrics().width(
"Ctrl+Shift+Alt+Backspace, Ctrl+Shift+Alt+Backspace")
fw = self.style().pixelMetric(self.style().PM_DefaultFrameWidth)
self.setMinimumWidth(tw + (2 * fw) + 4)
# We need to add 4 to take into account the horizontalMargin of the
# line edit, whose value is hardcoded in qt.
def keyPressEvent(self, e):
"""Qt Override"""
self.parent().keyPressEvent(e)
def keyReleaseEvent(self, e):
"""Qt Override"""
self.parent().keyReleaseEvent(e)
def setText(self, sequence):
"""Qt method extension."""
self.setToolTip(sequence)
super(ShortcutLineEdit, self).setText(sequence)
class ShortcutFinder(FinderLineEdit):
"""Textbox for filtering listed shortcuts in the table."""
def keyPressEvent(self, event):
"""Qt and FilterLineEdit Override."""
key = event.key()
if key in [Qt.Key_Up]:
self._parent.previous_row()
elif key in [Qt.Key_Down]:
self._parent.next_row()
elif key in [Qt.Key_Enter, Qt.Key_Return]:
self._parent.show_editor()
else:
super(ShortcutFinder, self).keyPressEvent(event)
class ShortcutEditor(QDialog):
"""A dialog for entering key sequences."""
def __init__(self, parent, context, name, sequence, shortcuts):
super(ShortcutEditor, self).__init__(parent)
self._parent = parent
self.setWindowFlags(self.windowFlags() &
~Qt.WindowContextHelpButtonHint)
self.context = context
self.name = name
self.shortcuts = shortcuts
self.current_sequence = sequence or _('<None>')
self._qsequences = list()
self.setup()
self.update_warning()
@property
def new_sequence(self):
"""Return a string representation of the new key sequence."""
return ', '.join(self._qsequences)
@property
def new_qsequence(self):
"""Return the QKeySequence object of the new key sequence."""
return QKeySequence(self.new_sequence)
def setup(self):
"""Setup the ShortcutEditor with the provided arguments."""
# Widgets
icon_info = HelperToolButton()
icon_info.setIcon(get_std_icon('MessageBoxInformation'))
layout_icon_info = QVBoxLayout()
layout_icon_info.setContentsMargins(0, 0, 0, 0)
layout_icon_info.setSpacing(0)
layout_icon_info.addWidget(icon_info)
layout_icon_info.addStretch(100)
self.label_info = QLabel()
self.label_info.setText(
_("Press the new shortcut and select 'Ok' to confirm, "
"click 'Cancel' to revert to the previous state, "
"or use 'Clear' to unbind the command from a shortcut."))
self.label_info.setAlignment(Qt.AlignTop | Qt.AlignLeft)
self.label_info.setWordWrap(True)
layout_info = QHBoxLayout()
layout_info.setContentsMargins(0, 0, 0, 0)
layout_info.addLayout(layout_icon_info)
layout_info.addWidget(self.label_info)
layout_info.setStretch(1, 100)
self.label_current_sequence = QLabel(_("Current shortcut:"))
self.text_current_sequence = QLabel(self.current_sequence)
self.label_new_sequence = QLabel(_("New shortcut:"))
self.text_new_sequence = ShortcutLineEdit(self)
self.text_new_sequence.setPlaceholderText(_("Press shortcut."))
self.helper_button = HelperToolButton()
self.helper_button.setIcon(QIcon())
self.label_warning = QLabel()
self.label_warning.setWordWrap(True)
self.label_warning.setAlignment(Qt.AlignTop | Qt.AlignLeft)
self.button_default = QPushButton(_('Default'))
self.button_ok = QPushButton(_('Ok'))
self.button_ok.setEnabled(False)
self.button_clear = QPushButton(_('Clear'))
self.button_cancel = QPushButton(_('Cancel'))
button_box = QHBoxLayout()
button_box.addWidget(self.button_default)
button_box.addStretch(100)
button_box.addWidget(self.button_ok)
button_box.addWidget(self.button_clear)
button_box.addWidget(self.button_cancel)
# New Sequence button box
self.btn_clear_sequence = create_toolbutton(
self, icon=ima.icon('editclear'),
tip=_("Clear all entered key sequences"),
triggered=self.clear_new_sequence)
self.button_back_sequence = create_toolbutton(
self, icon=ima.icon('ArrowBack'),
tip=_("Remove last key sequence entered"),
triggered=self.back_new_sequence)
newseq_btnbar = QHBoxLayout()
newseq_btnbar.setSpacing(0)
newseq_btnbar.setContentsMargins(0, 0, 0, 0)
newseq_btnbar.addWidget(self.button_back_sequence)
newseq_btnbar.addWidget(self.btn_clear_sequence)
# Setup widgets
self.setWindowTitle(_('Shortcut: {0}').format(self.name))
self.helper_button.setToolTip('')
style = """
QToolButton {
margin:1px;
border: 0px solid grey;
padding:0px;
border-radius: 0px;
}"""
self.helper_button.setStyleSheet(style)
icon_info.setToolTip('')
icon_info.setStyleSheet(style)
# Layout
layout_sequence = QGridLayout()
layout_sequence.setContentsMargins(0, 0, 0, 0)
layout_sequence.addLayout(layout_info, 0, 0, 1, 4)
layout_sequence.addItem(QSpacerItem(15, 15), 1, 0, 1, 4)
layout_sequence.addWidget(self.label_current_sequence, 2, 0)
layout_sequence.addWidget(self.text_current_sequence, 2, 2)
layout_sequence.addWidget(self.label_new_sequence, 3, 0)
layout_sequence.addWidget(self.helper_button, 3, 1)
layout_sequence.addWidget(self.text_new_sequence, 3, 2)
layout_sequence.addLayout(newseq_btnbar, 3, 3)
layout_sequence.addWidget(self.label_warning, 4, 2, 1, 2)
layout_sequence.setColumnStretch(2, 100)
layout_sequence.setRowStretch(4, 100)
layout = QVBoxLayout(self)
layout.addLayout(layout_sequence)
layout.addSpacing(10)
layout.addLayout(button_box)
layout.setSizeConstraint(layout.SetFixedSize)
# Signals
self.button_ok.clicked.connect(self.accept_override)
self.button_clear.clicked.connect(self.unbind_shortcut)
self.button_cancel.clicked.connect(self.reject)
self.button_default.clicked.connect(self.set_sequence_to_default)
# Set all widget to no focus so that we can register <Tab> key
# press event.
widgets = (
self.label_warning, self.helper_button, self.text_new_sequence,
self.button_clear, self.button_default, self.button_cancel,
self.button_ok, self.btn_clear_sequence, self.button_back_sequence)
for w in widgets:
w.setFocusPolicy(Qt.NoFocus)
w.clearFocus()
@Slot()
def reject(self):
"""Slot for rejected signal."""
# Added for spyder-ide/spyder#5426. Due to the focusPolicy of
# Qt.NoFocus for the buttons, if the cancel button was clicked without
# first setting focus to the button, it would cause a seg fault crash.
self.button_cancel.setFocus()
super(ShortcutEditor, self).reject()
@Slot()
def accept(self):
"""Slot for accepted signal."""
# Added for spyder-ide/spyder#5426. Due to the focusPolicy of
# Qt.NoFocus for the buttons, if the cancel button was clicked without
# first setting focus to the button, it would cause a seg fault crash.
self.button_ok.setFocus()
super(ShortcutEditor, self).accept()
def event(self, event):
"""Qt method override."""
if event.type() in (QEvent.Shortcut, QEvent.ShortcutOverride):
return True
else:
return super(ShortcutEditor, self).event(event)
def keyPressEvent(self, event):
"""Qt method override."""
event_key = event.key()
if not event_key or event_key == Qt.Key_unknown:
return
if len(self._qsequences) == 4:
# QKeySequence accepts a maximum of 4 different sequences.
return
if event_key in [Qt.Key_Control, Qt.Key_Shift,
Qt.Key_Alt, Qt.Key_Meta]:
# The event corresponds to just and only a special key.
return
translator = ShortcutTranslator()
event_keyseq = translator.keyevent_to_keyseq(event)
event_keystr = event_keyseq.toString(QKeySequence.PortableText)
self._qsequences.append(event_keystr)
self.update_warning()
def check_conflicts(self):
"""Check shortcuts for conflicts."""
conflicts = []
if len(self._qsequences) == 0:
return conflicts
new_qsequence = self.new_qsequence
for shortcut in self.shortcuts:
shortcut_qsequence = QKeySequence.fromString(str(shortcut.key))
if shortcut_qsequence.isEmpty():
continue
if (shortcut.context, shortcut.name) == (self.context, self.name):
continue
if shortcut.context in [self.context, '_'] or self.context == '_':
if (shortcut_qsequence.matches(new_qsequence) or
new_qsequence.matches(shortcut_qsequence)):
conflicts.append(shortcut)
return conflicts
def check_ascii(self):
"""
Check that all characters in the new sequence are ascii or else the
shortcut will not work.
"""
try:
self.new_sequence.encode('ascii')
except UnicodeEncodeError:
return False
else:
return True
def check_singlekey(self):
"""Check if the first sub-sequence of the new key sequence is valid."""
if len(self._qsequences) == 0:
return True
else:
keystr = self._qsequences[0]
valid_single_keys = (EDITOR_SINGLE_KEYS if
self.context == 'editor' else SINGLE_KEYS)
if any((m in keystr for m in ('Ctrl', 'Alt', 'Shift', 'Meta'))):
return True
else:
# This means that the the first subsequence is composed of
# a single key with no modifier.
valid_single_keys = (EDITOR_SINGLE_KEYS if
self.context == 'editor' else SINGLE_KEYS)
if any((k == keystr for k in valid_single_keys)):
return True
else:
return False
def update_warning(self):
"""Update the warning label, buttons state and sequence text."""
new_qsequence = self.new_qsequence
new_sequence = self.new_sequence
self.text_new_sequence.setText(
new_qsequence.toString(QKeySequence.NativeText))
conflicts = self.check_conflicts()
if len(self._qsequences) == 0:
warning = SEQUENCE_EMPTY
tip = ''
icon = QIcon()
elif conflicts:
warning = SEQUENCE_CONFLICT
template = '<p style="margin-bottom: 0.3em">{0}</p>{1}{2}'
tip_title = _('This key sequence conflicts with:')
tip_body = ''
for s in conflicts:
tip_body += ' ' * 2
tip_body += ' - {0}: <b>{1}</b><br>'.format(s.context, s.name)
tip_body += '<br>'
if len(conflicts) == 1:
tip_override = _("Press 'Ok' to unbind it and assign it to")
else:
tip_override = _("Press 'Ok' to unbind them and assign it to")
tip_override += ' <b>{}</b>.'.format(self.name)
tip = template.format(tip_title, tip_body, tip_override)
icon = get_std_icon('MessageBoxWarning')
elif new_sequence in BLACKLIST:
warning = IN_BLACKLIST
tip = _('This key sequence is forbidden.')
icon = get_std_icon('MessageBoxWarning')
elif self.check_singlekey() is False or self.check_ascii() is False:
warning = INVALID_KEY
tip = _('This key sequence is invalid.')
icon = get_std_icon('MessageBoxWarning')
else:
warning = NO_WARNING
tip = _('This key sequence is valid.')
icon = get_std_icon('DialogApplyButton')
self.warning = warning
self.conflicts = conflicts
self.helper_button.setIcon(icon)
self.button_ok.setEnabled(
self.warning in [NO_WARNING, SEQUENCE_CONFLICT])
self.label_warning.setText(tip)
def set_sequence_from_str(self, sequence):
"""
This is a convenience method to set the new QKeySequence of the
shortcut editor from a string.
"""
self._qsequences = [QKeySequence(s) for s in sequence.split(', ')]
self.update_warning()
def set_sequence_to_default(self):
"""Set the new sequence to the default value defined in the config."""
sequence = CONF.get_default(
'shortcuts', "{}/{}".format(self.context, self.name))
self._qsequences = sequence.split(', ')
self.update_warning()
def back_new_sequence(self):
"""Remove the last subsequence from the sequence compound."""
self._qsequences = self._qsequences[:-1]
self.update_warning()
def clear_new_sequence(self):
"""Clear the new sequence."""
self._qsequences = []
self.update_warning()
def unbind_shortcut(self):
"""Unbind the shortcut."""
self._qsequences = []
self.accept()
def accept_override(self):
"""Unbind all conflicted shortcuts, and accept the new one"""
conflicts = self.check_conflicts()
if conflicts:
for shortcut in conflicts:
shortcut.key = ''
self.accept()
class Shortcut(object):
"""Shortcut convenience class for holding shortcut context, name,
original ordering index, key sequence for the shortcut and localized text.
"""
def __init__(self, context, name, key=None):
self.index = 0 # Sorted index. Populated when loading shortcuts
self.context = context
self.name = name
self.key = key
def __str__(self):
return "{0}/{1}: {2}".format(self.context, self.name, self.key)
def load(self):
self.key = CONF.get_shortcut(self.context, self.name)
def save(self):
CONF.set_shortcut(self.context, self.name, self.key)
CONTEXT, NAME, SEQUENCE, SEARCH_SCORE = [0, 1, 2, 3]
class ShortcutsModel(QAbstractTableModel):
def __init__(self, parent, text_color=None, text_color_highlight=None):
QAbstractTableModel.__init__(self)
self._parent = parent
self.shortcuts = []
self.scores = []
self.rich_text = []
self.normal_text = []
self.letters = ''
self.label = QLabel()
self.widths = []
# Needed to compensate for the HTMLDelegate color selection unawarness
palette = parent.palette()
if text_color is None:
self.text_color = palette.text().color().name()
else:
self.text_color = text_color
if text_color_highlight is None:
self.text_color_highlight = \
palette.highlightedText().color().name()
else:
self.text_color_highlight = text_color_highlight
def current_index(self):
"""Get the currently selected index in the parent table view."""
i = self._parent.proxy_model.mapToSource(self._parent.currentIndex())
return i
def sortByName(self):
"""Qt Override."""
self.shortcuts = sorted(self.shortcuts,
key=lambda x: x.context+'/'+x.name)
self.reset()
def flags(self, index):
"""Qt Override."""
if not index.isValid():
return Qt.ItemIsEnabled
return Qt.ItemFlags(int(QAbstractTableModel.flags(self, index)))
def data(self, index, role=Qt.DisplayRole):
"""Qt Override."""
row = index.row()
if not index.isValid() or not (0 <= row < len(self.shortcuts)):
return to_qvariant()
shortcut = self.shortcuts[row]
key = shortcut.key
column = index.column()
if role == Qt.DisplayRole:
if column == CONTEXT:
return to_qvariant(shortcut.context)
elif column == NAME:
color = self.text_color
if self._parent == QApplication.focusWidget():
if self.current_index().row() == row:
color = self.text_color_highlight
else:
color = self.text_color
text = self.rich_text[row]
text = '<p style="color:{0}">{1}</p>'.format(color, text)
return to_qvariant(text)
elif column == SEQUENCE:
text = QKeySequence(key).toString(QKeySequence.NativeText)
return to_qvariant(text)
elif column == SEARCH_SCORE:
# Treating search scores as a table column simplifies the
# sorting once a score for a specific string in the finder
# has been defined. This column however should always remain
# hidden.
return to_qvariant(self.scores[row])
elif role == Qt.TextAlignmentRole:
return to_qvariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
return to_qvariant()
def headerData(self, section, orientation, role=Qt.DisplayRole):
"""Qt Override."""
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:
return to_qvariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
return to_qvariant(int(Qt.AlignRight | Qt.AlignVCenter))
if role != Qt.DisplayRole:
return to_qvariant()
if orientation == Qt.Horizontal:
if section == CONTEXT:
return to_qvariant(_("Context"))
elif section == NAME:
return to_qvariant(_("Name"))
elif section == SEQUENCE:
return to_qvariant(_("Shortcut"))
elif section == SEARCH_SCORE:
return to_qvariant(_("Score"))
return to_qvariant()
def rowCount(self, index=QModelIndex()):
"""Qt Override."""
return len(self.shortcuts)
def columnCount(self, index=QModelIndex()):
"""Qt Override."""
return 4
def setData(self, index, value, role=Qt.EditRole):
"""Qt Override."""
if index.isValid() and 0 <= index.row() < len(self.shortcuts):
shortcut = self.shortcuts[index.row()]
column = index.column()
text = from_qvariant(value, str)
if column == SEQUENCE:
shortcut.key = text
self.dataChanged.emit(index, index)
return True
return False
def update_search_letters(self, text):
"""Update search letters with text input in search box."""
self.letters = text
names = [shortcut.name for shortcut in self.shortcuts]
results = get_search_scores(text, names, template='<b>{0}</b>')
self.normal_text, self.rich_text, self.scores = zip(*results)
self.reset()
def update_active_row(self):
"""Update active row to update color in selected text."""
self.data(self.current_index())
def row(self, row_num):
"""Get row based on model index. Needed for the custom proxy model."""
return self.shortcuts[row_num]
def reset(self):
""""Reset model to take into account new search letters."""
self.beginResetModel()
self.endResetModel()
class ShortcutsTable(QTableView):
def __init__(self,
parent=None, text_color=None, text_color_highlight=None):
QTableView.__init__(self, parent)
self._parent = parent
self.finder = None
self.source_model = ShortcutsModel(
self,
text_color=text_color,
text_color_highlight=text_color_highlight)
self.proxy_model = CustomSortFilterProxy(self)
self.last_regex = ''
self.proxy_model.setSourceModel(self.source_model)
self.proxy_model.setDynamicSortFilter(True)
self.proxy_model.setFilterKeyColumn(NAME)
self.proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
self.setModel(self.proxy_model)
self.hideColumn(SEARCH_SCORE)
self.setItemDelegateForColumn(NAME, HTMLDelegate(self, margin=9))
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.setSortingEnabled(True)
self.setEditTriggers(QAbstractItemView.AllEditTriggers)
self.selectionModel().selectionChanged.connect(self.selection)
self.verticalHeader().hide()
self.load_shortcuts()
def focusOutEvent(self, e):
"""Qt Override."""
self.source_model.update_active_row()
super(ShortcutsTable, self).focusOutEvent(e)
def focusInEvent(self, e):
"""Qt Override."""
super(ShortcutsTable, self).focusInEvent(e)
self.selectRow(self.currentIndex().row())
def selection(self, index):
"""Update selected row."""
self.update()
self.isActiveWindow()
def adjust_cells(self):
"""Adjust column size based on contents."""
self.resizeColumnsToContents()
fm = self.horizontalHeader().fontMetrics()
names = [fm.width(s.name + ' '*9) for s in self.source_model.shortcuts]
self.setColumnWidth(NAME, max(names))
self.horizontalHeader().setStretchLastSection(True)
def load_shortcuts(self):
"""Load shortcuts and assign to table model."""
shortcuts = []
for context, name, keystr in CONF.iter_shortcuts():
shortcut = Shortcut(context, name, keystr)
shortcuts.append(shortcut)
shortcuts = sorted(shortcuts, key=lambda x: x.context+x.name)
# Store the original order of shortcuts
for i, shortcut in enumerate(shortcuts):
shortcut.index = i
self.source_model.shortcuts = shortcuts
self.source_model.scores = [0]*len(shortcuts)
self.source_model.rich_text = [s.name for s in shortcuts]
self.source_model.reset()
self.adjust_cells()
self.sortByColumn(CONTEXT, Qt.AscendingOrder)
def check_shortcuts(self):
"""Check shortcuts for conflicts."""
conflicts = []
for index, sh1 in enumerate(self.source_model.shortcuts):
if index == len(self.source_model.shortcuts)-1:
break
if str(sh1.key) == '':
continue
for sh2 in self.source_model.shortcuts[index+1:]:
if sh2 is sh1:
continue
if str(sh2.key) == str(sh1.key) \
and (sh1.context == sh2.context or sh1.context == '_' or
sh2.context == '_'):
conflicts.append((sh1, sh2))
if conflicts:
self.parent().show_this_page.emit()
cstr = "\n".join(['%s <---> %s' % (sh1, sh2)
for sh1, sh2 in conflicts])
QMessageBox.warning(self, _("Conflicts"),
_("The following conflicts have been "
"detected:")+"\n"+cstr, QMessageBox.Ok)
def save_shortcuts(self):
"""Save shortcuts from table model."""
self.check_shortcuts()
for shortcut in self.source_model.shortcuts:
shortcut.save()
def show_editor(self):
"""Create, setup and display the shortcut editor dialog."""
index = self.proxy_model.mapToSource(self.currentIndex())
row, column = index.row(), index.column()
shortcuts = self.source_model.shortcuts
context = shortcuts[row].context
name = shortcuts[row].name
sequence_index = self.source_model.index(row, SEQUENCE)
sequence = sequence_index.data()
dialog = ShortcutEditor(self, context, name, sequence, shortcuts)
if dialog.exec_():
new_sequence = dialog.new_sequence
self.source_model.setData(sequence_index, new_sequence)
def set_regex(self, regex=None, reset=False):
"""Update the regex text for the shortcut finder."""
if reset:
text = ''
else:
text = self.finder.text().replace(' ', '').lower()
self.proxy_model.set_filter(text)
self.source_model.update_search_letters(text)
self.sortByColumn(SEARCH_SCORE, Qt.AscendingOrder)
if self.last_regex != regex:
self.selectRow(0)
self.last_regex = regex
def next_row(self):
"""Move to next row from currently selected row."""
row = self.currentIndex().row()
rows = self.proxy_model.rowCount()
if row + 1 == rows:
row = -1
self.selectRow(row + 1)
def previous_row(self):
"""Move to previous row from currently selected row."""
row = self.currentIndex().row()
rows = self.proxy_model.rowCount()
if row == 0:
row = rows
self.selectRow(row - 1)
def keyPressEvent(self, event):
"""Qt Override."""
key = event.key()
if key in [Qt.Key_Enter, Qt.Key_Return]:
self.show_editor()
elif key in [Qt.Key_Tab]:
self.finder.setFocus()
elif key in [Qt.Key_Backtab]:
self.parent().reset_btn.setFocus()
elif key in [Qt.Key_Up, Qt.Key_Down, Qt.Key_Left, Qt.Key_Right]:
super(ShortcutsTable, self).keyPressEvent(event)
elif key not in [Qt.Key_Escape, Qt.Key_Space]:
text = event.text()
if text:
if re.search(VALID_FINDER_CHARS, text) is not None:
self.finder.setFocus()
self.finder.set_text(text)
elif key in [Qt.Key_Escape]:
self.finder.keyPressEvent(event)
def mouseDoubleClickEvent(self, event):
"""Qt Override."""
self.show_editor()
self.update()
class ShortcutsConfigPage(GeneralConfigPage):
CONF_SECTION = "shortcuts"
NAME = _("Keyboard shortcuts")
def setup_page(self):
self.ICON = ima.icon('keyboard')
# Widgets
self.table = ShortcutsTable(self, text_color=ima.MAIN_FG_COLOR)
self.finder = ShortcutFinder(self.table, self.table.set_regex)
self.table.finder = self.finder
self.table.finder.setPlaceholderText(
_("Search for a shortcut in the table above"))
self.label_finder = QLabel(_('Search: '))
self.reset_btn = QPushButton(_("Reset to default values"))
self.top_label = QLabel(
_("Here you can browse the list of all available shortcuts in "
"Spyder. You can also customize them by double-clicking on any "
"entry in this table."))
self.top_label.setWordWrap(True)
# Layout
hlayout = QHBoxLayout()
vlayout = QVBoxLayout()
vlayout.addWidget(self.top_label)
hlayout.addWidget(self.label_finder)
hlayout.addWidget(self.finder)
vlayout.addWidget(self.table)
vlayout.addLayout(hlayout)
vlayout.addWidget(self.reset_btn)
self.setLayout(vlayout)
self.setTabOrder(self.table, self.finder)
self.setTabOrder(self.finder, self.reset_btn)
# Signals and slots
if PYQT5:
# Qt5 'dataChanged' has 3 parameters
self.table.proxy_model.dataChanged.connect(
lambda i1, i2, roles, opt='': self.has_been_modified(opt))
else:
self.table.proxy_model.dataChanged.connect(
lambda i1, i2, opt='': self.has_been_modified(opt))
self.reset_btn.clicked.connect(self.reset_to_default)
def check_settings(self):
self.table.check_shortcuts()
def reset_to_default(self):
"""Reset to default values of the shortcuts making a confirmation."""
reset = QMessageBox.warning(self, _("Shortcuts reset"),
_("Do you want to reset "
"to default values?"),
QMessageBox.Yes | QMessageBox.No)
if reset == QMessageBox.No:
return
CONF.reset_shortcuts()
self.main.apply_shortcuts()
self.table.load_shortcuts()
self.load_from_conf()
self.set_modified(False)
def apply_settings(self, options):
self.table.save_shortcuts()
self.main.apply_shortcuts()
def test():
from spyder.utils.qthelpers import qapplication
app = qapplication()
table = ShortcutsTable()
table.show()
app.exec_()
table.check_shortcuts()
if __name__ == '__main__':
test()