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