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

Last change on this file since 7725 was 7725, checked in by bastiK, 9 years ago

autocomplete: remember user input and prefer recently entered strings

It bugged my, that in tag add dialog, JOSM always autocompletes addr:h to
addr:housename. But addr:housenumber is what I want.

Now it remembers the last tags that have been entered in a session
and gives those the highest priority in autocompletion.
More recent entries are preferred.

File size: 35.1 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 * @since 5633
84 */
85class TagEditHelper {
86 private final DefaultTableModel tagData;
87 private final Map<String, Map<String, Integer>> valueCount;
88
89 // Selection that we are editing by using both dialogs
90 Collection<OsmPrimitive> sel;
91
92 private String changedKey;
93 private String objKey;
94
95 Comparator<AutoCompletionListItem> defaultACItemComparator = new Comparator<AutoCompletionListItem>() {
96 @Override
97 public int compare(AutoCompletionListItem o1, AutoCompletionListItem o2) {
98 return String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());
99 }
100 };
101
102 private String lastAddKey = null;
103 private String lastAddValue = null;
104
105 public static final int DEFAULT_LRU_TAGS_NUMBER = 5;
106 public static final int MAX_LRU_TAGS_NUMBER = 30;
107
108 // LRU cache for recently added tags (http://java-planet.blogspot.com/2005/08/how-to-set-up-simple-lru-cache-using.html)
109 private final Map<Tag, Void> recentTags = new LinkedHashMap<Tag, Void>(MAX_LRU_TAGS_NUMBER+1, 1.1f, true) {
110 @Override
111 protected boolean removeEldestEntry(Map.Entry<Tag, Void> eldest) {
112 return size() > MAX_LRU_TAGS_NUMBER;
113 }
114 };
115
116 TagEditHelper(DefaultTableModel propertyData, Map<String, Map<String, Integer>> valueCount) {
117 this.tagData = propertyData;
118 this.valueCount = valueCount;
119 }
120
121 /**
122 * Open the add selection dialog and add a new key/value to the table (and
123 * to the dataset, of course).
124 */
125 public void addTag() {
126 changedKey = null;
127 sel = Main.main.getInProgressSelection();
128 if (sel == null || sel.isEmpty()) return;
129
130 final AddTagsDialog addDialog = new AddTagsDialog();
131
132 addDialog.showDialog();
133
134 addDialog.destroyActions();
135 if (addDialog.getValue() == 1)
136 addDialog.performTagAdding();
137 else
138 addDialog.undoAllTagsAdding();
139 }
140
141 /**
142 * Edit the value in the tags table row.
143 * @param row The row of the table from which the value is edited.
144 * @param focusOnKey Determines if the initial focus should be set on key instead of value
145 * @since 5653
146 */
147 public void editTag(final int row, boolean focusOnKey) {
148 changedKey = null;
149 sel = Main.main.getInProgressSelection();
150 if (sel == null || sel.isEmpty()) return;
151
152 String key = tagData.getValueAt(row, 0).toString();
153 objKey=key;
154
155 @SuppressWarnings("unchecked")
156 final EditTagDialog editDialog = new EditTagDialog(key, row,
157 (Map<String, Integer>) tagData.getValueAt(row, 1), focusOnKey);
158 editDialog.showDialog();
159 if (editDialog.getValue() !=1 ) return;
160 editDialog.performTagEdit();
161 }
162
163 /**
164 * If during last editProperty call user changed the key name, this key will be returned
165 * Elsewhere, returns null.
166 * @return The modified key, or {@code null}
167 */
168 public String getChangedKey() {
169 return changedKey;
170 }
171
172 public void resetChangedKey() {
173 changedKey = null;
174 }
175
176 /**
177 * For a given key k, return a list of keys which are used as keys for
178 * auto-completing values to increase the search space.
179 * @param key the key k
180 * @return a list of keys
181 */
182 private static List<String> getAutocompletionKeys(String key) {
183 if ("name".equals(key) || "addr:street".equals(key))
184 return Arrays.asList("addr:street", "name");
185 else
186 return Arrays.asList(key);
187 }
188
189 /**
190 * Load recently used tags from preferences if needed.
191 */
192 public void loadTagsIfNeeded() {
193 if (PROPERTY_REMEMBER_TAGS.get() && recentTags.isEmpty()) {
194 recentTags.clear();
195 Collection<String> c = Main.pref.getCollection("properties.recent-tags");
196 Iterator<String> it = c.iterator();
197 String key, value;
198 while (it.hasNext()) {
199 key = it.next();
200 value = it.next();
201 recentTags.put(new Tag(key, value), null);
202 }
203 }
204 }
205
206 /**
207 * Store recently used tags in preferences if needed.
208 */
209 public void saveTagsIfNeeded() {
210 if (PROPERTY_REMEMBER_TAGS.get() && !recentTags.isEmpty()) {
211 List<String> c = new ArrayList<>( recentTags.size()*2 );
212 for (Tag t: recentTags.keySet()) {
213 c.add(t.getKey());
214 c.add(t.getValue());
215 }
216 Main.pref.putCollection("properties.recent-tags", c);
217 }
218 }
219
220 /**
221 * Warns user about a key being overwritten.
222 * @param action The action done by the user. Must state what key is changed
223 * @param togglePref The preference to save the checkbox state to
224 * @return {@code true} if the user accepts to overwrite key, {@code false} otherwise
225 */
226 private boolean warnOverwriteKey(String action, String togglePref) {
227 ExtendedDialog ed = new ExtendedDialog(
228 Main.parent,
229 tr("Overwrite key"),
230 new String[]{tr("Replace"), tr("Cancel")});
231 ed.setButtonIcons(new String[]{"purge", "cancel"});
232 ed.setContent(action+"\n"+ tr("The new key is already used, overwrite values?"));
233 ed.setCancelButton(2);
234 ed.toggleEnable(togglePref);
235 ed.showDialog();
236
237 return ed.getValue() == 1;
238 }
239
240 public final class EditTagDialog extends AbstractTagsDialog {
241 final String key;
242 final Map<String, Integer> m;
243 final int row;
244
245 Comparator<AutoCompletionListItem> usedValuesAwareComparator = new Comparator<AutoCompletionListItem>() {
246 @Override
247 public int compare(AutoCompletionListItem o1, AutoCompletionListItem o2) {
248 boolean c1 = m.containsKey(o1.getValue());
249 boolean c2 = m.containsKey(o2.getValue());
250 if (c1 == c2)
251 return String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());
252 else if (c1)
253 return -1;
254 else
255 return +1;
256 }
257 };
258
259 ListCellRenderer<AutoCompletionListItem> cellRenderer = new ListCellRenderer<AutoCompletionListItem>() {
260 final DefaultListCellRenderer def = new DefaultListCellRenderer();
261 @Override
262 public Component getListCellRendererComponent(JList<? extends AutoCompletionListItem> list,
263 AutoCompletionListItem value, int index, boolean isSelected, boolean cellHasFocus){
264 Component c = def.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
265 if (c instanceof JLabel) {
266 String str = value.getValue();
267 if (valueCount.containsKey(objKey)) {
268 Map<String, Integer> m = valueCount.get(objKey);
269 if (m.containsKey(str)) {
270 str = tr("{0} ({1})", str, m.get(str));
271 c.setFont(c.getFont().deriveFont(Font.ITALIC + Font.BOLD));
272 }
273 }
274 ((JLabel) c).setText(str);
275 }
276 return c;
277 }
278 };
279
280 private EditTagDialog(String key, int row, Map<String, Integer> map, final boolean initialFocusOnKey) {
281 super(Main.parent, trn("Change value?", "Change values?", map.size()), new String[] {tr("OK"),tr("Cancel")});
282 setButtonIcons(new String[] {"ok","cancel"});
283 setCancelButton(2);
284 configureContextsensitiveHelp("/Dialog/EditValue", true /* show help button */);
285 this.key = key;
286 this.row = row;
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 AutoCompletingComboBox keys;
422 AutoCompletingComboBox values;
423 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 = sysSel.getContents(null);
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 objKey=key;
510 }
511 };
512 editor.addFocusListener(focus);
513 return focus;
514 }
515
516 protected JPopupMenu popupMenu = new JPopupMenu() {
517 JCheckBoxMenuItem fixTagLanguageCb = new JCheckBoxMenuItem(
518 new AbstractAction(tr("Use English language for tag by default")){
519 @Override
520 public void actionPerformed(ActionEvent e) {
521 boolean sel=((JCheckBoxMenuItem) e.getSource()).getState();
522 PROPERTY_FIX_TAG_LOCALE.put(sel);
523 }
524 });
525 {
526 add(fixTagLanguageCb);
527 fixTagLanguageCb.setState(PROPERTY_FIX_TAG_LOCALE.get());
528 }
529 };
530 }
531
532 class AddTagsDialog extends AbstractTagsDialog {
533 List<JosmAction> recentTagsActions = new ArrayList<>();
534
535 // Counter of added commands for possible undo
536 private int commandCount;
537
538 public AddTagsDialog() {
539 super(Main.parent, tr("Add value?"), new String[] {tr("OK"),tr("Cancel")});
540 setButtonIcons(new String[] {"ok","cancel"});
541 setCancelButton(2);
542 configureContextsensitiveHelp("/Dialog/AddValue", true /* show help button */);
543
544 JPanel mainPanel = new JPanel(new GridBagLayout());
545 keys = new AutoCompletingComboBox();
546 values = new AutoCompletingComboBox();
547
548 mainPanel.add(new JLabel("<html>"+trn("This will change up to {0} object.",
549 "This will change up to {0} objects.", sel.size(),sel.size())
550 +"<br><br>"+tr("Please select a key")), GBC.eol().fill(GBC.HORIZONTAL));
551
552 AutoCompletionManager autocomplete = Main.main.getEditLayer().data.getAutoCompletionManager();
553 List<AutoCompletionListItem> keyList = autocomplete.getKeys();
554
555 AutoCompletionListItem itemToSelect = null;
556 // remove the object's tag keys from the list
557 Iterator<AutoCompletionListItem> iter = keyList.iterator();
558 while (iter.hasNext()) {
559 AutoCompletionListItem item = iter.next();
560 if (item.getValue().equals(lastAddKey)) {
561 itemToSelect = item;
562 }
563 for (int i = 0; i < tagData.getRowCount(); ++i) {
564 if (item.getValue().equals(tagData.getValueAt(i, 0))) {
565 if (itemToSelect == item) {
566 itemToSelect = null;
567 }
568 iter.remove();
569 break;
570 }
571 }
572 }
573
574 Collections.sort(keyList, defaultACItemComparator);
575 keys.setPossibleACItems(keyList);
576 keys.setEditable(true);
577
578 mainPanel.add(keys, GBC.eop().fill());
579
580 mainPanel.add(new JLabel(tr("Please select a value")), GBC.eol());
581 values.setEditable(true);
582 mainPanel.add(values, GBC.eop().fill());
583 if (itemToSelect != null) {
584 keys.setSelectedItem(itemToSelect);
585 if (lastAddValue != null) {
586 values.setSelectedItem(lastAddValue);
587 }
588 }
589
590 FocusAdapter focus = addFocusAdapter(autocomplete, defaultACItemComparator);
591 // fire focus event in advance or otherwise the popup list will be too small at first
592 focus.focusGained(null);
593
594 int recentTagsToShow = PROPERTY_RECENT_TAGS_NUMBER.get();
595 if (recentTagsToShow > MAX_LRU_TAGS_NUMBER) {
596 recentTagsToShow = MAX_LRU_TAGS_NUMBER;
597 }
598
599 // Add tag on Shift-Enter
600 mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
601 KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_MASK), "addAndContinue");
602 mainPanel.getActionMap().put("addAndContinue", new AbstractAction() {
603 @Override
604 public void actionPerformed(ActionEvent e) {
605 performTagAdding();
606 selectKeysComboBox();
607 }
608 });
609
610 suggestRecentlyAddedTags(mainPanel, recentTagsToShow, focus);
611
612 setContent(mainPanel, false);
613
614 selectKeysComboBox();
615
616 popupMenu.add(new AbstractAction(tr("Set number of recently added tags")) {
617 @Override
618 public void actionPerformed(ActionEvent e) {
619 selectNumberOfTags();
620 }
621 });
622 JCheckBoxMenuItem rememberLastTags = new JCheckBoxMenuItem(
623 new AbstractAction(tr("Remember last used tags after a restart")){
624 @Override
625 public void actionPerformed(ActionEvent e) {
626 boolean sel=((JCheckBoxMenuItem) e.getSource()).getState();
627 PROPERTY_REMEMBER_TAGS.put(sel);
628 if (sel) saveTagsIfNeeded();
629 }
630 });
631 rememberLastTags.setState(PROPERTY_REMEMBER_TAGS.get());
632 popupMenu.add(rememberLastTags);
633 }
634
635 private void selectNumberOfTags() {
636 String s = JOptionPane.showInputDialog(this, tr("Please enter the number of recently added tags to display"));
637 if (s!=null) try {
638 int v = Integer.parseInt(s);
639 if (v>=0 && v<=MAX_LRU_TAGS_NUMBER) {
640 PROPERTY_RECENT_TAGS_NUMBER.put(v);
641 return;
642 }
643 } catch (NumberFormatException ex) {
644 Main.warn(ex);
645 }
646 JOptionPane.showMessageDialog(this, tr("Please enter integer number between 0 and {0}", MAX_LRU_TAGS_NUMBER));
647 }
648
649 private void suggestRecentlyAddedTags(JPanel mainPanel, int tagsToShow, final FocusAdapter focus) {
650 if (!(tagsToShow > 0 && !recentTags.isEmpty()))
651 return;
652
653 mainPanel.add(new JLabel(tr("Recently added tags")), GBC.eol());
654
655 int count = 1;
656 // We store the maximum number (9) of recent tags to allow dynamic change of number of tags shown in the preferences.
657 // 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.
658 // 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.
659 List<Tag> tags = new LinkedList<>(recentTags.keySet());
660 for (int i = tags.size()-1; i >= 0 && count <= tagsToShow; i--, count++) {
661 final Tag t = tags.get(i);
662 // Create action for reusing the tag, with keyboard shortcut Ctrl+(1-5)
663 String actionShortcutKey = "properties:recent:"+count;
664 String actionShortcutShiftKey = "properties:recent:shift:"+count;
665 Shortcut sc = Shortcut.registerShortcut(actionShortcutKey, tr("Choose recent tag {0}", count), KeyEvent.VK_0+count, Shortcut.CTRL);
666 final JosmAction action = new JosmAction(actionShortcutKey, null, tr("Use this tag again"), sc, false) {
667 @Override
668 public void actionPerformed(ActionEvent e) {
669 keys.setSelectedItem(t.getKey());
670 // fix #7951, #8298 - update list of values before setting value (?)
671 focus.focusGained(null);
672 values.setSelectedItem(t.getValue());
673 selectValuesCombobox();
674 }
675 };
676 Shortcut scShift = Shortcut.registerShortcut(actionShortcutShiftKey, tr("Apply recent tag {0}", count), KeyEvent.VK_0+count, Shortcut.CTRL_SHIFT);
677 final JosmAction actionShift = new JosmAction(actionShortcutShiftKey, null, tr("Use this tag again"), scShift, false) {
678 @Override
679 public void actionPerformed(ActionEvent e) {
680 action.actionPerformed(null);
681 performTagAdding();
682 selectKeysComboBox();
683 }
684 };
685 recentTagsActions.add(action);
686 recentTagsActions.add(actionShift);
687 disableTagIfNeeded(t, action);
688 // Find and display icon
689 ImageIcon icon = MapPaintStyles.getNodeIcon(t, false); // Filters deprecated icon
690 if (icon == null) {
691 // If no icon found in map style look at presets
692 Map<String, String> map = new HashMap<>();
693 map.put(t.getKey(), t.getValue());
694 for (TaggingPreset tp : TaggingPreset.getMatchingPresets(null, map, false)) {
695 icon = tp.getIcon();
696 if (icon != null) {
697 break;
698 }
699 }
700 // If still nothing display an empty icon
701 if (icon == null) {
702 icon = new ImageIcon(new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB));
703 }
704 }
705 GridBagConstraints gbc = new GridBagConstraints();
706 gbc.ipadx = 5;
707 mainPanel.add(new JLabel(action.isEnabled() ? icon : GuiHelper.getDisabledIcon(icon)), gbc);
708 // Create tag label
709 final String color = action.isEnabled() ? "" : "; color:gray";
710 final JLabel tagLabel = new JLabel("<html>"
711 + "<style>td{border:1px solid gray; font-weight:normal"+color+"}</style>"
712 + "<table><tr><td>" + XmlWriter.encode(t.toString(), true) + "</td></tr></table></html>");
713 if (action.isEnabled()) {
714 // Register action
715 mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(sc.getKeyStroke(), actionShortcutKey);
716 mainPanel.getActionMap().put(actionShortcutKey, action);
717 mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(scShift.getKeyStroke(), actionShortcutShiftKey);
718 mainPanel.getActionMap().put(actionShortcutShiftKey, actionShift);
719 // Make the tag label clickable and set tooltip to the action description (this displays also the keyboard shortcut)
720 tagLabel.setToolTipText((String) action.getValue(Action.SHORT_DESCRIPTION));
721 tagLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
722 tagLabel.addMouseListener(new MouseAdapter() {
723 @Override
724 public void mouseClicked(MouseEvent e) {
725 action.actionPerformed(null);
726 // add tags and close window on double-click
727 if (e.getClickCount()>1) {
728 buttonAction(0, null); // emulate OK click and close the dialog
729 }
730 // add tags on Shift-Click
731 if (e.isShiftDown()) {
732 performTagAdding();
733 selectKeysComboBox();
734 }
735 }
736 });
737 } else {
738 // Disable tag label
739 tagLabel.setEnabled(false);
740 // Explain in the tooltip why
741 tagLabel.setToolTipText(tr("The key ''{0}'' is already used", t.getKey()));
742 }
743 // Finally add label to the resulting panel
744 JPanel tagPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
745 tagPanel.add(tagLabel);
746 mainPanel.add(tagPanel, GBC.eol().fill(GBC.HORIZONTAL));
747 }
748 }
749
750 public void destroyActions() {
751 for (JosmAction action : recentTagsActions) {
752 action.destroy();
753 }
754 }
755
756 /**
757 * Read tags from comboboxes and add it to all selected objects
758 */
759 public final void performTagAdding() {
760 String key = Tag.removeWhiteSpaces(keys.getEditor().getItem().toString());
761 String value = Tag.removeWhiteSpaces(values.getEditor().getItem().toString());
762 if (key.isEmpty() || value.isEmpty()) return;
763 for (OsmPrimitive osm: sel) {
764 String val = osm.get(key);
765 if (val != null && !val.equals(value)) {
766 if (!warnOverwriteKey(tr("You changed the value of ''{0}'' from ''{1}'' to ''{2}''.", key, val, value),
767 "overwriteAddKey"))
768 return;
769 break;
770 }
771 }
772 lastAddKey = key;
773 lastAddValue = value;
774 recentTags.put(new Tag(key, value), null);
775 AutoCompletionManager.rememberUserInput(key, value, false);
776 commandCount++;
777 Main.main.undoRedo.add(new ChangePropertyCommand(sel, key, value));
778 changedKey = key;
779 }
780
781 public void undoAllTagsAdding() {
782 Main.main.undoRedo.undo(commandCount);
783 }
784
785 private void disableTagIfNeeded(final Tag t, final JosmAction action) {
786 // Disable action if its key is already set on the object (the key being absent from the keys list for this reason
787 // performing this action leads to autocomplete to the next key (see #7671 comments)
788 for (int j = 0; j < tagData.getRowCount(); ++j) {
789 if (t.getKey().equals(tagData.getValueAt(j, 0))) {
790 action.setEnabled(false);
791 break;
792 }
793 }
794 }
795 }
796}
Note: See TracBrowser for help on using the repository browser.