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

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

remove extra whitespaces

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