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

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

checkstyle: enable relevant whitespace checks and fix them

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