source: josm/trunk/src/org/openstreetmap/josm/gui/preferences/shortcut/PrefJPanel.java@ 8510

Last change on this file since 8510 was 8510, checked in by Don-vip, 9 years ago

checkstyle: enable relevant whitespace checks and fix them

  • Property svn:eol-style set to native
File size: 16.5 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.preferences.shortcut;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.Color;
8import java.awt.Component;
9import java.awt.Dimension;
10import java.awt.GridBagConstraints;
11import java.awt.GridBagLayout;
12import java.awt.Insets;
13import java.awt.Toolkit;
14import java.awt.event.KeyEvent;
15import java.lang.reflect.Field;
16import java.util.ArrayList;
17import java.util.LinkedHashMap;
18import java.util.List;
19import java.util.Map;
20import java.util.regex.PatternSyntaxException;
21
22import javax.swing.AbstractAction;
23import javax.swing.BorderFactory;
24import javax.swing.BoxLayout;
25import javax.swing.DefaultComboBoxModel;
26import javax.swing.JCheckBox;
27import javax.swing.JLabel;
28import javax.swing.JPanel;
29import javax.swing.JScrollPane;
30import javax.swing.JTable;
31import javax.swing.KeyStroke;
32import javax.swing.ListSelectionModel;
33import javax.swing.RowFilter;
34import javax.swing.SwingConstants;
35import javax.swing.event.DocumentEvent;
36import javax.swing.event.DocumentListener;
37import javax.swing.event.ListSelectionEvent;
38import javax.swing.event.ListSelectionListener;
39import javax.swing.table.AbstractTableModel;
40import javax.swing.table.DefaultTableCellRenderer;
41import javax.swing.table.TableColumnModel;
42import javax.swing.table.TableModel;
43import javax.swing.table.TableRowSorter;
44
45import org.openstreetmap.josm.Main;
46import org.openstreetmap.josm.gui.widgets.JosmComboBox;
47import org.openstreetmap.josm.gui.widgets.JosmTextField;
48import org.openstreetmap.josm.gui.widgets.SelectAllOnFocusGainedDecorator;
49import org.openstreetmap.josm.tools.Shortcut;
50
51/**
52 * This is the keyboard preferences content.
53 */
54public class PrefJPanel extends JPanel {
55
56 // table of shortcuts
57 private AbstractTableModel model;
58 // this are the display(!) texts for the checkboxes. Let the JVM do the i18n for us <g>.
59 // Ok, there's a real reason for this: The JVM should know best how the keys are labelled
60 // on the physical keyboard. What language pack is installed in JOSM is completely
61 // independent from the keyboard's labelling. But the operation system's locale
62 // usually matches the keyboard. This even works with my English Windows and my German keyboard.
63 private static final String SHIFT = KeyEvent.getKeyModifiersText(KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.SHIFT_DOWN_MASK).getModifiers());
64 private static final String CTRL = KeyEvent.getKeyModifiersText(KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_DOWN_MASK).getModifiers());
65 private static final String ALT = KeyEvent.getKeyModifiersText(KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.ALT_DOWN_MASK).getModifiers());
66 private static final String META = KeyEvent.getKeyModifiersText(KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.META_DOWN_MASK).getModifiers());
67
68 // A list of keys to present the user. Sadly this really is a list of keys Java knows about,
69 // not a list of real physical keys. If someone knows how to get that list?
70 private static Map<Integer, String> keyList = setKeyList();
71
72 private static Map<Integer, String> setKeyList() {
73 Map<Integer, String> list = new LinkedHashMap<>();
74 String unknown = Toolkit.getProperty("AWT.unknown", "Unknown");
75 // Assume all known keys are declared in KeyEvent as "public static int VK_*"
76 for (Field field : KeyEvent.class.getFields()) {
77 if (field.getName().startsWith("VK_")) {
78 try {
79 int i = field.getInt(null);
80 String s = KeyEvent.getKeyText(i);
81 if (s != null && s.length() > 0 && !s.contains(unknown)) {
82 list.put(Integer.valueOf(i), s);
83 }
84 } catch (Exception e) {
85 Main.error(e);
86 }
87 }
88 }
89 list.put(Integer.valueOf(-1), "");
90 return list;
91 }
92
93 private JCheckBox cbAlt = new JCheckBox();
94 private JCheckBox cbCtrl = new JCheckBox();
95 private JCheckBox cbMeta = new JCheckBox();
96 private JCheckBox cbShift = new JCheckBox();
97 private JCheckBox cbDefault = new JCheckBox();
98 private JCheckBox cbDisable = new JCheckBox();
99 private JosmComboBox<String> tfKey = new JosmComboBox<>();
100
101 private JTable shortcutTable = new JTable();
102
103 private JosmTextField filterField = new JosmTextField();
104
105 /** Creates new form prefJPanel */
106 public PrefJPanel() {
107 this.model = new ScListModel();
108 initComponents();
109 }
110
111 /**
112 * Show only shortcuts with descriptions containing given substring
113 * @param substring The substring used to filter
114 */
115 public void filter(String substring) {
116 filterField.setText(substring);
117 }
118
119 private static class ScListModel extends AbstractTableModel {
120 private final String[] columnNames = new String[]{tr("Action"), tr("Shortcut")};
121 private transient List<Shortcut> data;
122
123 /**
124 * Constructs a new {@code ScListModel}.
125 */
126 public ScListModel() {
127 data = Shortcut.listAll();
128 }
129
130 @Override
131 public int getColumnCount() {
132 return columnNames.length;
133 }
134
135 @Override
136 public int getRowCount() {
137 return data.size();
138 }
139
140 @Override
141 public String getColumnName(int col) {
142 return columnNames[col];
143 }
144
145 @Override
146 public Object getValueAt(int row, int col) {
147 return (col == 0) ? data.get(row).getLongText() : data.get(row);
148 }
149 }
150
151 private class ShortcutTableCellRenderer extends DefaultTableCellRenderer {
152
153 private boolean name;
154
155 public ShortcutTableCellRenderer(boolean name) {
156 this.name = name;
157 }
158
159 @Override
160 public Component getTableCellRendererComponent(JTable table, Object value, boolean
161 isSelected, boolean hasFocus, int row, int column) {
162 int row1 = shortcutTable.convertRowIndexToModel(row);
163 Shortcut sc = (Shortcut) model.getValueAt(row1, -1);
164 if (sc == null) return null;
165 JLabel label = (JLabel) super.getTableCellRendererComponent(
166 table, name ? sc.getLongText() : sc.getKeyText(), isSelected, hasFocus, row, column);
167 label.setBackground(Main.pref.getUIColor("Table.background"));
168 if (isSelected) {
169 label.setForeground(Main.pref.getUIColor("Table.foreground"));
170 }
171 if (sc.isAssignedUser()) {
172 label.setBackground(Main.pref.getColor(
173 marktr("Shortcut Background: User"),
174 new Color(200, 255, 200)));
175 } else if (!sc.isAssignedDefault()) {
176 label.setBackground(Main.pref.getColor(
177 marktr("Shortcut Background: Modified"),
178 new Color(255, 255, 200)));
179 }
180 return label;
181 }
182 }
183
184 private void initComponents() {
185 JPanel listPane = new JPanel();
186 JScrollPane listScrollPane = new JScrollPane();
187 JPanel shortcutEditPane = new JPanel();
188
189 CbAction action = new CbAction(this);
190 setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
191 add(buildFilterPanel());
192 listPane.setLayout(new java.awt.GridLayout());
193
194 // This is the list of shortcuts:
195 shortcutTable.setModel(model);
196 shortcutTable.getSelectionModel().addListSelectionListener(new CbAction(this));
197 shortcutTable.setFillsViewportHeight(true);
198 shortcutTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
199 shortcutTable.setAutoCreateRowSorter(true);
200 TableColumnModel mod = shortcutTable.getColumnModel();
201 mod.getColumn(0).setCellRenderer(new ShortcutTableCellRenderer(true));
202 mod.getColumn(1).setCellRenderer(new ShortcutTableCellRenderer(false));
203 listScrollPane.setViewportView(shortcutTable);
204
205 listPane.add(listScrollPane);
206
207 add(listPane);
208
209 // and here follows the edit area. I won't object to someone re-designing it, it looks, um, "minimalistic" ;)
210 shortcutEditPane.setLayout(new java.awt.GridLayout(5, 2));
211
212 cbDefault.setAction(action);
213 cbDefault.setText(tr("Use default"));
214 cbShift.setAction(action);
215 cbShift.setText(SHIFT); // see above for why no tr()
216 cbDisable.setAction(action);
217 cbDisable.setText(tr("Disable"));
218 cbCtrl.setAction(action);
219 cbCtrl.setText(CTRL); // see above for why no tr()
220 cbAlt.setAction(action);
221 cbAlt.setText(ALT); // see above for why no tr()
222 tfKey.setAction(action);
223 tfKey.setModel(new DefaultComboBoxModel<>(keyList.values().toArray(new String[0])));
224 cbMeta.setAction(action);
225 cbMeta.setText(META); // see above for why no tr()
226
227 shortcutEditPane.add(cbDefault);
228 shortcutEditPane.add(new JLabel());
229 shortcutEditPane.add(cbShift);
230 shortcutEditPane.add(cbDisable);
231 shortcutEditPane.add(cbCtrl);
232 shortcutEditPane.add(new JLabel(tr("Key:"), SwingConstants.LEFT));
233 shortcutEditPane.add(cbAlt);
234 shortcutEditPane.add(tfKey);
235 shortcutEditPane.add(cbMeta);
236
237 shortcutEditPane.add(new JLabel(tr("Attention: Use real keyboard keys only!")));
238
239 action.actionPerformed(null); // init checkboxes
240
241 add(shortcutEditPane);
242 }
243
244 private JPanel buildFilterPanel() {
245 // copied from PluginPreference
246 JPanel pnl = new JPanel(new GridBagLayout());
247 pnl.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
248 GridBagConstraints gc = new GridBagConstraints();
249
250 gc.anchor = GridBagConstraints.NORTHWEST;
251 gc.fill = GridBagConstraints.HORIZONTAL;
252 gc.weightx = 0.0;
253 gc.insets = new Insets(0, 0, 0, 5);
254 pnl.add(new JLabel(tr("Search:")), gc);
255
256 gc.gridx = 1;
257 gc.weightx = 1.0;
258 pnl.add(filterField, gc);
259 filterField.setToolTipText(tr("Enter a search expression"));
260 SelectAllOnFocusGainedDecorator.decorate(filterField);
261 filterField.getDocument().addDocumentListener(new FilterFieldAdapter());
262 pnl.setMaximumSize(new Dimension(300, 10));
263 return pnl;
264 }
265
266 private void disableAllModifierCheckboxes() {
267 cbDefault.setEnabled(false);
268 cbDisable.setEnabled(false);
269 cbShift.setEnabled(false);
270 cbCtrl.setEnabled(false);
271 cbAlt.setEnabled(false);
272 cbMeta.setEnabled(false);
273 }
274
275 // this allows to edit shortcuts. it:
276 // * sets the edit controls to the selected shortcut
277 // * enabled/disables the controls as needed
278 // * writes the user's changes to the shortcut
279 // And after I finally had it working, I realized that those two methods
280 // are playing ping-pong (politically correct: table tennis, I know) and
281 // even have some duplicated code. Feel free to refactor, If you have
282 // more expirience with GUI coding than I have.
283 private class CbAction extends AbstractAction implements ListSelectionListener {
284 private PrefJPanel panel;
285
286 public CbAction(PrefJPanel panel) {
287 this.panel = panel;
288 }
289
290 @Override
291 public void valueChanged(ListSelectionEvent e) {
292 ListSelectionModel lsm = panel.shortcutTable.getSelectionModel(); // can't use e here
293 if (!lsm.isSelectionEmpty()) {
294 int row = panel.shortcutTable.convertRowIndexToModel(lsm.getMinSelectionIndex());
295 Shortcut sc = (Shortcut) panel.model.getValueAt(row, -1);
296 panel.cbDefault.setSelected(!sc.isAssignedUser());
297 panel.cbDisable.setSelected(sc.getKeyStroke() == null);
298 panel.cbShift.setSelected(sc.getAssignedModifier() != -1 && (sc.getAssignedModifier() & KeyEvent.SHIFT_DOWN_MASK) != 0);
299 panel.cbCtrl.setSelected(sc.getAssignedModifier() != -1 && (sc.getAssignedModifier() & KeyEvent.CTRL_DOWN_MASK) != 0);
300 panel.cbAlt.setSelected(sc.getAssignedModifier() != -1 && (sc.getAssignedModifier() & KeyEvent.ALT_DOWN_MASK) != 0);
301 panel.cbMeta.setSelected(sc.getAssignedModifier() != -1 && (sc.getAssignedModifier() & KeyEvent.META_DOWN_MASK) != 0);
302 if (sc.getKeyStroke() != null) {
303 tfKey.setSelectedItem(keyList.get(sc.getKeyStroke().getKeyCode()));
304 } else {
305 tfKey.setSelectedItem(keyList.get(-1));
306 }
307 if (!sc.isChangeable()) {
308 disableAllModifierCheckboxes();
309 panel.tfKey.setEnabled(false);
310 } else {
311 panel.cbDefault.setEnabled(true);
312 actionPerformed(null);
313 }
314 model.fireTableRowsUpdated(row, row);
315 } else {
316 panel.disableAllModifierCheckboxes();
317 panel.tfKey.setEnabled(false);
318 }
319 }
320
321 @Override
322 public void actionPerformed(java.awt.event.ActionEvent e) {
323 ListSelectionModel lsm = panel.shortcutTable.getSelectionModel();
324 if (lsm != null && !lsm.isSelectionEmpty()) {
325 if (e != null) { // only if we've been called by a user action
326 int row = panel.shortcutTable.convertRowIndexToModel(lsm.getMinSelectionIndex());
327 Shortcut sc = (Shortcut) panel.model.getValueAt(row, -1);
328 if (panel.cbDisable.isSelected()) {
329 sc.setAssignedModifier(-1);
330 } else if (panel.tfKey.getSelectedItem() == null || "".equals(panel.tfKey.getSelectedItem())) {
331 sc.setAssignedModifier(KeyEvent.VK_CANCEL);
332 } else {
333 sc.setAssignedModifier(
334 (panel.cbShift.isSelected() ? KeyEvent.SHIFT_DOWN_MASK : 0) |
335 (panel.cbCtrl.isSelected() ? KeyEvent.CTRL_DOWN_MASK : 0) |
336 (panel.cbAlt.isSelected() ? KeyEvent.ALT_DOWN_MASK : 0) |
337 (panel.cbMeta.isSelected() ? KeyEvent.META_DOWN_MASK : 0)
338 );
339 for (Map.Entry<Integer, String> entry : keyList.entrySet()) {
340 if (entry.getValue().equals(panel.tfKey.getSelectedItem())) {
341 sc.setAssignedKey(entry.getKey());
342 }
343 }
344 }
345 sc.setAssignedUser(!panel.cbDefault.isSelected());
346 valueChanged(null);
347 }
348 boolean state = !panel.cbDefault.isSelected();
349 panel.cbDisable.setEnabled(state);
350 state = state && !panel.cbDisable.isSelected();
351 panel.cbShift.setEnabled(state);
352 panel.cbCtrl.setEnabled(state);
353 panel.cbAlt.setEnabled(state);
354 panel.cbMeta.setEnabled(state);
355 panel.tfKey.setEnabled(state);
356 } else {
357 panel.disableAllModifierCheckboxes();
358 panel.tfKey.setEnabled(false);
359 }
360 }
361 }
362
363 class FilterFieldAdapter implements DocumentListener {
364 public void filter() {
365 String expr = filterField.getText().trim();
366 if (expr.isEmpty()) {
367 expr = null;
368 }
369 try {
370 final TableRowSorter<? extends TableModel> sorter =
371 (TableRowSorter<? extends TableModel>) shortcutTable.getRowSorter();
372 if (expr == null) {
373 sorter.setRowFilter(null);
374 } else {
375 expr = expr.replace("+", "\\+");
376 // split search string on whitespace, do case-insensitive AND search
377 List<RowFilter<Object, Object>> andFilters = new ArrayList<>();
378 for (String word : expr.split("\\s+")) {
379 andFilters.add(RowFilter.regexFilter("(?i)" + word));
380 }
381 sorter.setRowFilter(RowFilter.andFilter(andFilters));
382 }
383 model.fireTableDataChanged();
384 } catch (PatternSyntaxException | ClassCastException ex) {
385 Main.warn(ex);
386 }
387 }
388
389 @Override
390 public void changedUpdate(DocumentEvent e) {
391 filter();
392 }
393
394 @Override
395 public void insertUpdate(DocumentEvent e) {
396 filter();
397 }
398
399 @Override
400 public void removeUpdate(DocumentEvent e) {
401 filter();
402 }
403 }
404}
Note: See TracBrowser for help on using the repository browser.