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

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

see #12554 - Factor out RecentTagCollection, add unit tests

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