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