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

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

code refactoring for unit tests / headless mode

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