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

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

fix #10039 - No warning when adding a tag with an already existing key

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