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

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

fix #9482, see #9423, see #6853 - fix regression from r6542: irregular behaviour drawing ways

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