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

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

Sonar/FindBugs - various bugfixes / violation fixes

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