001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui.dialogs.properties; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005import static org.openstreetmap.josm.tools.I18n.trn; 006 007import java.awt.BorderLayout; 008import java.awt.Component; 009import java.awt.Container; 010import java.awt.Cursor; 011import java.awt.Dimension; 012import java.awt.FlowLayout; 013import java.awt.Font; 014import java.awt.GridBagConstraints; 015import java.awt.GridBagLayout; 016import java.awt.datatransfer.Clipboard; 017import java.awt.datatransfer.Transferable; 018import java.awt.event.ActionEvent; 019import java.awt.event.FocusAdapter; 020import java.awt.event.FocusEvent; 021import java.awt.event.InputEvent; 022import java.awt.event.KeyEvent; 023import java.awt.event.MouseAdapter; 024import java.awt.event.MouseEvent; 025import java.awt.event.WindowAdapter; 026import java.awt.event.WindowEvent; 027import java.awt.image.BufferedImage; 028import java.text.Normalizer; 029import java.util.ArrayList; 030import java.util.Arrays; 031import java.util.Collection; 032import java.util.Collections; 033import java.util.Comparator; 034import java.util.HashMap; 035import java.util.List; 036import java.util.Map; 037import java.util.Objects; 038import java.util.TreeMap; 039import java.util.stream.IntStream; 040 041import javax.swing.AbstractAction; 042import javax.swing.Action; 043import javax.swing.Box; 044import javax.swing.ButtonGroup; 045import javax.swing.ComboBoxModel; 046import javax.swing.DefaultListCellRenderer; 047import javax.swing.ImageIcon; 048import javax.swing.JCheckBoxMenuItem; 049import javax.swing.JComponent; 050import javax.swing.JLabel; 051import javax.swing.JList; 052import javax.swing.JMenu; 053import javax.swing.JOptionPane; 054import javax.swing.JPanel; 055import javax.swing.JPopupMenu; 056import javax.swing.JRadioButtonMenuItem; 057import javax.swing.JTable; 058import javax.swing.KeyStroke; 059import javax.swing.ListCellRenderer; 060import javax.swing.SwingUtilities; 061import javax.swing.table.DefaultTableModel; 062import javax.swing.text.JTextComponent; 063 064import org.openstreetmap.josm.actions.JosmAction; 065import org.openstreetmap.josm.actions.search.SearchAction; 066import org.openstreetmap.josm.command.ChangePropertyCommand; 067import org.openstreetmap.josm.command.Command; 068import org.openstreetmap.josm.command.SequenceCommand; 069import org.openstreetmap.josm.data.UndoRedoHandler; 070import org.openstreetmap.josm.data.osm.OsmDataManager; 071import org.openstreetmap.josm.data.osm.OsmPrimitive; 072import org.openstreetmap.josm.data.osm.Tag; 073import org.openstreetmap.josm.data.osm.search.SearchCompiler; 074import org.openstreetmap.josm.data.osm.search.SearchParseError; 075import org.openstreetmap.josm.data.osm.search.SearchSetting; 076import org.openstreetmap.josm.data.preferences.BooleanProperty; 077import org.openstreetmap.josm.data.preferences.EnumProperty; 078import org.openstreetmap.josm.data.preferences.IntegerProperty; 079import org.openstreetmap.josm.data.preferences.ListProperty; 080import org.openstreetmap.josm.data.preferences.StringProperty; 081import org.openstreetmap.josm.data.tagging.ac.AutoCompletionItem; 082import org.openstreetmap.josm.gui.ExtendedDialog; 083import org.openstreetmap.josm.gui.IExtendedDialog; 084import org.openstreetmap.josm.gui.MainApplication; 085import org.openstreetmap.josm.gui.datatransfer.ClipboardUtils; 086import org.openstreetmap.josm.gui.mappaint.MapPaintStyles; 087import org.openstreetmap.josm.gui.tagging.ac.AutoCompletingComboBox; 088import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionManager; 089import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset; 090import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets; 091import org.openstreetmap.josm.gui.util.GuiHelper; 092import org.openstreetmap.josm.gui.util.WindowGeometry; 093import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher; 094import org.openstreetmap.josm.io.XmlWriter; 095import org.openstreetmap.josm.tools.GBC; 096import org.openstreetmap.josm.tools.Logging; 097import org.openstreetmap.josm.tools.PlatformManager; 098import org.openstreetmap.josm.tools.Shortcut; 099import org.openstreetmap.josm.tools.Utils; 100 101/** 102 * Class that helps PropertiesDialog add and edit tag values. 103 * @since 5633 104 */ 105public class TagEditHelper { 106 107 private final JTable tagTable; 108 private final DefaultTableModel tagData; 109 private final Map<String, Map<String, Integer>> valueCount; 110 111 // Selection that we are editing by using both dialogs 112 protected Collection<OsmPrimitive> sel; 113 114 private String changedKey; 115 private String objKey; 116 117 static final Comparator<AutoCompletionItem> DEFAULT_AC_ITEM_COMPARATOR = 118 (o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue()); 119 120 /** Default number of recent tags */ 121 public static final int DEFAULT_LRU_TAGS_NUMBER = 5; 122 /** Maximum number of recent tags */ 123 public static final int MAX_LRU_TAGS_NUMBER = 30; 124 125 /** Use English language for tag by default */ 126 public static final BooleanProperty PROPERTY_FIX_TAG_LOCALE = new BooleanProperty("properties.fix-tag-combobox-locale", false); 127 /** Whether recent tags must be remembered */ 128 public static final BooleanProperty PROPERTY_REMEMBER_TAGS = new BooleanProperty("properties.remember-recently-added-tags", true); 129 /** Number of recent tags */ 130 public static final IntegerProperty PROPERTY_RECENT_TAGS_NUMBER = new IntegerProperty("properties.recently-added-tags", 131 DEFAULT_LRU_TAGS_NUMBER); 132 /** The preference storage of recent tags */ 133 public static final ListProperty PROPERTY_RECENT_TAGS = new ListProperty("properties.recent-tags", 134 Collections.<String>emptyList()); 135 /** The preference list of tags which should not be remembered, since r9940 */ 136 public static final StringProperty PROPERTY_TAGS_TO_IGNORE = new StringProperty("properties.recent-tags.ignore", 137 new SearchSetting().writeToString()); 138 139 /** 140 * What to do with recent tags where keys already exist 141 */ 142 private enum RecentExisting { 143 ENABLE, 144 DISABLE, 145 HIDE 146 } 147 148 /** 149 * Preference setting for popup menu item "Recent tags with existing key" 150 */ 151 public static final EnumProperty<RecentExisting> PROPERTY_RECENT_EXISTING = new EnumProperty<>( 152 "properties.recently-added-tags-existing-key", RecentExisting.class, RecentExisting.DISABLE); 153 154 /** 155 * What to do after applying tag 156 */ 157 private enum RefreshRecent { 158 NO, 159 STATUS, 160 REFRESH 161 } 162 163 /** 164 * Preference setting for popup menu item "Refresh recent tags list after applying tag" 165 */ 166 public static final EnumProperty<RefreshRecent> PROPERTY_REFRESH_RECENT = new EnumProperty<>( 167 "properties.refresh-recently-added-tags", RefreshRecent.class, RefreshRecent.STATUS); 168 169 final RecentTagCollection recentTags = new RecentTagCollection(MAX_LRU_TAGS_NUMBER); 170 SearchSetting tagsToIgnore; 171 172 /** 173 * Copy of recently added tags in sorted from newest to oldest order. 174 * 175 * We store the maximum number of recent tags to allow dynamic change of number of tags shown in the preferences. 176 * Used to cache initial status. 177 */ 178 private List<Tag> tags; 179 180 static { 181 // init user input based on recent tags 182 final RecentTagCollection recentTags = new RecentTagCollection(MAX_LRU_TAGS_NUMBER); 183 recentTags.loadFromPreference(PROPERTY_RECENT_TAGS); 184 recentTags.toList().forEach(tag -> AutoCompletionManager.rememberUserInput(tag.getKey(), tag.getValue(), false)); 185 } 186 187 /** 188 * Constructs a new {@code TagEditHelper}. 189 * @param tagTable tag table 190 * @param propertyData table model 191 * @param valueCount tag value count 192 */ 193 public TagEditHelper(JTable tagTable, DefaultTableModel propertyData, Map<String, Map<String, Integer>> valueCount) { 194 this.tagTable = tagTable; 195 this.tagData = propertyData; 196 this.valueCount = valueCount; 197 } 198 199 /** 200 * Finds the key from given row of tag editor. 201 * @param viewRow index of row 202 * @return key of tag 203 */ 204 public final String getDataKey(int viewRow) { 205 return tagData.getValueAt(tagTable.convertRowIndexToModel(viewRow), 0).toString(); 206 } 207 208 /** 209 * Determines if the given tag key is already used (by all selected primitives, not just some of them) 210 * @param key the key to check 211 * @return {@code true} if the key is used by all selected primitives (key not unset for at least one primitive) 212 */ 213 @SuppressWarnings("unchecked") 214 boolean containsDataKey(String key) { 215 return IntStream.range(0, tagData.getRowCount()) 216 .anyMatch(i -> key.equals(tagData.getValueAt(i, 0)) /* sic! do not use getDataKey*/ 217 && !((Map<String, Integer>) tagData.getValueAt(i, 1)).containsKey("") /* sic! do not use getDataValues*/); 218 } 219 220 /** 221 * Finds the values from given row of tag editor. 222 * @param viewRow index of row 223 * @return map of values and number of occurrences 224 */ 225 @SuppressWarnings("unchecked") 226 public final Map<String, Integer> getDataValues(int viewRow) { 227 return (Map<String, Integer>) tagData.getValueAt(tagTable.convertRowIndexToModel(viewRow), 1); 228 } 229 230 /** 231 * Open the add selection dialog and add a new key/value to the table (and 232 * to the dataset, of course). 233 */ 234 public void addTag() { 235 changedKey = null; 236 sel = OsmDataManager.getInstance().getInProgressSelection(); 237 if (sel == null || sel.isEmpty()) 238 return; 239 240 final AddTagsDialog addDialog = getAddTagsDialog(); 241 242 addDialog.showDialog(); 243 244 addDialog.destroyActions(); 245 if (addDialog.getValue() == 1) 246 addDialog.performTagAdding(); 247 else 248 addDialog.undoAllTagsAdding(); 249 } 250 251 /** 252 * Returns a new {@code AddTagsDialog}. 253 * @return a new {@code AddTagsDialog} 254 */ 255 protected AddTagsDialog getAddTagsDialog() { 256 return new AddTagsDialog(); 257 } 258 259 /** 260 * Edit the value in the tags table row. 261 * @param row The row of the table from which the value is edited. 262 * @param focusOnKey Determines if the initial focus should be set on key instead of value 263 * @since 5653 264 */ 265 public void editTag(final int row, boolean focusOnKey) { 266 changedKey = null; 267 sel = OsmDataManager.getInstance().getInProgressSelection(); 268 if (sel == null || sel.isEmpty()) 269 return; 270 271 String key = getDataKey(row); 272 objKey = key; 273 274 final IEditTagDialog editDialog = getEditTagDialog(row, focusOnKey, key); 275 editDialog.showDialog(); 276 if (editDialog.getValue() != 1) 277 return; 278 editDialog.performTagEdit(); 279 } 280 281 /** 282 * Extracted interface of {@link EditTagDialog}. 283 */ 284 protected interface IEditTagDialog extends IExtendedDialog { 285 /** 286 * Edit tags of multiple selected objects according to selected ComboBox values 287 * If value == "", tag will be deleted 288 * Confirmations may be needed. 289 */ 290 void performTagEdit(); 291 } 292 293 protected IEditTagDialog getEditTagDialog(int row, boolean focusOnKey, String key) { 294 return new EditTagDialog(key, getDataValues(row), focusOnKey); 295 } 296 297 /** 298 * If during last editProperty call user changed the key name, this key will be returned 299 * Elsewhere, returns null. 300 * @return The modified key, or {@code null} 301 */ 302 public String getChangedKey() { 303 return changedKey; 304 } 305 306 /** 307 * Reset last changed key. 308 */ 309 public void resetChangedKey() { 310 changedKey = null; 311 } 312 313 /** 314 * For a given key k, return a list of keys which are used as keys for 315 * auto-completing values to increase the search space. 316 * @param key the key k 317 * @return a list of keys 318 */ 319 private static List<String> getAutocompletionKeys(String key) { 320 if ("name".equals(key) || "addr:street".equals(key)) 321 return Arrays.asList("addr:street", "name"); 322 else 323 return Arrays.asList(key); 324 } 325 326 /** 327 * Load recently used tags from preferences if needed. 328 */ 329 public void loadTagsIfNeeded() { 330 loadTagsToIgnore(); 331 if (PROPERTY_REMEMBER_TAGS.get() && recentTags.isEmpty()) { 332 recentTags.loadFromPreference(PROPERTY_RECENT_TAGS); 333 } 334 } 335 336 void loadTagsToIgnore() { 337 final SearchSetting searchSetting = Utils.firstNonNull( 338 SearchSetting.readFromString(PROPERTY_TAGS_TO_IGNORE.get()), new SearchSetting()); 339 if (!Objects.equals(tagsToIgnore, searchSetting)) { 340 try { 341 tagsToIgnore = searchSetting; 342 recentTags.setTagsToIgnore(tagsToIgnore); 343 } catch (SearchParseError parseError) { 344 warnAboutParseError(parseError); 345 tagsToIgnore = new SearchSetting(); 346 recentTags.setTagsToIgnore(SearchCompiler.Never.INSTANCE); 347 } 348 } 349 } 350 351 private static void warnAboutParseError(SearchParseError parseError) { 352 Logging.warn(parseError); 353 JOptionPane.showMessageDialog( 354 MainApplication.getMainFrame(), 355 parseError.getMessage(), 356 tr("Error"), 357 JOptionPane.ERROR_MESSAGE 358 ); 359 } 360 361 /** 362 * Store recently used tags in preferences if needed. 363 */ 364 public void saveTagsIfNeeded() { 365 if (PROPERTY_REMEMBER_TAGS.get() && !recentTags.isEmpty()) { 366 recentTags.saveToPreference(PROPERTY_RECENT_TAGS); 367 } 368 } 369 370 /** 371 * Forget recently selected primitives to allow GC. 372 * @since 14509 373 */ 374 public void resetSelection() { 375 sel = null; 376 } 377 378 /** 379 * Update cache of recent tags used for displaying tags. 380 */ 381 private void cacheRecentTags() { 382 tags = recentTags.toList(); 383 Collections.reverse(tags); 384 } 385 386 /** 387 * Warns user about a key being overwritten. 388 * @param action The action done by the user. Must state what key is changed 389 * @param togglePref The preference to save the checkbox state to 390 * @return {@code true} if the user accepts to overwrite key, {@code false} otherwise 391 */ 392 private static boolean warnOverwriteKey(String action, String togglePref) { 393 return new ExtendedDialog( 394 MainApplication.getMainFrame(), 395 tr("Overwrite key"), 396 tr("Replace"), tr("Cancel")) 397 .setButtonIcons("purge", "cancel") 398 .setContent(action+'\n'+ tr("The new key is already used, overwrite values?")) 399 .setCancelButton(2) 400 .toggleEnable(togglePref) 401 .showDialog().getValue() == 1; 402 } 403 404 protected class EditTagDialog extends AbstractTagsDialog implements IEditTagDialog { 405 private final String key; 406 private final transient Map<String, Integer> m; 407 private final transient Comparator<AutoCompletionItem> usedValuesAwareComparator; 408 409 private final transient ListCellRenderer<AutoCompletionItem> cellRenderer = new ListCellRenderer<AutoCompletionItem>() { 410 private final DefaultListCellRenderer def = new DefaultListCellRenderer(); 411 @Override 412 public Component getListCellRendererComponent(JList<? extends AutoCompletionItem> list, 413 AutoCompletionItem value, int index, boolean isSelected, boolean cellHasFocus) { 414 Component c = def.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); 415 if (c instanceof JLabel) { 416 String str = value.getValue(); 417 if (valueCount.containsKey(objKey)) { 418 Map<String, Integer> map = valueCount.get(objKey); 419 if (map.containsKey(str)) { 420 str = tr("{0} ({1})", str, map.get(str)); 421 c.setFont(c.getFont().deriveFont(Font.ITALIC + Font.BOLD)); 422 } 423 } 424 ((JLabel) c).setText(str); 425 } 426 return c; 427 } 428 }; 429 430 protected EditTagDialog(String key, Map<String, Integer> map, final boolean initialFocusOnKey) { 431 super(MainApplication.getMainFrame(), trn("Change value?", "Change values?", map.size()), tr("OK"), tr("Cancel")); 432 setButtonIcons("ok", "cancel"); 433 setCancelButton(2); 434 configureContextsensitiveHelp("/Dialog/EditValue", true /* show help button */); 435 this.key = key; 436 this.m = map; 437 438 usedValuesAwareComparator = (o1, o2) -> { 439 boolean c1 = m.containsKey(o1.getValue()); 440 boolean c2 = m.containsKey(o2.getValue()); 441 if (c1 == c2) 442 return String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue()); 443 else if (c1) 444 return -1; 445 else 446 return +1; 447 }; 448 449 JPanel mainPanel = new JPanel(new BorderLayout()); 450 451 String msg = "<html>"+trn("This will change {0} object.", 452 "This will change up to {0} objects.", sel.size(), sel.size()) 453 +"<br><br>("+tr("An empty value deletes the tag.", key)+")</html>"; 454 455 mainPanel.add(new JLabel(msg), BorderLayout.NORTH); 456 457 JPanel p = new JPanel(new GridBagLayout()); 458 mainPanel.add(p, BorderLayout.CENTER); 459 460 AutoCompletionManager autocomplete = AutoCompletionManager.of(OsmDataManager.getInstance().getActiveDataSet()); 461 List<AutoCompletionItem> keyList = autocomplete.getTagKeys(DEFAULT_AC_ITEM_COMPARATOR); 462 463 keys = new AutoCompletingComboBox(key); 464 keys.setPossibleAcItems(keyList); 465 keys.setEditable(true); 466 keys.setSelectedItem(key); 467 468 p.add(Box.createVerticalStrut(5), GBC.eol()); 469 p.add(new JLabel(tr("Key")), GBC.std()); 470 p.add(Box.createHorizontalStrut(10), GBC.std()); 471 p.add(keys, GBC.eol().fill(GBC.HORIZONTAL)); 472 473 List<AutoCompletionItem> valueList = autocomplete.getTagValues(getAutocompletionKeys(key), usedValuesAwareComparator); 474 475 final String selection = m.size() != 1 ? tr("<different>") : m.entrySet().iterator().next().getKey(); 476 477 values = new AutoCompletingComboBox(selection); 478 values.setRenderer(cellRenderer); 479 480 values.setEditable(true); 481 values.setPossibleAcItems(valueList); 482 values.setSelectedItem(selection); 483 values.getEditor().setItem(selection); 484 p.add(Box.createVerticalStrut(5), GBC.eol()); 485 p.add(new JLabel(tr("Value")), GBC.std()); 486 p.add(Box.createHorizontalStrut(10), GBC.std()); 487 p.add(values, GBC.eol().fill(GBC.HORIZONTAL)); 488 values.getEditor().addActionListener(e -> buttonAction(0, null)); 489 addFocusAdapter(autocomplete, usedValuesAwareComparator); 490 491 setContent(mainPanel, false); 492 493 addWindowListener(new WindowAdapter() { 494 @Override 495 public void windowOpened(WindowEvent e) { 496 if (initialFocusOnKey) { 497 selectKeysComboBox(); 498 } else { 499 selectValuesCombobox(); 500 } 501 } 502 }); 503 } 504 505 @Override 506 public void performTagEdit() { 507 String value = Utils.removeWhiteSpaces(values.getEditor().getItem().toString()); 508 value = Normalizer.normalize(value, Normalizer.Form.NFC); 509 if (value.isEmpty()) { 510 value = null; // delete the key 511 } 512 String newkey = Utils.removeWhiteSpaces(keys.getEditor().getItem().toString()); 513 newkey = Normalizer.normalize(newkey, Normalizer.Form.NFC); 514 if (newkey.isEmpty()) { 515 newkey = key; 516 value = null; // delete the key instead 517 } 518 if (key.equals(newkey) && tr("<different>").equals(value)) 519 return; 520 if (key.equals(newkey) || value == null) { 521 UndoRedoHandler.getInstance().add(new ChangePropertyCommand(sel, newkey, value)); 522 AutoCompletionManager.rememberUserInput(newkey, value, true); 523 } else { 524 for (OsmPrimitive osm: sel) { 525 if (osm.get(newkey) != null) { 526 if (!warnOverwriteKey(tr("You changed the key from ''{0}'' to ''{1}''.", key, newkey), 527 "overwriteEditKey")) 528 return; 529 break; 530 } 531 } 532 Collection<Command> commands = new ArrayList<>(); 533 commands.add(new ChangePropertyCommand(sel, key, null)); 534 if (value.equals(tr("<different>"))) { 535 Map<String, List<OsmPrimitive>> map = new HashMap<>(); 536 for (OsmPrimitive osm: sel) { 537 String val = osm.get(key); 538 if (val != null) { 539 if (map.containsKey(val)) { 540 map.get(val).add(osm); 541 } else { 542 List<OsmPrimitive> v = new ArrayList<>(); 543 v.add(osm); 544 map.put(val, v); 545 } 546 } 547 } 548 for (Map.Entry<String, List<OsmPrimitive>> e: map.entrySet()) { 549 commands.add(new ChangePropertyCommand(e.getValue(), newkey, e.getKey())); 550 } 551 } else { 552 commands.add(new ChangePropertyCommand(sel, newkey, value)); 553 AutoCompletionManager.rememberUserInput(newkey, value, false); 554 } 555 UndoRedoHandler.getInstance().add(new SequenceCommand( 556 trn("Change properties of up to {0} object", 557 "Change properties of up to {0} objects", sel.size(), sel.size()), 558 commands)); 559 } 560 561 changedKey = newkey; 562 } 563 } 564 565 protected abstract class AbstractTagsDialog extends ExtendedDialog { 566 protected AutoCompletingComboBox keys; 567 protected AutoCompletingComboBox values; 568 569 AbstractTagsDialog(Component parent, String title, String... buttonTexts) { 570 super(parent, title, buttonTexts); 571 addMouseListener(new PopupMenuLauncher(popupMenu)); 572 } 573 574 @Override 575 public void setupDialog() { 576 super.setupDialog(); 577 buttons.get(0).setEnabled(!OsmDataManager.getInstance().getActiveDataSet().isLocked()); 578 final Dimension size = getSize(); 579 // Set resizable only in width 580 setMinimumSize(size); 581 setPreferredSize(size); 582 // setMaximumSize does not work, and never worked, but still it seems not to bother Oracle to fix this 10-year-old bug 583 // https://bugs.openjdk.java.net/browse/JDK-6200438 584 // https://bugs.openjdk.java.net/browse/JDK-6464548 585 586 setRememberWindowGeometry(getClass().getName() + ".geometry", 587 WindowGeometry.centerInWindow(MainApplication.getMainFrame(), size)); 588 } 589 590 @Override 591 public void setVisible(boolean visible) { 592 // Do not want dialog to be resizable in height, as its size may increase each time because of the recently added tags 593 // So need to modify the stored geometry (size part only) in order to use the automatic positioning mechanism 594 if (visible) { 595 WindowGeometry geometry = initWindowGeometry(); 596 Dimension storedSize = geometry.getSize(); 597 Dimension size = getSize(); 598 if (!storedSize.equals(size)) { 599 if (storedSize.width < size.width) { 600 storedSize.width = size.width; 601 } 602 if (storedSize.height != size.height) { 603 storedSize.height = size.height; 604 } 605 rememberWindowGeometry(geometry); 606 } 607 keys.setFixedLocale(PROPERTY_FIX_TAG_LOCALE.get()); 608 } 609 super.setVisible(visible); 610 } 611 612 private void selectACComboBoxSavingUnixBuffer(AutoCompletingComboBox cb) { 613 // select combobox with saving unix system selection (middle mouse paste) 614 Clipboard sysSel = ClipboardUtils.getSystemSelection(); 615 if (sysSel != null) { 616 Transferable old = ClipboardUtils.getClipboardContent(sysSel); 617 cb.requestFocusInWindow(); 618 cb.getEditor().selectAll(); 619 if (old != null) { 620 sysSel.setContents(old, null); 621 } 622 } else { 623 cb.requestFocusInWindow(); 624 cb.getEditor().selectAll(); 625 } 626 } 627 628 public void selectKeysComboBox() { 629 selectACComboBoxSavingUnixBuffer(keys); 630 } 631 632 public void selectValuesCombobox() { 633 selectACComboBoxSavingUnixBuffer(values); 634 } 635 636 /** 637 * Create a focus handling adapter and apply in to the editor component of value 638 * autocompletion box. 639 * @param autocomplete Manager handling the autocompletion 640 * @param comparator Class to decide what values are offered on autocompletion 641 * @return The created adapter 642 */ 643 protected FocusAdapter addFocusAdapter(final AutoCompletionManager autocomplete, final Comparator<AutoCompletionItem> comparator) { 644 // get the combo box' editor component 645 final JTextComponent editor = values.getEditorComponent(); 646 // Refresh the values model when focus is gained 647 FocusAdapter focus = new FocusAdapter() { 648 @Override 649 public void focusGained(FocusEvent e) { 650 Logging.trace("Focus gained by {0}, e={1}", values, e); 651 String key = keys.getEditor().getItem().toString(); 652 List<AutoCompletionItem> correctItems = autocomplete.getTagValues(getAutocompletionKeys(key), comparator); 653 ComboBoxModel<AutoCompletionItem> currentModel = values.getModel(); 654 final int size = correctItems.size(); 655 boolean valuesOK = size == currentModel.getSize(); 656 for (int i = 0; valuesOK && i < size; i++) { 657 valuesOK = Objects.equals(currentModel.getElementAt(i), correctItems.get(i)); 658 } 659 if (!valuesOK) { 660 values.setPossibleAcItems(correctItems); 661 } 662 if (!Objects.equals(key, objKey)) { 663 values.getEditor().selectAll(); 664 objKey = key; 665 } 666 } 667 }; 668 editor.addFocusListener(focus); 669 return focus; 670 } 671 672 protected JPopupMenu popupMenu = new JPopupMenu() { 673 private final JCheckBoxMenuItem fixTagLanguageCb = new JCheckBoxMenuItem( 674 new AbstractAction(tr("Use English language for tag by default")) { 675 @Override 676 public void actionPerformed(ActionEvent e) { 677 boolean use = ((JCheckBoxMenuItem) e.getSource()).getState(); 678 PROPERTY_FIX_TAG_LOCALE.put(use); 679 keys.setFixedLocale(use); 680 } 681 }); 682 { 683 add(fixTagLanguageCb); 684 fixTagLanguageCb.setState(PROPERTY_FIX_TAG_LOCALE.get()); 685 } 686 }; 687 } 688 689 protected class AddTagsDialog extends AbstractTagsDialog { 690 private final List<JosmAction> recentTagsActions = new ArrayList<>(); 691 protected final transient FocusAdapter focus; 692 private final JPanel mainPanel; 693 private JPanel recentTagsPanel; 694 695 // Counter of added commands for possible undo 696 private int commandCount; 697 698 protected AddTagsDialog() { 699 super(MainApplication.getMainFrame(), tr("Add value?"), tr("OK"), tr("Cancel")); 700 setButtonIcons("ok", "cancel"); 701 setCancelButton(2); 702 configureContextsensitiveHelp("/Dialog/AddValue", true /* show help button */); 703 704 mainPanel = new JPanel(new GridBagLayout()); 705 keys = new AutoCompletingComboBox(); 706 values = new AutoCompletingComboBox(); 707 708 mainPanel.add(new JLabel("<html>"+trn("This will change up to {0} object.", 709 "This will change up to {0} objects.", sel.size(), sel.size()) 710 +"<br><br>"+tr("Please select a key")), GBC.eol().fill(GBC.HORIZONTAL)); 711 712 cacheRecentTags(); 713 AutoCompletionManager autocomplete = AutoCompletionManager.of(OsmDataManager.getInstance().getActiveDataSet()); 714 List<AutoCompletionItem> keyList = autocomplete.getTagKeys(DEFAULT_AC_ITEM_COMPARATOR); 715 716 // remove the object's tag keys from the list 717 keyList.removeIf(item -> containsDataKey(item.getValue())); 718 719 keys.setPossibleAcItems(keyList); 720 keys.setEditable(true); 721 722 mainPanel.add(keys, GBC.eop().fill(GBC.HORIZONTAL)); 723 724 mainPanel.add(new JLabel(tr("Please select a value")), GBC.eol()); 725 values.setEditable(true); 726 mainPanel.add(values, GBC.eop().fill(GBC.HORIZONTAL)); 727 728 // pre-fill first recent tag for which the key is not already present 729 tags.stream() 730 .filter(tag -> !containsDataKey(tag.getKey())) 731 .findFirst() 732 .ifPresent(tag -> { 733 keys.setSelectedItem(tag.getKey()); 734 values.setSelectedItem(tag.getValue()); 735 }); 736 737 focus = addFocusAdapter(autocomplete, DEFAULT_AC_ITEM_COMPARATOR); 738 // fire focus event in advance or otherwise the popup list will be too small at first 739 focus.focusGained(null); 740 741 // Add tag on Shift-Enter 742 mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( 743 KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK), "addAndContinue"); 744 mainPanel.getActionMap().put("addAndContinue", new AbstractAction() { 745 @Override 746 public void actionPerformed(ActionEvent e) { 747 performTagAdding(); 748 refreshRecentTags(); 749 selectKeysComboBox(); 750 } 751 }); 752 753 suggestRecentlyAddedTags(); 754 755 mainPanel.add(Box.createVerticalGlue(), GBC.eop().fill()); 756 setContent(mainPanel, false); 757 758 selectKeysComboBox(); 759 760 popupMenu.add(new AbstractAction(tr("Set number of recently added tags")) { 761 @Override 762 public void actionPerformed(ActionEvent e) { 763 selectNumberOfTags(); 764 suggestRecentlyAddedTags(); 765 } 766 }); 767 768 popupMenu.add(buildMenuRecentExisting()); 769 popupMenu.add(buildMenuRefreshRecent()); 770 771 JCheckBoxMenuItem rememberLastTags = new JCheckBoxMenuItem( 772 new AbstractAction(tr("Remember last used tags after a restart")) { 773 @Override 774 public void actionPerformed(ActionEvent e) { 775 boolean state = ((JCheckBoxMenuItem) e.getSource()).getState(); 776 PROPERTY_REMEMBER_TAGS.put(state); 777 if (state) 778 saveTagsIfNeeded(); 779 } 780 }); 781 rememberLastTags.setState(PROPERTY_REMEMBER_TAGS.get()); 782 popupMenu.add(rememberLastTags); 783 } 784 785 private JMenu buildMenuRecentExisting() { 786 JMenu menu = new JMenu(tr("Recent tags with existing key")); 787 TreeMap<RecentExisting, String> radios = new TreeMap<>(); 788 radios.put(RecentExisting.ENABLE, tr("Enable")); 789 radios.put(RecentExisting.DISABLE, tr("Disable")); 790 radios.put(RecentExisting.HIDE, tr("Hide")); 791 ButtonGroup buttonGroup = new ButtonGroup(); 792 for (final Map.Entry<RecentExisting, String> entry : radios.entrySet()) { 793 JRadioButtonMenuItem radio = new JRadioButtonMenuItem(new AbstractAction(entry.getValue()) { 794 @Override 795 public void actionPerformed(ActionEvent e) { 796 PROPERTY_RECENT_EXISTING.put(entry.getKey()); 797 suggestRecentlyAddedTags(); 798 } 799 }); 800 buttonGroup.add(radio); 801 radio.setSelected(PROPERTY_RECENT_EXISTING.get() == entry.getKey()); 802 menu.add(radio); 803 } 804 return menu; 805 } 806 807 private JMenu buildMenuRefreshRecent() { 808 JMenu menu = new JMenu(tr("Refresh recent tags list after applying tag")); 809 TreeMap<RefreshRecent, String> radios = new TreeMap<>(); 810 radios.put(RefreshRecent.NO, tr("No refresh")); 811 radios.put(RefreshRecent.STATUS, tr("Refresh tag status only (enabled / disabled)")); 812 radios.put(RefreshRecent.REFRESH, tr("Refresh tag status and list of recently added tags")); 813 ButtonGroup buttonGroup = new ButtonGroup(); 814 for (final Map.Entry<RefreshRecent, String> entry : radios.entrySet()) { 815 JRadioButtonMenuItem radio = new JRadioButtonMenuItem(new AbstractAction(entry.getValue()) { 816 @Override 817 public void actionPerformed(ActionEvent e) { 818 PROPERTY_REFRESH_RECENT.put(entry.getKey()); 819 } 820 }); 821 buttonGroup.add(radio); 822 radio.setSelected(PROPERTY_REFRESH_RECENT.get() == entry.getKey()); 823 menu.add(radio); 824 } 825 return menu; 826 } 827 828 @Override 829 public void setContentPane(Container contentPane) { 830 final int commandDownMask = PlatformManager.getPlatform().getMenuShortcutKeyMaskEx(); 831 List<String> lines = new ArrayList<>(); 832 Shortcut.findShortcut(KeyEvent.VK_1, commandDownMask).ifPresent(sc -> 833 lines.add(sc.getKeyText() + ' ' + tr("to apply first suggestion")) 834 ); 835 lines.add(Shortcut.getKeyText(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK)) + ' ' 836 +tr("to add without closing the dialog")); 837 Shortcut.findShortcut(KeyEvent.VK_1, commandDownMask | KeyEvent.SHIFT_DOWN_MASK).ifPresent(sc -> 838 lines.add(sc.getKeyText() + ' ' + tr("to add first suggestion without closing the dialog")) 839 ); 840 final JLabel helpLabel = new JLabel("<html>" + Utils.join("<br>", lines) + "</html>"); 841 helpLabel.setFont(helpLabel.getFont().deriveFont(Font.PLAIN)); 842 contentPane.add(helpLabel, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(5, 5, 5, 5)); 843 super.setContentPane(contentPane); 844 } 845 846 protected void selectNumberOfTags() { 847 String s = String.format("%d", PROPERTY_RECENT_TAGS_NUMBER.get()); 848 while (true) { 849 s = JOptionPane.showInputDialog(this, tr("Please enter the number of recently added tags to display"), s); 850 if (s == null || s.isEmpty()) { 851 return; 852 } 853 try { 854 int v = Integer.parseInt(s); 855 if (v >= 0 && v <= MAX_LRU_TAGS_NUMBER) { 856 PROPERTY_RECENT_TAGS_NUMBER.put(v); 857 return; 858 } 859 } catch (NumberFormatException ex) { 860 Logging.warn(ex); 861 } 862 JOptionPane.showMessageDialog(this, tr("Please enter integer number between 0 and {0}", MAX_LRU_TAGS_NUMBER)); 863 } 864 } 865 866 protected void suggestRecentlyAddedTags() { 867 if (recentTagsPanel == null) { 868 recentTagsPanel = new JPanel(new GridBagLayout()); 869 buildRecentTagsPanel(); 870 mainPanel.add(recentTagsPanel, GBC.eol().fill(GBC.HORIZONTAL)); 871 } else { 872 Dimension panelOldSize = recentTagsPanel.getPreferredSize(); 873 recentTagsPanel.removeAll(); 874 buildRecentTagsPanel(); 875 Dimension panelNewSize = recentTagsPanel.getPreferredSize(); 876 Dimension dialogOldSize = getMinimumSize(); 877 Dimension dialogNewSize = new Dimension(dialogOldSize.width, dialogOldSize.height-panelOldSize.height+panelNewSize.height); 878 setMinimumSize(dialogNewSize); 879 setPreferredSize(dialogNewSize); 880 setSize(dialogNewSize); 881 revalidate(); 882 repaint(); 883 } 884 } 885 886 protected void buildRecentTagsPanel() { 887 final int tagsToShow = Math.min(PROPERTY_RECENT_TAGS_NUMBER.get(), MAX_LRU_TAGS_NUMBER); 888 if (!(tagsToShow > 0 && !recentTags.isEmpty())) 889 return; 890 recentTagsPanel.add(new JLabel(tr("Recently added tags")), GBC.eol()); 891 892 int count = 0; 893 destroyActions(); 894 for (int i = 0; i < tags.size() && count < tagsToShow; i++) { 895 final Tag t = tags.get(i); 896 boolean keyExists = containsDataKey(t.getKey()); 897 if (keyExists && PROPERTY_RECENT_EXISTING.get() == RecentExisting.HIDE) 898 continue; 899 count++; 900 // Create action for reusing the tag, with keyboard shortcut 901 /* POSSIBLE SHORTCUTS: 1,2,3,4,5,6,7,8,9,0=10 */ 902 final Shortcut sc = count > 10 ? null : Shortcut.registerShortcut("properties:recent:" + count, 903 tr("Choose recent tag {0}", count), KeyEvent.VK_0 + (count % 10), Shortcut.CTRL); 904 final JosmAction action = new JosmAction( 905 tr("Choose recent tag {0}", count), null, tr("Use this tag again"), sc, false) { 906 @Override 907 public void actionPerformed(ActionEvent e) { 908 keys.setSelectedItem(t.getKey()); 909 // fix #7951, #8298 - update list of values before setting value (?) 910 focus.focusGained(null); 911 values.setSelectedItem(t.getValue()); 912 selectValuesCombobox(); 913 } 914 }; 915 /* POSSIBLE SHORTCUTS: 1,2,3,4,5,6,7,8,9,0=10 */ 916 final Shortcut scShift = count > 10 ? null : Shortcut.registerShortcut("properties:recent:apply:" + count, 917 tr("Apply recent tag {0}", count), KeyEvent.VK_0 + (count % 10), Shortcut.CTRL_SHIFT); 918 final JosmAction actionShift = new JosmAction( 919 tr("Apply recent tag {0}", count), null, tr("Use this tag again"), scShift, false) { 920 @Override 921 public void actionPerformed(ActionEvent e) { 922 action.actionPerformed(null); 923 performTagAdding(); 924 refreshRecentTags(); 925 selectKeysComboBox(); 926 } 927 }; 928 recentTagsActions.add(action); 929 recentTagsActions.add(actionShift); 930 if (keyExists && PROPERTY_RECENT_EXISTING.get() == RecentExisting.DISABLE) { 931 action.setEnabled(false); 932 } 933 // Find and display icon 934 ImageIcon icon = MapPaintStyles.getNodeIcon(t, false); // Filters deprecated icon 935 if (icon == null) { 936 // If no icon found in map style look at presets 937 Map<String, String> map = new HashMap<>(); 938 map.put(t.getKey(), t.getValue()); 939 for (TaggingPreset tp : TaggingPresets.getMatchingPresets(null, map, false)) { 940 icon = tp.getIcon(); 941 if (icon != null) { 942 break; 943 } 944 } 945 // If still nothing display an empty icon 946 if (icon == null) { 947 icon = new ImageIcon(new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB)); 948 } 949 } 950 GridBagConstraints gbc = new GridBagConstraints(); 951 gbc.ipadx = 5; 952 recentTagsPanel.add(new JLabel(action.isEnabled() ? icon : GuiHelper.getDisabledIcon(icon)), gbc); 953 // Create tag label 954 final String color = action.isEnabled() ? "" : "; color:gray"; 955 final JLabel tagLabel = new JLabel("<html>" 956 + "<style>td{" + color + "}</style>" 957 + "<table><tr>" 958 + "<td>" + count + ".</td>" 959 + "<td style='border:1px solid gray'>" + XmlWriter.encode(t.toString(), true) + '<' + 960 "/td></tr></table></html>"); 961 tagLabel.setFont(tagLabel.getFont().deriveFont(Font.PLAIN)); 962 if (action.isEnabled() && sc != null && scShift != null) { 963 // Register action 964 recentTagsPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(sc.getKeyStroke(), "choose"+count); 965 recentTagsPanel.getActionMap().put("choose"+count, action); 966 recentTagsPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(scShift.getKeyStroke(), "apply"+count); 967 recentTagsPanel.getActionMap().put("apply"+count, actionShift); 968 } 969 if (action.isEnabled()) { 970 // Make the tag label clickable and set tooltip to the action description (this displays also the keyboard shortcut) 971 tagLabel.setToolTipText((String) action.getValue(Action.SHORT_DESCRIPTION)); 972 tagLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); 973 tagLabel.addMouseListener(new MouseAdapter() { 974 @Override 975 public void mouseClicked(MouseEvent e) { 976 action.actionPerformed(null); 977 if (SwingUtilities.isRightMouseButton(e)) { 978 Component component = e.getComponent(); 979 if (component.isShowing()) { 980 new TagPopupMenu(t).show(component, e.getX(), e.getY()); 981 } 982 } else if (e.isShiftDown()) { 983 // add tags on Shift-Click 984 performTagAdding(); 985 refreshRecentTags(); 986 selectKeysComboBox(); 987 } else if (e.getClickCount() > 1) { 988 // add tags and close window on double-click 989 buttonAction(0, null); // emulate OK click and close the dialog 990 } 991 } 992 }); 993 } else { 994 // Disable tag label 995 tagLabel.setEnabled(false); 996 // Explain in the tooltip why 997 tagLabel.setToolTipText(tr("The key ''{0}'' is already used", t.getKey())); 998 } 999 // Finally add label to the resulting panel 1000 JPanel tagPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); 1001 tagPanel.add(tagLabel); 1002 recentTagsPanel.add(tagPanel, GBC.eol().fill(GBC.HORIZONTAL)); 1003 } 1004 // Clear label if no tags were added 1005 if (count == 0) { 1006 recentTagsPanel.removeAll(); 1007 } 1008 } 1009 1010 class TagPopupMenu extends JPopupMenu { 1011 1012 TagPopupMenu(Tag t) { 1013 add(new IgnoreTagAction(tr("Ignore key ''{0}''", t.getKey()), new Tag(t.getKey(), ""))); 1014 add(new IgnoreTagAction(tr("Ignore tag ''{0}''", t), t)); 1015 add(new EditIgnoreTagsAction()); 1016 } 1017 } 1018 1019 class IgnoreTagAction extends AbstractAction { 1020 final transient Tag tag; 1021 1022 IgnoreTagAction(String name, Tag tag) { 1023 super(name); 1024 this.tag = tag; 1025 } 1026 1027 @Override 1028 public void actionPerformed(ActionEvent e) { 1029 try { 1030 if (tagsToIgnore != null) { 1031 recentTags.ignoreTag(tag, tagsToIgnore); 1032 PROPERTY_TAGS_TO_IGNORE.put(tagsToIgnore.writeToString()); 1033 } 1034 } catch (SearchParseError parseError) { 1035 throw new IllegalStateException(parseError); 1036 } 1037 } 1038 } 1039 1040 class EditIgnoreTagsAction extends AbstractAction { 1041 1042 EditIgnoreTagsAction() { 1043 super(tr("Edit ignore list")); 1044 } 1045 1046 @Override 1047 public void actionPerformed(ActionEvent e) { 1048 final SearchSetting newTagsToIngore = SearchAction.showSearchDialog(tagsToIgnore); 1049 if (newTagsToIngore == null) { 1050 return; 1051 } 1052 try { 1053 tagsToIgnore = newTagsToIngore; 1054 recentTags.setTagsToIgnore(tagsToIgnore); 1055 PROPERTY_TAGS_TO_IGNORE.put(tagsToIgnore.writeToString()); 1056 } catch (SearchParseError parseError) { 1057 warnAboutParseError(parseError); 1058 } 1059 } 1060 } 1061 1062 /** 1063 * Destroy the recentTagsActions. 1064 */ 1065 public void destroyActions() { 1066 for (JosmAction action : recentTagsActions) { 1067 action.destroy(); 1068 } 1069 recentTagsActions.clear(); 1070 } 1071 1072 /** 1073 * Read tags from comboboxes and add it to all selected objects 1074 */ 1075 public final void performTagAdding() { 1076 String key = Utils.removeWhiteSpaces(keys.getEditor().getItem().toString()); 1077 String value = Utils.removeWhiteSpaces(values.getEditor().getItem().toString()); 1078 if (key.isEmpty() || value.isEmpty()) 1079 return; 1080 for (OsmPrimitive osm : sel) { 1081 String val = osm.get(key); 1082 if (val != null && !val.equals(value)) { 1083 if (!warnOverwriteKey(tr("You changed the value of ''{0}'' from ''{1}'' to ''{2}''.", key, val, value), 1084 "overwriteAddKey")) 1085 return; 1086 break; 1087 } 1088 } 1089 recentTags.add(new Tag(key, value)); 1090 valueCount.put(key, new TreeMap<String, Integer>()); 1091 AutoCompletionManager.rememberUserInput(key, value, false); 1092 commandCount++; 1093 UndoRedoHandler.getInstance().add(new ChangePropertyCommand(sel, key, value)); 1094 changedKey = key; 1095 clearEntries(); 1096 } 1097 1098 protected void clearEntries() { 1099 keys.getEditor().setItem(""); 1100 values.getEditor().setItem(""); 1101 } 1102 1103 public void undoAllTagsAdding() { 1104 UndoRedoHandler.getInstance().undo(commandCount); 1105 } 1106 1107 private void refreshRecentTags() { 1108 switch (PROPERTY_REFRESH_RECENT.get()) { 1109 case REFRESH: 1110 cacheRecentTags(); 1111 suggestRecentlyAddedTags(); 1112 break; 1113 case STATUS: 1114 suggestRecentlyAddedTags(); 1115 break; 1116 default: // Do nothing 1117 } 1118 } 1119 } 1120}