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

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

fix some compilation warnings

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