source: josm/trunk/src/org/openstreetmap/josm/gui/dialogs/properties/TagEditHelper.java@ 9260

Last change on this file since 9260 was 9260, checked in by simon04, 8 years ago

Shortcuts: fixups for r9258, r9259

  • Property svn:eol-style set to native
File size: 37.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.dialogs.properties;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.awt.BorderLayout;
8import java.awt.Component;
9import java.awt.Container;
10import java.awt.Cursor;
11import java.awt.Dimension;
12import java.awt.FlowLayout;
13import java.awt.Font;
14import java.awt.GridBagConstraints;
15import java.awt.GridBagLayout;
16import java.awt.Toolkit;
17import java.awt.datatransfer.Clipboard;
18import java.awt.datatransfer.Transferable;
19import java.awt.event.ActionEvent;
20import java.awt.event.ActionListener;
21import java.awt.event.FocusAdapter;
22import java.awt.event.FocusEvent;
23import java.awt.event.InputEvent;
24import java.awt.event.KeyEvent;
25import java.awt.event.MouseAdapter;
26import java.awt.event.MouseEvent;
27import java.awt.event.WindowAdapter;
28import java.awt.event.WindowEvent;
29import java.awt.image.BufferedImage;
30import java.text.Normalizer;
31import java.util.ArrayList;
32import java.util.Arrays;
33import java.util.Collection;
34import java.util.Collections;
35import java.util.Comparator;
36import java.util.HashMap;
37import java.util.Iterator;
38import java.util.LinkedHashMap;
39import java.util.LinkedList;
40import java.util.List;
41import java.util.Map;
42
43import javax.swing.AbstractAction;
44import javax.swing.Action;
45import javax.swing.Box;
46import javax.swing.DefaultListCellRenderer;
47import javax.swing.ImageIcon;
48import javax.swing.JCheckBoxMenuItem;
49import javax.swing.JComponent;
50import javax.swing.JLabel;
51import javax.swing.JList;
52import javax.swing.JOptionPane;
53import javax.swing.JPanel;
54import javax.swing.JPopupMenu;
55import javax.swing.JTable;
56import javax.swing.KeyStroke;
57import javax.swing.ListCellRenderer;
58import javax.swing.table.DefaultTableModel;
59import javax.swing.text.JTextComponent;
60
61import org.openstreetmap.josm.Main;
62import org.openstreetmap.josm.actions.JosmAction;
63import org.openstreetmap.josm.command.ChangePropertyCommand;
64import org.openstreetmap.josm.command.Command;
65import org.openstreetmap.josm.command.SequenceCommand;
66import org.openstreetmap.josm.data.osm.OsmPrimitive;
67import org.openstreetmap.josm.data.osm.Tag;
68import org.openstreetmap.josm.data.preferences.BooleanProperty;
69import org.openstreetmap.josm.data.preferences.IntegerProperty;
70import org.openstreetmap.josm.gui.ExtendedDialog;
71import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
72import org.openstreetmap.josm.gui.tagging.ac.AutoCompletingComboBox;
73import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionListItem;
74import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionManager;
75import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;
76import org.openstreetmap.josm.gui.util.GuiHelper;
77import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
78import org.openstreetmap.josm.io.XmlWriter;
79import org.openstreetmap.josm.tools.GBC;
80import org.openstreetmap.josm.tools.Shortcut;
81import org.openstreetmap.josm.tools.Utils;
82import org.openstreetmap.josm.tools.WindowGeometry;
83
84/**
85 * Class that helps PropertiesDialog add and edit tag values.
86 * @since 5633
87 */
88class TagEditHelper {
89 private final JTable tagTable;
90 private final DefaultTableModel tagData;
91 private final Map<String, Map<String, Integer>> valueCount;
92
93 // Selection that we are editing by using both dialogs
94 private Collection<OsmPrimitive> sel;
95
96 private String changedKey;
97 private String objKey;
98
99 private final Comparator<AutoCompletionListItem> defaultACItemComparator = new Comparator<AutoCompletionListItem>() {
100 @Override
101 public int compare(AutoCompletionListItem o1, AutoCompletionListItem o2) {
102 return String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());
103 }
104 };
105
106 private String lastAddKey;
107 private String lastAddValue;
108
109 public static final int DEFAULT_LRU_TAGS_NUMBER = 5;
110 public static final int MAX_LRU_TAGS_NUMBER = 30;
111
112 // LRU cache for recently added tags (http://java-planet.blogspot.com/2005/08/how-to-set-up-simple-lru-cache-using.html)
113 private final Map<Tag, Void> recentTags = new LinkedHashMap<Tag, Void>(MAX_LRU_TAGS_NUMBER+1, 1.1f, true) {
114 @Override
115 protected boolean removeEldestEntry(Map.Entry<Tag, Void> eldest) {
116 return size() > MAX_LRU_TAGS_NUMBER;
117 }
118 };
119
120 TagEditHelper(JTable tagTable, DefaultTableModel propertyData, Map<String, Map<String, Integer>> valueCount) {
121 this.tagTable = tagTable;
122 this.tagData = propertyData;
123 this.valueCount = valueCount;
124 }
125
126 public final String getDataKey(int viewRow) {
127 return tagData.getValueAt(tagTable.convertRowIndexToModel(viewRow), 0).toString();
128 }
129
130 @SuppressWarnings("unchecked")
131 public final Map<String, Integer> getDataValues(int viewRow) {
132 return (Map<String, Integer>) tagData.getValueAt(tagTable.convertRowIndexToModel(viewRow), 1);
133 }
134
135 /**
136 * Open the add selection dialog and add a new key/value to the table (and
137 * to the dataset, of course).
138 */
139 public void addTag() {
140 changedKey = null;
141 sel = Main.main.getInProgressSelection();
142 if (sel == null || sel.isEmpty()) return;
143
144 final AddTagsDialog addDialog = new AddTagsDialog();
145
146 addDialog.showDialog();
147
148 addDialog.destroyActions();
149 if (addDialog.getValue() == 1)
150 addDialog.performTagAdding();
151 else
152 addDialog.undoAllTagsAdding();
153 }
154
155 /**
156 * Edit the value in the tags table row.
157 * @param row The row of the table from which the value is edited.
158 * @param focusOnKey Determines if the initial focus should be set on key instead of value
159 * @since 5653
160 */
161 public void editTag(final int row, boolean focusOnKey) {
162 changedKey = null;
163 sel = Main.main.getInProgressSelection();
164 if (sel == null || sel.isEmpty()) return;
165
166 String key = getDataKey(row);
167 objKey = key;
168
169 final EditTagDialog editDialog = new EditTagDialog(key, getDataValues(row), focusOnKey);
170 editDialog.showDialog();
171 if (editDialog.getValue() != 1) return;
172 editDialog.performTagEdit();
173 }
174
175 /**
176 * If during last editProperty call user changed the key name, this key will be returned
177 * Elsewhere, returns null.
178 * @return The modified key, or {@code null}
179 */
180 public String getChangedKey() {
181 return changedKey;
182 }
183
184 public void resetChangedKey() {
185 changedKey = null;
186 }
187
188 /**
189 * For a given key k, return a list of keys which are used as keys for
190 * auto-completing values to increase the search space.
191 * @param key the key k
192 * @return a list of keys
193 */
194 private static List<String> getAutocompletionKeys(String key) {
195 if ("name".equals(key) || "addr:street".equals(key))
196 return Arrays.asList("addr:street", "name");
197 else
198 return Arrays.asList(key);
199 }
200
201 /**
202 * Load recently used tags from preferences if needed.
203 */
204 public void loadTagsIfNeeded() {
205 if (PROPERTY_REMEMBER_TAGS.get() && recentTags.isEmpty()) {
206 recentTags.clear();
207 Collection<String> c = Main.pref.getCollection("properties.recent-tags");
208 Iterator<String> it = c.iterator();
209 String key, value;
210 while (it.hasNext()) {
211 key = it.next();
212 value = it.next();
213 recentTags.put(new Tag(key, value), null);
214 }
215 }
216 }
217
218 /**
219 * Store recently used tags in preferences if needed.
220 */
221 public void saveTagsIfNeeded() {
222 if (PROPERTY_REMEMBER_TAGS.get() && !recentTags.isEmpty()) {
223 List<String> c = new ArrayList<>(recentTags.size()*2);
224 for (Tag t: recentTags.keySet()) {
225 c.add(t.getKey());
226 c.add(t.getValue());
227 }
228 Main.pref.putCollection("properties.recent-tags", c);
229 }
230 }
231
232 /**
233 * Warns user about a key being overwritten.
234 * @param action The action done by the user. Must state what key is changed
235 * @param togglePref The preference to save the checkbox state to
236 * @return {@code true} if the user accepts to overwrite key, {@code false} otherwise
237 */
238 private static boolean warnOverwriteKey(String action, String togglePref) {
239 ExtendedDialog ed = new ExtendedDialog(
240 Main.parent,
241 tr("Overwrite key"),
242 new String[]{tr("Replace"), tr("Cancel")});
243 ed.setButtonIcons(new String[]{"purge", "cancel"});
244 ed.setContent(action+'\n'+ tr("The new key is already used, overwrite values?"));
245 ed.setCancelButton(2);
246 ed.toggleEnable(togglePref);
247 ed.showDialog();
248
249 return ed.getValue() == 1;
250 }
251
252 public final class EditTagDialog extends AbstractTagsDialog {
253 private final String key;
254 private final transient Map<String, Integer> m;
255
256 private final transient Comparator<AutoCompletionListItem> usedValuesAwareComparator = new Comparator<AutoCompletionListItem>() {
257 @Override
258 public int compare(AutoCompletionListItem o1, AutoCompletionListItem o2) {
259 boolean c1 = m.containsKey(o1.getValue());
260 boolean c2 = m.containsKey(o2.getValue());
261 if (c1 == c2)
262 return String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());
263 else if (c1)
264 return -1;
265 else
266 return +1;
267 }
268 };
269
270 private final transient ListCellRenderer<AutoCompletionListItem> cellRenderer = new ListCellRenderer<AutoCompletionListItem>() {
271 private final DefaultListCellRenderer def = new DefaultListCellRenderer();
272 @Override
273 public Component getListCellRendererComponent(JList<? extends AutoCompletionListItem> list,
274 AutoCompletionListItem value, int index, boolean isSelected, boolean cellHasFocus) {
275 Component c = def.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
276 if (c instanceof JLabel) {
277 String str = value.getValue();
278 if (valueCount.containsKey(objKey)) {
279 Map<String, Integer> m = valueCount.get(objKey);
280 if (m.containsKey(str)) {
281 str = tr("{0} ({1})", str, m.get(str));
282 c.setFont(c.getFont().deriveFont(Font.ITALIC + Font.BOLD));
283 }
284 }
285 ((JLabel) c).setText(str);
286 }
287 return c;
288 }
289 };
290
291 private EditTagDialog(String key, Map<String, Integer> map, final boolean initialFocusOnKey) {
292 super(Main.parent, trn("Change value?", "Change values?", map.size()), new String[] {tr("OK"), tr("Cancel")});
293 setButtonIcons(new String[] {"ok", "cancel"});
294 setCancelButton(2);
295 configureContextsensitiveHelp("/Dialog/EditValue", true /* show help button */);
296 this.key = key;
297 this.m = map;
298
299 JPanel mainPanel = new JPanel(new BorderLayout());
300
301 String msg = "<html>"+trn("This will change {0} object.",
302 "This will change up to {0} objects.", sel.size(), sel.size())
303 +"<br><br>("+tr("An empty value deletes the tag.", key)+")</html>";
304
305 mainPanel.add(new JLabel(msg), BorderLayout.NORTH);
306
307 JPanel p = new JPanel(new GridBagLayout());
308 mainPanel.add(p, BorderLayout.CENTER);
309
310 AutoCompletionManager autocomplete = Main.main.getEditLayer().data.getAutoCompletionManager();
311 List<AutoCompletionListItem> keyList = autocomplete.getKeys();
312 Collections.sort(keyList, defaultACItemComparator);
313
314 keys = new AutoCompletingComboBox(key);
315 keys.setPossibleACItems(keyList);
316 keys.setEditable(true);
317 keys.setSelectedItem(key);
318
319 p.add(Box.createVerticalStrut(5), GBC.eol());
320 p.add(new JLabel(tr("Key")), GBC.std());
321 p.add(Box.createHorizontalStrut(10), GBC.std());
322 p.add(keys, GBC.eol().fill(GBC.HORIZONTAL));
323
324 List<AutoCompletionListItem> valueList = autocomplete.getValues(getAutocompletionKeys(key));
325 Collections.sort(valueList, usedValuesAwareComparator);
326
327 final String selection = m.size() != 1 ? tr("<different>") : m.entrySet().iterator().next().getKey();
328
329 values = new AutoCompletingComboBox(selection);
330 values.setRenderer(cellRenderer);
331
332 values.setEditable(true);
333 values.setPossibleACItems(valueList);
334 values.setSelectedItem(selection);
335 values.getEditor().setItem(selection);
336 p.add(Box.createVerticalStrut(5), GBC.eol());
337 p.add(new JLabel(tr("Value")), GBC.std());
338 p.add(Box.createHorizontalStrut(10), GBC.std());
339 p.add(values, GBC.eol().fill(GBC.HORIZONTAL));
340 values.getEditor().addActionListener(new ActionListener() {
341 @Override
342 public void actionPerformed(ActionEvent e) {
343 buttonAction(0, null); // emulate OK button click
344 }
345 });
346 addFocusAdapter(autocomplete, usedValuesAwareComparator);
347
348 setContent(mainPanel, false);
349
350 addWindowListener(new WindowAdapter() {
351 @Override
352 public void windowOpened(WindowEvent e) {
353 if (initialFocusOnKey) {
354 selectKeysComboBox();
355 } else {
356 selectValuesCombobox();
357 }
358 }
359 });
360 }
361
362 /**
363 * Edit tags of multiple selected objects according to selected ComboBox values
364 * If value == "", tag will be deleted
365 * Confirmations may be needed.
366 */
367 private void performTagEdit() {
368 String value = Tag.removeWhiteSpaces(values.getEditor().getItem().toString());
369 value = Normalizer.normalize(value, java.text.Normalizer.Form.NFC);
370 if (value.isEmpty()) {
371 value = null; // delete the key
372 }
373 String newkey = Tag.removeWhiteSpaces(keys.getEditor().getItem().toString());
374 newkey = Normalizer.normalize(newkey, java.text.Normalizer.Form.NFC);
375 if (newkey.isEmpty()) {
376 newkey = key;
377 value = null; // delete the key instead
378 }
379 if (key.equals(newkey) && tr("<different>").equals(value))
380 return;
381 if (key.equals(newkey) || value == null) {
382 Main.main.undoRedo.add(new ChangePropertyCommand(sel, newkey, value));
383 AutoCompletionManager.rememberUserInput(newkey, value, true);
384 } else {
385 for (OsmPrimitive osm: sel) {
386 if (osm.get(newkey) != null) {
387 if (!warnOverwriteKey(tr("You changed the key from ''{0}'' to ''{1}''.", key, newkey),
388 "overwriteEditKey"))
389 return;
390 break;
391 }
392 }
393 Collection<Command> commands = new ArrayList<>();
394 commands.add(new ChangePropertyCommand(sel, key, null));
395 if (value.equals(tr("<different>"))) {
396 Map<String, List<OsmPrimitive>> map = new HashMap<>();
397 for (OsmPrimitive osm: sel) {
398 String val = osm.get(key);
399 if (val != null) {
400 if (map.containsKey(val)) {
401 map.get(val).add(osm);
402 } else {
403 List<OsmPrimitive> v = new ArrayList<>();
404 v.add(osm);
405 map.put(val, v);
406 }
407 }
408 }
409 for (Map.Entry<String, List<OsmPrimitive>> e: map.entrySet()) {
410 commands.add(new ChangePropertyCommand(e.getValue(), newkey, e.getKey()));
411 }
412 } else {
413 commands.add(new ChangePropertyCommand(sel, newkey, value));
414 AutoCompletionManager.rememberUserInput(newkey, value, false);
415 }
416 Main.main.undoRedo.add(new SequenceCommand(
417 trn("Change properties of up to {0} object",
418 "Change properties of up to {0} objects", sel.size(), sel.size()),
419 commands));
420 }
421
422 changedKey = newkey;
423 }
424 }
425
426 public static final BooleanProperty PROPERTY_FIX_TAG_LOCALE = new BooleanProperty("properties.fix-tag-combobox-locale", false);
427 public static final BooleanProperty PROPERTY_REMEMBER_TAGS = new BooleanProperty("properties.remember-recently-added-tags", true);
428 public static final IntegerProperty PROPERTY_RECENT_TAGS_NUMBER = new IntegerProperty("properties.recently-added-tags",
429 DEFAULT_LRU_TAGS_NUMBER);
430
431 abstract class AbstractTagsDialog extends ExtendedDialog {
432 protected AutoCompletingComboBox keys;
433 protected AutoCompletingComboBox values;
434 protected Component componentUnderMouse;
435
436 AbstractTagsDialog(Component parent, String title, String[] buttonTexts) {
437 super(parent, title, buttonTexts);
438 addMouseListener(new PopupMenuLauncher(popupMenu));
439 }
440
441 @Override
442 public void setupDialog() {
443 super.setupDialog();
444 final Dimension size = getSize();
445 // Set resizable only in width
446 setMinimumSize(size);
447 setPreferredSize(size);
448 // setMaximumSize does not work, and never worked, but still it seems not to bother Oracle to fix this 10-year-old bug
449 // https://bugs.openjdk.java.net/browse/JDK-6200438
450 // https://bugs.openjdk.java.net/browse/JDK-6464548
451
452 setRememberWindowGeometry(getClass().getName() + ".geometry",
453 WindowGeometry.centerInWindow(Main.parent, size));
454 }
455
456 @Override
457 public void setVisible(boolean visible) {
458 // Do not want dialog to be resizable in height, as its size may increase each time because of the recently added tags
459 // So need to modify the stored geometry (size part only) in order to use the automatic positioning mechanism
460 if (visible) {
461 WindowGeometry geometry = initWindowGeometry();
462 Dimension storedSize = geometry.getSize();
463 Dimension size = getSize();
464 if (!storedSize.equals(size)) {
465 if (storedSize.width < size.width) {
466 storedSize.width = size.width;
467 }
468 if (storedSize.height != size.height) {
469 storedSize.height = size.height;
470 }
471 rememberWindowGeometry(geometry);
472 }
473 keys.setFixedLocale(PROPERTY_FIX_TAG_LOCALE.get());
474 }
475 super.setVisible(visible);
476 }
477
478 private void selectACComboBoxSavingUnixBuffer(AutoCompletingComboBox cb) {
479 // select combobox with saving unix system selection (middle mouse paste)
480 Clipboard sysSel = Toolkit.getDefaultToolkit().getSystemSelection();
481 if (sysSel != null) {
482 Transferable old = Utils.getTransferableContent(sysSel);
483 cb.requestFocusInWindow();
484 cb.getEditor().selectAll();
485 sysSel.setContents(old, null);
486 } else {
487 cb.requestFocusInWindow();
488 cb.getEditor().selectAll();
489 }
490 }
491
492 public void selectKeysComboBox() {
493 selectACComboBoxSavingUnixBuffer(keys);
494 }
495
496 public void selectValuesCombobox() {
497 selectACComboBoxSavingUnixBuffer(values);
498 }
499
500 /**
501 * Create a focus handling adapter and apply in to the editor component of value
502 * autocompletion box.
503 * @param autocomplete Manager handling the autocompletion
504 * @param comparator Class to decide what values are offered on autocompletion
505 * @return The created adapter
506 */
507 protected FocusAdapter addFocusAdapter(final AutoCompletionManager autocomplete, final Comparator<AutoCompletionListItem> comparator) {
508 // get the combo box' editor component
509 JTextComponent editor = (JTextComponent) values.getEditor().getEditorComponent();
510 // Refresh the values model when focus is gained
511 FocusAdapter focus = new FocusAdapter() {
512 @Override
513 public void focusGained(FocusEvent e) {
514 String key = keys.getEditor().getItem().toString();
515
516 List<AutoCompletionListItem> valueList = autocomplete.getValues(getAutocompletionKeys(key));
517 Collections.sort(valueList, comparator);
518 if (Main.isTraceEnabled()) {
519 Main.trace("Focus gained by {0}, e={1}", values, e);
520 }
521 values.setPossibleACItems(valueList);
522 values.getEditor().selectAll();
523 objKey = key;
524 }
525 };
526 editor.addFocusListener(focus);
527 return focus;
528 }
529
530 protected JPopupMenu popupMenu = new JPopupMenu() {
531 private final JCheckBoxMenuItem fixTagLanguageCb = new JCheckBoxMenuItem(
532 new AbstractAction(tr("Use English language for tag by default")) {
533 @Override
534 public void actionPerformed(ActionEvent e) {
535 boolean use = ((JCheckBoxMenuItem) e.getSource()).getState();
536 PROPERTY_FIX_TAG_LOCALE.put(use);
537 keys.setFixedLocale(use);
538 }
539 });
540 {
541 add(fixTagLanguageCb);
542 fixTagLanguageCb.setState(PROPERTY_FIX_TAG_LOCALE.get());
543 }
544 };
545 }
546
547 class AddTagsDialog extends AbstractTagsDialog {
548 private final List<JosmAction> recentTagsActions = new ArrayList<>();
549
550 // Counter of added commands for possible undo
551 private int commandCount;
552
553 AddTagsDialog() {
554 super(Main.parent, tr("Add value?"), new String[] {tr("OK"), tr("Cancel")});
555 setButtonIcons(new String[] {"ok", "cancel"});
556 setCancelButton(2);
557 configureContextsensitiveHelp("/Dialog/AddValue", true /* show help button */);
558
559 JPanel mainPanel = new JPanel(new GridBagLayout());
560 keys = new AutoCompletingComboBox();
561 values = new AutoCompletingComboBox();
562
563 mainPanel.add(new JLabel("<html>"+trn("This will change up to {0} object.",
564 "This will change up to {0} objects.", sel.size(), sel.size())
565 +"<br><br>"+tr("Please select a key")), GBC.eol().fill(GBC.HORIZONTAL));
566
567 AutoCompletionManager autocomplete = Main.main.getEditLayer().data.getAutoCompletionManager();
568 List<AutoCompletionListItem> keyList = autocomplete.getKeys();
569
570 AutoCompletionListItem itemToSelect = null;
571 // remove the object's tag keys from the list
572 Iterator<AutoCompletionListItem> iter = keyList.iterator();
573 while (iter.hasNext()) {
574 AutoCompletionListItem item = iter.next();
575 if (item.getValue().equals(lastAddKey)) {
576 itemToSelect = item;
577 }
578 for (int i = 0; i < tagData.getRowCount(); ++i) {
579 if (item.getValue().equals(getDataKey(i))) {
580 if (itemToSelect == item) {
581 itemToSelect = null;
582 }
583 iter.remove();
584 break;
585 }
586 }
587 }
588
589 Collections.sort(keyList, defaultACItemComparator);
590 keys.setPossibleACItems(keyList);
591 keys.setEditable(true);
592
593 mainPanel.add(keys, GBC.eop().fill(GBC.HORIZONTAL));
594
595 mainPanel.add(new JLabel(tr("Please select a value")), GBC.eol());
596 values.setEditable(true);
597 mainPanel.add(values, GBC.eop().fill(GBC.HORIZONTAL));
598 if (itemToSelect != null) {
599 keys.setSelectedItem(itemToSelect);
600 if (lastAddValue != null) {
601 values.setSelectedItem(lastAddValue);
602 }
603 }
604
605 FocusAdapter focus = addFocusAdapter(autocomplete, defaultACItemComparator);
606 // fire focus event in advance or otherwise the popup list will be too small at first
607 focus.focusGained(null);
608
609 int recentTagsToShow = PROPERTY_RECENT_TAGS_NUMBER.get();
610 if (recentTagsToShow > MAX_LRU_TAGS_NUMBER) {
611 recentTagsToShow = MAX_LRU_TAGS_NUMBER;
612 }
613
614 // Add tag on Shift-Enter
615 mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
616 KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_MASK), "addAndContinue");
617 mainPanel.getActionMap().put("addAndContinue", new AbstractAction() {
618 @Override
619 public void actionPerformed(ActionEvent e) {
620 performTagAdding();
621 selectKeysComboBox();
622 }
623 });
624
625 suggestRecentlyAddedTags(mainPanel, recentTagsToShow, focus);
626
627 mainPanel.add(Box.createVerticalGlue(), GBC.eop().fill());
628 setContent(mainPanel, false);
629
630 selectKeysComboBox();
631
632 popupMenu.add(new AbstractAction(tr("Set number of recently added tags")) {
633 @Override
634 public void actionPerformed(ActionEvent e) {
635 selectNumberOfTags();
636 }
637 });
638 JCheckBoxMenuItem rememberLastTags = new JCheckBoxMenuItem(
639 new AbstractAction(tr("Remember last used tags after a restart")) {
640 @Override
641 public void actionPerformed(ActionEvent e) {
642 boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState();
643 PROPERTY_REMEMBER_TAGS.put(sel);
644 if (sel) saveTagsIfNeeded();
645 }
646 });
647 rememberLastTags.setState(PROPERTY_REMEMBER_TAGS.get());
648 popupMenu.add(rememberLastTags);
649 }
650
651 private String code(String text) {
652 return "<code>" + text + "</code> ";
653 }
654
655 @Override
656 public void setContentPane(Container contentPane) {
657 final int commandDownMask = GuiHelper.getMenuShortcutKeyMaskEx();
658 List<String> lines = new ArrayList<>();
659 Shortcut sc = Shortcut.findShortcut(KeyEvent.VK_1, commandDownMask);
660 if (sc != null) {
661 lines.add(code(sc.getKeyText()) + tr("to apply first suggestion"));
662 }
663 lines.add(code(KeyEvent.getKeyModifiersText(KeyEvent.SHIFT_MASK)+'+'+KeyEvent.getKeyText(KeyEvent.VK_ENTER))
664 +tr("to add without closing the dialog"));
665 sc = Shortcut.findShortcut(KeyEvent.VK_1, commandDownMask | KeyEvent.SHIFT_DOWN_MASK);
666 if (sc != null) {
667 lines.add(code(sc.getKeyText()) + tr("to add first suggestion without closing the dialog"));
668 }
669 final JLabel helpLabel = new JLabel("<html>" + Utils.join("<br>", lines) + "</html>");
670 helpLabel.setFont(helpLabel.getFont().deriveFont(Font.PLAIN));
671 contentPane.add(helpLabel, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(1, 2, 1, 2));
672 super.setContentPane(contentPane);
673 }
674
675 private void selectNumberOfTags() {
676 String s = JOptionPane.showInputDialog(this, tr("Please enter the number of recently added tags to display"));
677 if (s == null) {
678 return;
679 }
680 try {
681 int v = Integer.parseInt(s);
682 if (v >= 0 && v <= MAX_LRU_TAGS_NUMBER) {
683 PROPERTY_RECENT_TAGS_NUMBER.put(v);
684 return;
685 }
686 } catch (NumberFormatException ex) {
687 Main.warn(ex);
688 }
689 JOptionPane.showMessageDialog(this, tr("Please enter integer number between 0 and {0}", MAX_LRU_TAGS_NUMBER));
690 }
691
692 private void suggestRecentlyAddedTags(JPanel mainPanel, int tagsToShow, final FocusAdapter focus) {
693 if (!(tagsToShow > 0 && !recentTags.isEmpty()))
694 return;
695
696 mainPanel.add(new JLabel(tr("Recently added tags")), GBC.eol());
697
698 int count = 1;
699 // We store the maximum number (9) of recent tags to allow dynamic change of number of tags shown in the preferences.
700 // This implies to iterate in descending order, as the oldest elements will only be removed after we reach the maximum
701 // number and not the number of tags to show.
702 // However, as Set does not allow to iterate in descending order, we need to copy its elements into a List we can access
703 // in reverse order.
704 List<Tag> tags = new LinkedList<>(recentTags.keySet());
705 for (int i = tags.size()-1; i >= 0 && count <= tagsToShow; i--, count++) {
706 final Tag t = tags.get(i);
707 // Create action for reusing the tag, with keyboard shortcut
708 final String actionShortcutKey = "properties:recent:" + count;
709 final String actionShortcutShiftKey = "properties:recent:shift:" + count;
710 final Shortcut sc = count > 10 ? null : Shortcut.registerShortcut(
711 actionShortcutKey, tr("Choose recent tag {0}", count), KeyEvent.VK_0 + (count % 10), Shortcut.CTRL);
712 final JosmAction action = new JosmAction(actionShortcutKey, null, tr("Use this tag again"), sc, false) {
713 @Override
714 public void actionPerformed(ActionEvent e) {
715 keys.setSelectedItem(t.getKey());
716 // fix #7951, #8298 - update list of values before setting value (?)
717 focus.focusGained(null);
718 values.setSelectedItem(t.getValue());
719 selectValuesCombobox();
720 }
721 };
722 final Shortcut scShift = count > 10 ? null : Shortcut.registerShortcut(
723 actionShortcutShiftKey, tr("Apply recent tag {0}", count), KeyEvent.VK_0 + (count % 10), Shortcut.CTRL_SHIFT);
724 final JosmAction actionShift = new JosmAction(actionShortcutShiftKey, null, tr("Use this tag again"), scShift, false) {
725 @Override
726 public void actionPerformed(ActionEvent e) {
727 action.actionPerformed(null);
728 performTagAdding();
729 selectKeysComboBox();
730 }
731 };
732 recentTagsActions.add(action);
733 recentTagsActions.add(actionShift);
734 disableTagIfNeeded(t, action);
735 // Find and display icon
736 ImageIcon icon = MapPaintStyles.getNodeIcon(t, false); // Filters deprecated icon
737 if (icon == null) {
738 // If no icon found in map style look at presets
739 Map<String, String> map = new HashMap<>();
740 map.put(t.getKey(), t.getValue());
741 for (TaggingPreset tp : TaggingPreset.getMatchingPresets(null, map, false)) {
742 icon = tp.getIcon();
743 if (icon != null) {
744 break;
745 }
746 }
747 // If still nothing display an empty icon
748 if (icon == null) {
749 icon = new ImageIcon(new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB));
750 }
751 }
752 GridBagConstraints gbc = new GridBagConstraints();
753 gbc.ipadx = 5;
754 mainPanel.add(new JLabel(action.isEnabled() ? icon : GuiHelper.getDisabledIcon(icon)), gbc);
755 // Create tag label
756 final String color = action.isEnabled() ? "" : "; color:gray";
757 final JLabel tagLabel = new JLabel("<html>"
758 + "<style>td{" + color + "}</style>"
759 + "<table><tr>"
760 + "<td>" + count + ".</td>"
761 + "<td style='border:1px solid gray'>" + XmlWriter.encode(t.toString(), true) + '<' +
762 "/td></tr></table></html>");
763 tagLabel.setFont(tagLabel.getFont().deriveFont(Font.PLAIN));
764 if (action.isEnabled() && sc != null && scShift != null) {
765 // Register action
766 mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(sc.getKeyStroke(), actionShortcutKey);
767 mainPanel.getActionMap().put(actionShortcutKey, action);
768 mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(scShift.getKeyStroke(), actionShortcutShiftKey);
769 mainPanel.getActionMap().put(actionShortcutShiftKey, actionShift);
770 }
771 if (action.isEnabled()) {
772 // Make the tag label clickable and set tooltip to the action description (this displays also the keyboard shortcut)
773 tagLabel.setToolTipText((String) action.getValue(Action.SHORT_DESCRIPTION));
774 tagLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
775 tagLabel.addMouseListener(new MouseAdapter() {
776 @Override
777 public void mouseClicked(MouseEvent e) {
778 action.actionPerformed(null);
779 // add tags and close window on double-click
780 if (e.getClickCount() > 1) {
781 buttonAction(0, null); // emulate OK click and close the dialog
782 }
783 // add tags on Shift-Click
784 if (e.isShiftDown()) {
785 performTagAdding();
786 selectKeysComboBox();
787 }
788 }
789 });
790 } else {
791 // Disable tag label
792 tagLabel.setEnabled(false);
793 // Explain in the tooltip why
794 tagLabel.setToolTipText(tr("The key ''{0}'' is already used", t.getKey()));
795 }
796 // Finally add label to the resulting panel
797 JPanel tagPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
798 tagPanel.add(tagLabel);
799 mainPanel.add(tagPanel, GBC.eol().fill(GBC.HORIZONTAL));
800 }
801 }
802
803 public void destroyActions() {
804 for (JosmAction action : recentTagsActions) {
805 action.destroy();
806 }
807 }
808
809 /**
810 * Read tags from comboboxes and add it to all selected objects
811 */
812 public final void performTagAdding() {
813 String key = Tag.removeWhiteSpaces(keys.getEditor().getItem().toString());
814 String value = Tag.removeWhiteSpaces(values.getEditor().getItem().toString());
815 if (key.isEmpty() || value.isEmpty()) return;
816 for (OsmPrimitive osm: sel) {
817 String val = osm.get(key);
818 if (val != null && !val.equals(value)) {
819 if (!warnOverwriteKey(tr("You changed the value of ''{0}'' from ''{1}'' to ''{2}''.", key, val, value),
820 "overwriteAddKey"))
821 return;
822 break;
823 }
824 }
825 lastAddKey = key;
826 lastAddValue = value;
827 recentTags.put(new Tag(key, value), null);
828 AutoCompletionManager.rememberUserInput(key, value, false);
829 commandCount++;
830 Main.main.undoRedo.add(new ChangePropertyCommand(sel, key, value));
831 changedKey = key;
832 keys.getEditor().setItem("");
833 values.getEditor().setItem("");
834 }
835
836 public void undoAllTagsAdding() {
837 Main.main.undoRedo.undo(commandCount);
838 }
839
840 private void disableTagIfNeeded(final Tag t, final JosmAction action) {
841 // Disable action if its key is already set on the object (the key being absent from the keys list for this reason
842 // performing this action leads to autocomplete to the next key (see #7671 comments)
843 for (int j = 0; j < tagData.getRowCount(); ++j) {
844 if (t.getKey().equals(getDataKey(j))) {
845 action.setEnabled(false);
846 break;
847 }
848 }
849 }
850 }
851}
Note: See TracBrowser for help on using the repository browser.