source: josm/trunk/src/org/openstreetmap/josm/gui/dialogs/properties/PropertiesDialog.java@ 8846

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

sonar - fb-contrib - minor performance improvements:

  • Method passes constant String of length 1 to character overridden method
  • Method needlessly boxes a boolean constant
  • Method uses iterator().next() on a List to get the first item
  • Method converts String to boxed primitive using excessive boxing
  • Method converts String to primitive using excessive boxing
  • Method creates array using constants
  • Class defines List based fields but uses them like Sets
  • Property svn:eol-style set to native
File size: 55.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.dialogs.properties;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Component;
7import java.awt.Container;
8import java.awt.Font;
9import java.awt.GridBagLayout;
10import java.awt.Point;
11import java.awt.event.ActionEvent;
12import java.awt.event.InputEvent;
13import java.awt.event.KeyEvent;
14import java.awt.event.MouseAdapter;
15import java.awt.event.MouseEvent;
16import java.net.HttpURLConnection;
17import java.net.URI;
18import java.net.URISyntaxException;
19import java.util.ArrayList;
20import java.util.Arrays;
21import java.util.Collection;
22import java.util.Collections;
23import java.util.Comparator;
24import java.util.EnumSet;
25import java.util.HashMap;
26import java.util.HashSet;
27import java.util.LinkedList;
28import java.util.List;
29import java.util.Map;
30import java.util.Map.Entry;
31import java.util.Set;
32import java.util.TreeMap;
33import java.util.TreeSet;
34
35import javax.swing.AbstractAction;
36import javax.swing.JComponent;
37import javax.swing.JLabel;
38import javax.swing.JPanel;
39import javax.swing.JPopupMenu;
40import javax.swing.JScrollPane;
41import javax.swing.JTable;
42import javax.swing.KeyStroke;
43import javax.swing.ListSelectionModel;
44import javax.swing.event.ListSelectionEvent;
45import javax.swing.event.ListSelectionListener;
46import javax.swing.table.DefaultTableCellRenderer;
47import javax.swing.table.DefaultTableModel;
48import javax.swing.table.TableColumnModel;
49import javax.swing.table.TableModel;
50
51import org.openstreetmap.josm.Main;
52import org.openstreetmap.josm.actions.JosmAction;
53import org.openstreetmap.josm.actions.relation.DownloadMembersAction;
54import org.openstreetmap.josm.actions.relation.DownloadSelectedIncompleteMembersAction;
55import org.openstreetmap.josm.actions.relation.SelectInRelationListAction;
56import org.openstreetmap.josm.actions.relation.SelectMembersAction;
57import org.openstreetmap.josm.actions.relation.SelectRelationAction;
58import org.openstreetmap.josm.actions.search.SearchAction.SearchSetting;
59import org.openstreetmap.josm.command.ChangeCommand;
60import org.openstreetmap.josm.command.ChangePropertyCommand;
61import org.openstreetmap.josm.command.Command;
62import org.openstreetmap.josm.data.Preferences.PreferenceChangeEvent;
63import org.openstreetmap.josm.data.SelectionChangedListener;
64import org.openstreetmap.josm.data.osm.IRelation;
65import org.openstreetmap.josm.data.osm.Node;
66import org.openstreetmap.josm.data.osm.OsmPrimitive;
67import org.openstreetmap.josm.data.osm.Relation;
68import org.openstreetmap.josm.data.osm.RelationMember;
69import org.openstreetmap.josm.data.osm.Tag;
70import org.openstreetmap.josm.data.osm.Way;
71import org.openstreetmap.josm.data.osm.event.AbstractDatasetChangedEvent;
72import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter;
73import org.openstreetmap.josm.data.osm.event.DatasetEventManager;
74import org.openstreetmap.josm.data.osm.event.DatasetEventManager.FireMode;
75import org.openstreetmap.josm.data.osm.event.SelectionEventManager;
76import org.openstreetmap.josm.data.preferences.StringProperty;
77import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
78import org.openstreetmap.josm.gui.DefaultNameFormatter;
79import org.openstreetmap.josm.gui.ExtendedDialog;
80import org.openstreetmap.josm.gui.MapView;
81import org.openstreetmap.josm.gui.PopupMenuHandler;
82import org.openstreetmap.josm.gui.SideButton;
83import org.openstreetmap.josm.gui.dialogs.ToggleDialog;
84import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;
85import org.openstreetmap.josm.gui.help.HelpUtil;
86import org.openstreetmap.josm.gui.layer.OsmDataLayer;
87import org.openstreetmap.josm.gui.tagging.PresetHandler;
88import org.openstreetmap.josm.gui.tagging.TaggingPreset;
89import org.openstreetmap.josm.gui.tagging.TaggingPresetType;
90import org.openstreetmap.josm.gui.util.GuiHelper;
91import org.openstreetmap.josm.gui.util.HighlightHelper;
92import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
93import org.openstreetmap.josm.tools.GBC;
94import org.openstreetmap.josm.tools.ImageProvider;
95import org.openstreetmap.josm.tools.InputMapUtils;
96import org.openstreetmap.josm.tools.LanguageInfo;
97import org.openstreetmap.josm.tools.OpenBrowser;
98import org.openstreetmap.josm.tools.Predicates;
99import org.openstreetmap.josm.tools.Shortcut;
100import org.openstreetmap.josm.tools.Utils;
101
102/**
103 * This dialog displays the tags of the current selected primitives.
104 *
105 * If no object is selected, the dialog list is empty.
106 * If only one is selected, all tags of this object are selected.
107 * If more than one object are selected, the sum of all tags are displayed. If the
108 * different objects share the same tag, the shared value is displayed. If they have
109 * different values, all of them are put in a combo box and the string "<different>"
110 * is displayed in italic.
111 *
112 * Below the list, the user can click on an add, modify and delete tag button to
113 * edit the table selection value.
114 *
115 * The command is applied to all selected entries.
116 *
117 * @author imi
118 */
119public class PropertiesDialog extends ToggleDialog
120implements SelectionChangedListener, MapView.EditLayerChangeListener, DataSetListenerAdapter.Listener {
121
122 /**
123 * hook for roadsigns plugin to display a small button in the upper right corner of this dialog
124 */
125 public static final JPanel pluginHook = new JPanel();
126
127 /**
128 * The tag data of selected objects.
129 */
130 private final DefaultTableModel tagData = new ReadOnlyTableModel();
131
132 /**
133 * The membership data of selected objects.
134 */
135 private final DefaultTableModel membershipData = new ReadOnlyTableModel();
136
137 /**
138 * The tags table.
139 */
140 private final JTable tagTable = new JTable(tagData);
141
142 /**
143 * The membership table.
144 */
145 private final JTable membershipTable = new JTable(membershipData);
146
147 /** JPanel containing both previous tables */
148 private final JPanel bothTables = new JPanel();
149
150 // Popup menus
151 private final JPopupMenu tagMenu = new JPopupMenu();
152 private final JPopupMenu membershipMenu = new JPopupMenu();
153 private final JPopupMenu blankSpaceMenu = new JPopupMenu();
154
155 // Popup menu handlers
156 private final transient PopupMenuHandler tagMenuHandler = new PopupMenuHandler(tagMenu);
157 private final transient PopupMenuHandler membershipMenuHandler = new PopupMenuHandler(membershipMenu);
158 private final transient PopupMenuHandler blankSpaceMenuHandler = new PopupMenuHandler(blankSpaceMenu);
159
160 private final transient Map<String, Map<String, Integer>> valueCount = new TreeMap<>();
161 /**
162 * This sub-object is responsible for all adding and editing of tags
163 */
164 private final transient TagEditHelper editHelper = new TagEditHelper(tagData, valueCount);
165
166 private final transient DataSetListenerAdapter dataChangedAdapter = new DataSetListenerAdapter(this);
167 private final HelpAction helpAction = new HelpAction();
168 private final TaginfoAction taginfoAction = new TaginfoAction();
169 private final PasteValueAction pasteValueAction = new PasteValueAction();
170 private final CopyValueAction copyValueAction = new CopyValueAction();
171 private final CopyKeyValueAction copyKeyValueAction = new CopyKeyValueAction();
172 private final CopyAllKeyValueAction copyAllKeyValueAction = new CopyAllKeyValueAction();
173 private final SearchAction searchActionSame = new SearchAction(true);
174 private final SearchAction searchActionAny = new SearchAction(false);
175 private final AddAction addAction = new AddAction();
176 private final EditAction editAction = new EditAction();
177 private final DeleteAction deleteAction = new DeleteAction();
178 private final JosmAction[] josmActions = new JosmAction[]{addAction, editAction, deleteAction};
179
180 // relation actions
181 private final SelectInRelationListAction setRelationSelectionAction = new SelectInRelationListAction();
182 private final SelectRelationAction selectRelationAction = new SelectRelationAction(false);
183 private final SelectRelationAction addRelationToSelectionAction = new SelectRelationAction(true);
184
185 private final DownloadMembersAction downloadMembersAction = new DownloadMembersAction();
186 private final DownloadSelectedIncompleteMembersAction downloadSelectedIncompleteMembersAction =
187 new DownloadSelectedIncompleteMembersAction();
188
189 private final SelectMembersAction selectMembersAction = new SelectMembersAction(false);
190 private final SelectMembersAction addMembersToSelectionAction = new SelectMembersAction(true);
191
192 private final transient HighlightHelper highlightHelper = new HighlightHelper();
193
194 /**
195 * The Add button (needed to be able to disable it)
196 */
197 private final SideButton btnAdd = new SideButton(addAction);
198 /**
199 * The Edit button (needed to be able to disable it)
200 */
201 private final SideButton btnEdit = new SideButton(editAction);
202 /**
203 * The Delete button (needed to be able to disable it)
204 */
205 private final SideButton btnDel = new SideButton(deleteAction);
206 /**
207 * Matching preset display class
208 */
209 private final PresetListPanel presets = new PresetListPanel();
210
211 /**
212 * Text to display when nothing selected.
213 */
214 private final JLabel selectSth = new JLabel("<html><p>"
215 + tr("Select objects for which to change tags.") + "</p></html>");
216
217 private final transient PresetHandler presetHandler = new PresetHandler() {
218 @Override public void updateTags(List<Tag> tags) {
219 Command command = TaggingPreset.createCommand(getSelection(), tags);
220 if (command != null) Main.main.undoRedo.add(command);
221 }
222
223 @Override public Collection<OsmPrimitive> getSelection() {
224 if (Main.main == null) return null;
225 return Main.main.getInProgressSelection();
226 }
227 };
228
229 /**
230 * Create a new PropertiesDialog
231 */
232 public PropertiesDialog() {
233 super(tr("Tags/Memberships"), "propertiesdialog", tr("Tags for selected objects."),
234 Shortcut.registerShortcut("subwindow:properties", tr("Toggle: {0}", tr("Tags/Memberships")), KeyEvent.VK_P,
235 Shortcut.ALT_SHIFT), 150, true);
236
237 HelpUtil.setHelpContext(this, HelpUtil.ht("/Dialog/TagsMembership"));
238
239 setupTagsMenu();
240 buildTagsTable();
241
242 setupMembershipMenu();
243 buildMembershipTable();
244
245 // combine both tables and wrap them in a scrollPane
246 boolean top = Main.pref.getBoolean("properties.presets.top", true);
247 bothTables.setLayout(new GridBagLayout());
248 if (top) {
249 bothTables.add(presets, GBC.std().fill(GBC.HORIZONTAL).insets(5, 2, 5, 2).anchor(GBC.NORTHWEST));
250 double epsilon = Double.MIN_VALUE; // need to set a weight or else anchor value is ignored
251 bothTables.add(pluginHook, GBC.eol().insets(0, 1, 1, 1).anchor(GBC.NORTHEAST).weight(epsilon, epsilon));
252 }
253 bothTables.add(selectSth, GBC.eol().fill().insets(10, 10, 10, 10));
254 bothTables.add(tagTable.getTableHeader(), GBC.eol().fill(GBC.HORIZONTAL));
255 bothTables.add(tagTable, GBC.eol().fill(GBC.BOTH));
256 bothTables.add(membershipTable.getTableHeader(), GBC.eol().fill(GBC.HORIZONTAL));
257 bothTables.add(membershipTable, GBC.eol().fill(GBC.BOTH));
258 if (!top) {
259 bothTables.add(presets, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 2, 5, 2));
260 }
261
262 setupBlankSpaceMenu();
263 setupKeyboardShortcuts();
264
265 // Let the actions know when selection in the tables change
266 tagTable.getSelectionModel().addListSelectionListener(editAction);
267 membershipTable.getSelectionModel().addListSelectionListener(editAction);
268 tagTable.getSelectionModel().addListSelectionListener(deleteAction);
269 membershipTable.getSelectionModel().addListSelectionListener(deleteAction);
270
271 JScrollPane scrollPane = (JScrollPane) createLayout(bothTables, true,
272 Arrays.asList(this.btnAdd, this.btnEdit, this.btnDel));
273
274 MouseClickWatch mouseClickWatch = new MouseClickWatch();
275 tagTable.addMouseListener(mouseClickWatch);
276 membershipTable.addMouseListener(mouseClickWatch);
277 scrollPane.addMouseListener(mouseClickWatch);
278
279 selectSth.setPreferredSize(scrollPane.getSize());
280 presets.setSize(scrollPane.getSize());
281
282 editHelper.loadTagsIfNeeded();
283
284 Main.pref.addPreferenceChangeListener(this);
285 }
286
287 private void buildTagsTable() {
288 // setting up the tags table
289 tagData.setColumnIdentifiers(new String[]{tr("Key"), tr("Value")});
290 tagTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
291 tagTable.getTableHeader().setReorderingAllowed(false);
292
293 PropertiesCellRenderer cellRenderer = new PropertiesCellRenderer();
294 tagTable.getColumnModel().getColumn(0).setCellRenderer(cellRenderer);
295 tagTable.getColumnModel().getColumn(1).setCellRenderer(cellRenderer);
296 }
297
298 private void buildMembershipTable() {
299 membershipData.setColumnIdentifiers(new String[]{tr("Member Of"), tr("Role"), tr("Position")});
300 membershipTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
301
302 TableColumnModel mod = membershipTable.getColumnModel();
303 membershipTable.getTableHeader().setReorderingAllowed(false);
304 mod.getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
305 @Override public Component getTableCellRendererComponent(JTable table, Object value,
306 boolean isSelected, boolean hasFocus, int row, int column) {
307 Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
308 if (value == null)
309 return this;
310 if (c instanceof JLabel) {
311 JLabel label = (JLabel) c;
312 Relation r = (Relation) value;
313 label.setText(r.getDisplayName(DefaultNameFormatter.getInstance()));
314 if (r.isDisabledAndHidden()) {
315 label.setFont(label.getFont().deriveFont(Font.ITALIC));
316 }
317 }
318 return c;
319 }
320 });
321
322 mod.getColumn(1).setCellRenderer(new DefaultTableCellRenderer() {
323 @Override public Component getTableCellRendererComponent(JTable table, Object value,
324 boolean isSelected, boolean hasFocus, int row, int column) {
325 if (value == null)
326 return this;
327 Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
328 boolean isDisabledAndHidden = ((Relation) table.getValueAt(row, 0)).isDisabledAndHidden();
329 if (c instanceof JLabel) {
330 JLabel label = (JLabel) c;
331 label.setText(((MemberInfo) value).getRoleString());
332 if (isDisabledAndHidden) {
333 label.setFont(label.getFont().deriveFont(Font.ITALIC));
334 }
335 }
336 return c;
337 }
338 });
339
340 mod.getColumn(2).setCellRenderer(new DefaultTableCellRenderer() {
341 @Override public Component getTableCellRendererComponent(JTable table, Object value,
342 boolean isSelected, boolean hasFocus, int row, int column) {
343 Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
344 boolean isDisabledAndHidden = ((Relation) table.getValueAt(row, 0)).isDisabledAndHidden();
345 if (c instanceof JLabel) {
346 JLabel label = (JLabel) c;
347 label.setText(((MemberInfo) table.getValueAt(row, 1)).getPositionString());
348 if (isDisabledAndHidden) {
349 label.setFont(label.getFont().deriveFont(Font.ITALIC));
350 }
351 }
352 return c;
353 }
354 });
355 mod.getColumn(2).setPreferredWidth(20);
356 mod.getColumn(1).setPreferredWidth(40);
357 mod.getColumn(0).setPreferredWidth(200);
358 }
359
360 /**
361 * Creates the popup menu @field blankSpaceMenu and its launcher on main panel.
362 */
363 private void setupBlankSpaceMenu() {
364 if (Main.pref.getBoolean("properties.menu.add_edit_delete", true)) {
365 blankSpaceMenuHandler.addAction(addAction);
366 PopupMenuLauncher launcher = new PopupMenuLauncher(blankSpaceMenu) {
367 @Override
368 protected boolean checkSelection(Component component, Point p) {
369 if (component instanceof JTable) {
370 return ((JTable) component).rowAtPoint(p) == -1;
371 }
372 return true;
373 }
374 };
375 bothTables.addMouseListener(launcher);
376 tagTable.addMouseListener(launcher);
377 }
378 }
379
380 /**
381 * Creates the popup menu @field membershipMenu and its launcher on membership table.
382 */
383 private void setupMembershipMenu() {
384 // setting up the membership table
385 if (Main.pref.getBoolean("properties.menu.add_edit_delete", true)) {
386 membershipMenuHandler.addAction(editAction);
387 membershipMenuHandler.addAction(deleteAction);
388 membershipMenu.addSeparator();
389 }
390 membershipMenuHandler.addAction(setRelationSelectionAction);
391 membershipMenuHandler.addAction(selectRelationAction);
392 membershipMenuHandler.addAction(addRelationToSelectionAction);
393 membershipMenuHandler.addAction(selectMembersAction);
394 membershipMenuHandler.addAction(addMembersToSelectionAction);
395 membershipMenu.addSeparator();
396 membershipMenuHandler.addAction(downloadMembersAction);
397 membershipMenuHandler.addAction(downloadSelectedIncompleteMembersAction);
398 membershipMenu.addSeparator();
399 membershipMenu.add(helpAction);
400 membershipMenu.add(taginfoAction);
401
402 membershipTable.addMouseListener(new PopupMenuLauncher(membershipMenu) {
403 @Override
404 protected int checkTableSelection(JTable table, Point p) {
405 int row = super.checkTableSelection(table, p);
406 List<Relation> rels = new ArrayList<>();
407 for (int i: table.getSelectedRows()) {
408 rels.add((Relation) table.getValueAt(i, 0));
409 }
410 membershipMenuHandler.setPrimitives(rels);
411 return row;
412 }
413
414 @Override
415 public void mouseClicked(MouseEvent e) {
416 //update highlights
417 if (Main.isDisplayingMapView()) {
418 int row = membershipTable.rowAtPoint(e.getPoint());
419 if (row >= 0) {
420 if (highlightHelper.highlightOnly((Relation) membershipTable.getValueAt(row, 0))) {
421 Main.map.mapView.repaint();
422 }
423 }
424 }
425 super.mouseClicked(e);
426 }
427
428 @Override
429 public void mouseExited(MouseEvent me) {
430 highlightHelper.clear();
431 }
432 });
433 }
434
435 /**
436 * Creates the popup menu @field tagMenu and its launcher on tag table.
437 */
438 private void setupTagsMenu() {
439 if (Main.pref.getBoolean("properties.menu.add_edit_delete", true)) {
440 tagMenu.add(addAction);
441 tagMenu.add(editAction);
442 tagMenu.add(deleteAction);
443 tagMenu.addSeparator();
444 }
445 tagMenu.add(pasteValueAction);
446 tagMenu.add(copyValueAction);
447 tagMenu.add(copyKeyValueAction);
448 tagMenu.add(copyAllKeyValueAction);
449 tagMenu.addSeparator();
450 tagMenu.add(searchActionAny);
451 tagMenu.add(searchActionSame);
452 tagMenu.addSeparator();
453 tagMenu.add(helpAction);
454 tagMenu.add(taginfoAction);
455 tagTable.addMouseListener(new PopupMenuLauncher(tagMenu));
456 }
457
458 /**
459 * Assigns all needed keys like Enter and Spacebar to most important actions.
460 */
461 private void setupKeyboardShortcuts() {
462
463 // ENTER = editAction, open "edit" dialog
464 tagTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
465 .put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "onTableEnter");
466 tagTable.getActionMap().put("onTableEnter", editAction);
467 membershipTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
468 .put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "onTableEnter");
469 membershipTable.getActionMap().put("onTableEnter", editAction);
470
471 // INSERT button = addAction, open "add tag" dialog
472 tagTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
473 .put(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0), "onTableInsert");
474 tagTable.getActionMap().put("onTableInsert", addAction);
475
476 // unassign some standard shortcuts for JTable to allow upload / download / image browsing
477 InputMapUtils.unassignCtrlShiftUpDown(tagTable, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
478 InputMapUtils.unassignPageUpDown(tagTable, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
479
480 // unassign some standard shortcuts for correct copy-pasting, fix #8508
481 tagTable.setTransferHandler(null);
482
483 tagTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
484 .put(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK), "onCopy");
485 tagTable.getActionMap().put("onCopy", copyKeyValueAction);
486
487 // allow using enter to add tags for all look&feel configurations
488 InputMapUtils.enableEnter(this.btnAdd);
489
490 // DEL button = deleteAction
491 getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
492 KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete"
493 );
494 getActionMap().put("delete", deleteAction);
495
496 // F1 button = custom help action
497 getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
498 KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), "onHelp");
499 getActionMap().put("onHelp", helpAction);
500 }
501
502 /**
503 * This simply fires up an {@link RelationEditor} for the relation shown; everything else
504 * is the editor's business.
505 *
506 * @param row position
507 */
508 private void editMembership(int row) {
509 Relation relation = (Relation) membershipData.getValueAt(row, 0);
510 Main.map.relationListDialog.selectRelation(relation);
511 RelationEditor.getEditor(
512 Main.main.getEditLayer(),
513 relation,
514 ((MemberInfo) membershipData.getValueAt(row, 1)).role
515 ).setVisible(true);
516 }
517
518 private int findRow(TableModel model, Object value) {
519 for (int i = 0; i < model.getRowCount(); i++) {
520 if (model.getValueAt(i, 0).equals(value))
521 return i;
522 }
523 return -1;
524 }
525
526 /**
527 * Update selection status, call @{link #selectionChanged} function.
528 */
529 private void updateSelection() {
530 // Parameter is ignored in this class
531 selectionChanged(null);
532 }
533
534 @Override
535 public void showNotify() {
536 DatasetEventManager.getInstance().addDatasetListener(dataChangedAdapter, FireMode.IN_EDT_CONSOLIDATED);
537 SelectionEventManager.getInstance().addSelectionListener(this, FireMode.IN_EDT_CONSOLIDATED);
538 MapView.addEditLayerChangeListener(this);
539 for (JosmAction action : josmActions) {
540 Main.registerActionShortcut(action);
541 }
542 updateSelection();
543 }
544
545 @Override
546 public void hideNotify() {
547 DatasetEventManager.getInstance().removeDatasetListener(dataChangedAdapter);
548 SelectionEventManager.getInstance().removeSelectionListener(this);
549 MapView.removeEditLayerChangeListener(this);
550 for (JosmAction action : josmActions) {
551 Main.unregisterActionShortcut(action);
552 }
553 }
554
555 @Override
556 public void setVisible(boolean b) {
557 super.setVisible(b);
558 if (b && Main.main.getCurrentDataSet() != null) {
559 updateSelection();
560 }
561 }
562
563 @Override
564 public void destroy() {
565 super.destroy();
566 Main.pref.removePreferenceChangeListener(this);
567 for (JosmAction action : josmActions) {
568 action.destroy();
569 }
570 Container parent = pluginHook.getParent();
571 if (parent != null) {
572 parent.remove(pluginHook);
573 }
574 }
575
576 @Override
577 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
578 if (!isVisible())
579 return;
580 if (tagTable == null)
581 return; // selection changed may be received in base class constructor before init
582 if (tagTable.getCellEditor() != null) {
583 tagTable.getCellEditor().cancelCellEditing();
584 }
585
586 // Ignore parameter as we do not want to operate always on real selection here, especially in draw mode
587 Collection<OsmPrimitive> newSel = Main.main.getInProgressSelection();
588 if (newSel == null) {
589 newSel = Collections.<OsmPrimitive>emptyList();
590 }
591
592 String selectedTag;
593 Relation selectedRelation = null;
594 selectedTag = editHelper.getChangedKey(); // select last added or last edited key by default
595 if (selectedTag == null && tagTable.getSelectedRowCount() == 1) {
596 selectedTag = (String) tagData.getValueAt(tagTable.getSelectedRow(), 0);
597 }
598 if (membershipTable.getSelectedRowCount() == 1) {
599 selectedRelation = (Relation) membershipData.getValueAt(membershipTable.getSelectedRow(), 0);
600 }
601
602 // re-load tag data
603 tagData.setRowCount(0);
604
605 final boolean displayDiscardableKeys = Main.pref.getBoolean("display.discardable-keys", false);
606 final Map<String, Integer> keyCount = new HashMap<>();
607 final Map<String, String> tags = new HashMap<>();
608 valueCount.clear();
609 Set<TaggingPresetType> types = EnumSet.noneOf(TaggingPresetType.class);
610 for (OsmPrimitive osm : newSel) {
611 types.add(TaggingPresetType.forPrimitive(osm));
612 for (String key : osm.keySet()) {
613 if (displayDiscardableKeys || !OsmPrimitive.getDiscardableKeys().contains(key)) {
614 String value = osm.get(key);
615 keyCount.put(key, keyCount.containsKey(key) ? keyCount.get(key) + 1 : 1);
616 if (valueCount.containsKey(key)) {
617 Map<String, Integer> v = valueCount.get(key);
618 v.put(value, v.containsKey(value) ? v.get(value) + 1 : 1);
619 } else {
620 Map<String, Integer> v = new TreeMap<>();
621 v.put(value, 1);
622 valueCount.put(key, v);
623 }
624 }
625 }
626 }
627 for (Entry<String, Map<String, Integer>> e : valueCount.entrySet()) {
628 int count = 0;
629 for (Entry<String, Integer> e1 : e.getValue().entrySet()) {
630 count += e1.getValue();
631 }
632 if (count < newSel.size()) {
633 e.getValue().put("", newSel.size() - count);
634 }
635 tagData.addRow(new Object[]{e.getKey(), e.getValue()});
636 tags.put(e.getKey(), e.getValue().size() == 1
637 ? e.getValue().keySet().iterator().next() : tr("<different>"));
638 }
639
640 membershipData.setRowCount(0);
641
642 Map<Relation, MemberInfo> roles = new HashMap<>();
643 for (OsmPrimitive primitive: newSel) {
644 for (OsmPrimitive ref: primitive.getReferrers(true)) {
645 if (ref instanceof Relation && !ref.isIncomplete() && !ref.isDeleted()) {
646 Relation r = (Relation) ref;
647 MemberInfo mi = roles.get(r);
648 if (mi == null) {
649 mi = new MemberInfo(newSel);
650 }
651 roles.put(r, mi);
652 int i = 1;
653 for (RelationMember m : r.getMembers()) {
654 if (m.getMember() == primitive) {
655 mi.add(m, i);
656 }
657 ++i;
658 }
659 }
660 }
661 }
662
663 List<Relation> sortedRelations = new ArrayList<>(roles.keySet());
664 Collections.sort(sortedRelations, new Comparator<Relation>() {
665 @Override public int compare(Relation o1, Relation o2) {
666 int comp = Boolean.valueOf(o1.isDisabledAndHidden()).compareTo(o2.isDisabledAndHidden());
667 return comp != 0 ? comp : DefaultNameFormatter.getInstance().getRelationComparator().compare(o1, o2);
668 }}
669 );
670
671 for (Relation r: sortedRelations) {
672 membershipData.addRow(new Object[]{r, roles.get(r)});
673 }
674
675 presets.updatePresets(types, tags, presetHandler);
676
677 membershipTable.getTableHeader().setVisible(membershipData.getRowCount() > 0);
678 membershipTable.setVisible(membershipData.getRowCount() > 0);
679
680 boolean hasSelection = !newSel.isEmpty();
681 boolean hasTags = hasSelection && tagData.getRowCount() > 0;
682 boolean hasMemberships = hasSelection && membershipData.getRowCount() > 0;
683 addAction.setEnabled(hasSelection);
684 editAction.setEnabled(hasTags || hasMemberships);
685 deleteAction.setEnabled(hasTags || hasMemberships);
686 tagTable.setVisible(hasTags);
687 tagTable.getTableHeader().setVisible(hasTags);
688 selectSth.setVisible(!hasSelection);
689 pluginHook.setVisible(hasSelection);
690
691 int selectedIndex;
692 if (selectedTag != null && (selectedIndex = findRow(tagData, selectedTag)) != -1) {
693 tagTable.changeSelection(selectedIndex, 0, false, false);
694 } else if (selectedRelation != null && (selectedIndex = findRow(membershipData, selectedRelation)) != -1) {
695 membershipTable.changeSelection(selectedIndex, 0, false, false);
696 } else if (hasTags) {
697 tagTable.changeSelection(0, 0, false, false);
698 } else if (hasMemberships) {
699 membershipTable.changeSelection(0, 0, false, false);
700 }
701
702 if (tagData.getRowCount() != 0 || membershipData.getRowCount() != 0) {
703 if (newSel.size() > 1) {
704 setTitle(tr("Objects: {2} / Tags: {0} / Memberships: {1}",
705 tagData.getRowCount(), membershipData.getRowCount(), newSel.size()));
706 } else {
707 setTitle(tr("Tags: {0} / Memberships: {1}",
708 tagData.getRowCount(), membershipData.getRowCount()));
709 }
710 } else {
711 setTitle(tr("Tags / Memberships"));
712 }
713 }
714
715 /* ---------------------------------------------------------------------------------- */
716 /* EditLayerChangeListener */
717 /* ---------------------------------------------------------------------------------- */
718 @Override
719 public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) {
720 if (newLayer == null) editHelper.saveTagsIfNeeded();
721 // it is time to save history of tags
722 GuiHelper.runInEDT(new Runnable() {
723 @Override public void run() {
724 updateSelection();
725 }
726 });
727 }
728
729 @Override
730 public void processDatasetEvent(AbstractDatasetChangedEvent event) {
731 updateSelection();
732 }
733
734 /**
735 * Replies the tag popup menu handler.
736 * @return The tag popup menu handler
737 */
738 public PopupMenuHandler getPropertyPopupMenuHandler() {
739 return tagMenuHandler;
740 }
741
742 /**
743 * Returns the selected tag.
744 * @return The current selected tag
745 */
746 @SuppressWarnings("unchecked")
747 public Tag getSelectedProperty() {
748 int row = tagTable.getSelectedRow();
749 if (row == -1) return null;
750 Map<String, Integer> map = (TreeMap<String, Integer>) tagData.getValueAt(row, 1);
751 return new Tag(
752 tagData.getValueAt(row, 0).toString(),
753 map.size() > 1 ? "" : map.keySet().iterator().next());
754 }
755
756 /**
757 * Replies the membership popup menu handler.
758 * @return The membership popup menu handler
759 */
760 public PopupMenuHandler getMembershipPopupMenuHandler() {
761 return membershipMenuHandler;
762 }
763
764 /**
765 * Returns the selected relation membership.
766 * @return The current selected relation membership
767 */
768 public IRelation getSelectedMembershipRelation() {
769 int row = membershipTable.getSelectedRow();
770 return row > -1 ? (IRelation) membershipData.getValueAt(row, 0) : null;
771 }
772
773 /**
774 * Class that watches for mouse clicks
775 * @author imi
776 */
777 public class MouseClickWatch extends MouseAdapter {
778 @Override
779 public void mouseClicked(MouseEvent e) {
780 if (e.getClickCount() < 2) {
781 // single click, clear selection in other table not clicked in
782 if (e.getSource() == tagTable) {
783 membershipTable.clearSelection();
784 } else if (e.getSource() == membershipTable) {
785 tagTable.clearSelection();
786 }
787 } else if (e.getSource() == tagTable) {
788 // double click, edit or add tag
789 int row = tagTable.rowAtPoint(e.getPoint());
790 if (row > -1) {
791 boolean focusOnKey = tagTable.columnAtPoint(e.getPoint()) == 0;
792 editHelper.editTag(row, focusOnKey);
793 } else {
794 editHelper.addTag();
795 btnAdd.requestFocusInWindow();
796 }
797 } else if (e.getSource() == membershipTable) {
798 int row = membershipTable.rowAtPoint(e.getPoint());
799 if (row > -1) {
800 editMembership(row);
801 }
802 } else {
803 editHelper.addTag();
804 btnAdd.requestFocusInWindow();
805 }
806 }
807
808 @Override
809 public void mousePressed(MouseEvent e) {
810 if (e.getSource() == tagTable) {
811 membershipTable.clearSelection();
812 } else if (e.getSource() == membershipTable) {
813 tagTable.clearSelection();
814 }
815 }
816 }
817
818 static class MemberInfo {
819 private List<RelationMember> role = new ArrayList<>();
820 private Set<OsmPrimitive> members = new HashSet<>();
821 private List<Integer> position = new ArrayList<>();
822 private Iterable<OsmPrimitive> selection;
823 private String positionString;
824 private String roleString;
825
826 MemberInfo(Iterable<OsmPrimitive> selection) {
827 this.selection = selection;
828 }
829
830 void add(RelationMember r, Integer p) {
831 role.add(r);
832 members.add(r.getMember());
833 position.add(p);
834 }
835
836 String getPositionString() {
837 if (positionString == null) {
838 positionString = Utils.getPositionListString(position);
839 // if not all objects from the selection are member of this relation
840 if (Utils.exists(selection, Predicates.not(Predicates.inCollection(members)))) {
841 positionString += ",\u2717";
842 }
843 members = null;
844 position = null;
845 selection = null;
846 }
847 return Utils.shortenString(positionString, 20);
848 }
849
850 String getRoleString() {
851 if (roleString == null) {
852 for (RelationMember r : role) {
853 if (roleString == null) {
854 roleString = r.getRole();
855 } else if (!roleString.equals(r.getRole())) {
856 roleString = tr("<different>");
857 break;
858 }
859 }
860 }
861 return roleString;
862 }
863
864 @Override
865 public String toString() {
866 return "MemberInfo{" +
867 "roles='" + roleString + '\'' +
868 ", positions='" + positionString + '\'' +
869 '}';
870 }
871 }
872
873 /**
874 * Class that allows fast creation of read-only table model with String columns
875 */
876 public static class ReadOnlyTableModel extends DefaultTableModel {
877 @Override
878 public boolean isCellEditable(int row, int column) {
879 return false;
880 }
881
882 @Override
883 public Class<?> getColumnClass(int columnIndex) {
884 return String.class;
885 }
886 }
887
888 /**
889 * Action handling delete button press in properties dialog.
890 */
891 class DeleteAction extends JosmAction implements ListSelectionListener {
892
893 private static final String DELETE_FROM_RELATION_PREF = "delete_from_relation";
894
895 DeleteAction() {
896 super(tr("Delete"), /* ICON() */ "dialogs/delete", tr("Delete the selected key in all objects"),
897 Shortcut.registerShortcut("properties:delete", tr("Delete Tags"), KeyEvent.VK_D,
898 Shortcut.ALT_CTRL_SHIFT), false);
899 updateEnabledState();
900 }
901
902 protected void deleteTags(int[] rows) {
903 // convert list of rows to HashMap (and find gap for nextKey)
904 Map<String, String> tags = new HashMap<>(rows.length);
905 int nextKeyIndex = rows[0];
906 for (int row : rows) {
907 String key = tagData.getValueAt(row, 0).toString();
908 if (row == nextKeyIndex + 1) {
909 nextKeyIndex = row; // no gap yet
910 }
911 tags.put(key, null);
912 }
913
914 // find key to select after deleting other tags
915 String nextKey = null;
916 int rowCount = tagData.getRowCount();
917 if (rowCount > rows.length) {
918 if (nextKeyIndex == rows[rows.length-1]) {
919 // no gap found, pick next or previous key in list
920 nextKeyIndex = (nextKeyIndex + 1 < rowCount ? nextKeyIndex + 1 : rows[0] - 1);
921 } else {
922 // gap found
923 nextKeyIndex++;
924 }
925 nextKey = (String) tagData.getValueAt(nextKeyIndex, 0);
926 }
927
928 Collection<OsmPrimitive> sel = Main.main.getInProgressSelection();
929 Main.main.undoRedo.add(new ChangePropertyCommand(sel, tags));
930
931 membershipTable.clearSelection();
932 if (nextKey != null) {
933 tagTable.changeSelection(findRow(tagData, nextKey), 0, false, false);
934 }
935 }
936
937 protected void deleteFromRelation(int row) {
938 Relation cur = (Relation) membershipData.getValueAt(row, 0);
939
940 Relation nextRelation = null;
941 int rowCount = membershipTable.getRowCount();
942 if (rowCount > 1) {
943 nextRelation = (Relation) membershipData.getValueAt(row + 1 < rowCount ? row + 1 : row - 1, 0);
944 }
945
946 ExtendedDialog ed = new ExtendedDialog(Main.parent,
947 tr("Change relation"),
948 new String[] {tr("Delete from relation"), tr("Cancel")});
949 ed.setButtonIcons(new String[] {"dialogs/delete", "cancel"});
950 ed.setContent(tr("Really delete selection from relation {0}?", cur.getDisplayName(DefaultNameFormatter.getInstance())));
951 ed.toggleEnable(DELETE_FROM_RELATION_PREF);
952 ed.showDialog();
953
954 if (ed.getValue() != 1)
955 return;
956
957 Relation rel = new Relation(cur);
958 for (OsmPrimitive primitive: Main.main.getInProgressSelection()) {
959 rel.removeMembersFor(primitive);
960 }
961 Main.main.undoRedo.add(new ChangeCommand(cur, rel));
962
963 tagTable.clearSelection();
964 if (nextRelation != null) {
965 membershipTable.changeSelection(findRow(membershipData, nextRelation), 0, false, false);
966 }
967 }
968
969 @Override
970 public void actionPerformed(ActionEvent e) {
971 if (tagTable.getSelectedRowCount() > 0) {
972 int[] rows = tagTable.getSelectedRows();
973 deleteTags(rows);
974 } else if (membershipTable.getSelectedRowCount() > 0) {
975 ConditionalOptionPaneUtil.startBulkOperation(DELETE_FROM_RELATION_PREF);
976 int[] rows = membershipTable.getSelectedRows();
977 // delete from last relation to conserve row numbers in the table
978 for (int i = rows.length-1; i >= 0; i--) {
979 deleteFromRelation(rows[i]);
980 }
981 ConditionalOptionPaneUtil.endBulkOperation(DELETE_FROM_RELATION_PREF);
982 }
983 }
984
985 @Override
986 protected final void updateEnabledState() {
987 setEnabled(
988 (tagTable != null && tagTable.getSelectedRowCount() >= 1)
989 || (membershipTable != null && membershipTable.getSelectedRowCount() > 0)
990 );
991 }
992
993 @Override
994 public void valueChanged(ListSelectionEvent e) {
995 updateEnabledState();
996 }
997 }
998
999 /**
1000 * Action handling add button press in properties dialog.
1001 */
1002 class AddAction extends JosmAction {
1003 AddAction() {
1004 super(tr("Add"), /* ICON() */ "dialogs/add", tr("Add a new key/value pair to all objects"),
1005 Shortcut.registerShortcut("properties:add", tr("Add Tag"), KeyEvent.VK_A,
1006 Shortcut.ALT), false);
1007 }
1008
1009 @Override
1010 public void actionPerformed(ActionEvent e) {
1011 editHelper.addTag();
1012 btnAdd.requestFocusInWindow();
1013 }
1014 }
1015
1016 /**
1017 * Action handling edit button press in properties dialog.
1018 */
1019 class EditAction extends JosmAction implements ListSelectionListener {
1020 EditAction() {
1021 super(tr("Edit"), /* ICON() */ "dialogs/edit", tr("Edit the value of the selected key for all objects"),
1022 Shortcut.registerShortcut("properties:edit", tr("Edit Tags"), KeyEvent.VK_S,
1023 Shortcut.ALT), false);
1024 updateEnabledState();
1025 }
1026
1027 @Override
1028 public void actionPerformed(ActionEvent e) {
1029 if (!isEnabled())
1030 return;
1031 if (tagTable.getSelectedRowCount() == 1) {
1032 int row = tagTable.getSelectedRow();
1033 editHelper.editTag(row, false);
1034 } else if (membershipTable.getSelectedRowCount() == 1) {
1035 int row = membershipTable.getSelectedRow();
1036 editMembership(row);
1037 }
1038 }
1039
1040 @Override
1041 protected void updateEnabledState() {
1042 setEnabled(
1043 (tagTable != null && tagTable.getSelectedRowCount() == 1)
1044 ^ (membershipTable != null && membershipTable.getSelectedRowCount() == 1)
1045 );
1046 }
1047
1048 @Override
1049 public void valueChanged(ListSelectionEvent e) {
1050 updateEnabledState();
1051 }
1052 }
1053
1054 class HelpAction extends AbstractAction {
1055 HelpAction() {
1056 putValue(NAME, tr("Go to OSM wiki for tag help (F1)"));
1057 putValue(SHORT_DESCRIPTION, tr("Launch browser with wiki help for selected object"));
1058 putValue(SMALL_ICON, ImageProvider.get("dialogs", "search"));
1059 }
1060
1061 @Override
1062 public void actionPerformed(ActionEvent e) {
1063 try {
1064 String base = Main.pref.get("url.openstreetmap-wiki", "http://wiki.openstreetmap.org/wiki/");
1065 String lang = LanguageInfo.getWikiLanguagePrefix();
1066 final List<URI> uris = new ArrayList<>();
1067 int row;
1068 if (tagTable.getSelectedRowCount() == 1) {
1069 row = tagTable.getSelectedRow();
1070 String key = Utils.encodeUrl(tagData.getValueAt(row, 0).toString());
1071 @SuppressWarnings("unchecked")
1072 Map<String, Integer> m = (Map<String, Integer>) tagData.getValueAt(row, 1);
1073 String val = Utils.encodeUrl(m.entrySet().iterator().next().getKey());
1074
1075 uris.add(new URI(String.format("%s%sTag:%s=%s", base, lang, key, val)));
1076 uris.add(new URI(String.format("%sTag:%s=%s", base, key, val)));
1077 uris.add(new URI(String.format("%s%sKey:%s", base, lang, key)));
1078 uris.add(new URI(String.format("%sKey:%s", base, key)));
1079 uris.add(new URI(String.format("%s%sMap_Features", base, lang)));
1080 uris.add(new URI(String.format("%sMap_Features", base)));
1081 } else if (membershipTable.getSelectedRowCount() == 1) {
1082 row = membershipTable.getSelectedRow();
1083 String type = ((Relation) membershipData.getValueAt(row, 0)).get("type");
1084 if (type != null) {
1085 type = Utils.encodeUrl(type);
1086 }
1087
1088 if (type != null && !type.isEmpty()) {
1089 uris.add(new URI(String.format("%s%sRelation:%s", base, lang, type)));
1090 uris.add(new URI(String.format("%sRelation:%s", base, type)));
1091 }
1092
1093 uris.add(new URI(String.format("%s%sRelations", base, lang)));
1094 uris.add(new URI(String.format("%sRelations", base)));
1095 } else {
1096 // give the generic help page, if more than one element is selected
1097 uris.add(new URI(String.format("%s%sMap_Features", base, lang)));
1098 uris.add(new URI(String.format("%sMap_Features", base)));
1099 }
1100
1101 Main.worker.execute(new Runnable() {
1102 @Override public void run() {
1103 try {
1104 // find a page that actually exists in the wiki
1105 HttpURLConnection conn;
1106 for (URI u : uris) {
1107 conn = Utils.openHttpConnection(u.toURL());
1108 conn.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect", 15)*1000);
1109
1110 if (conn.getResponseCode() != 200) {
1111 Main.info("{0} does not exist", u);
1112 conn.disconnect();
1113 } else {
1114 int osize = conn.getContentLength();
1115 if (osize > -1) {
1116 conn.disconnect();
1117
1118 conn = Utils.openHttpConnection(new URI(u.toString()
1119 .replace("=", "%3D") /* do not URLencode whole string! */
1120 .replaceFirst("/wiki/", "/w/index.php?redirect=no&title=")
1121 ).toURL());
1122 conn.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect", 15)*1000);
1123 }
1124
1125 /* redirect pages have different content length, but retrieving a "nonredirect"
1126 * page using index.php and the direct-link method gives slightly different
1127 * content lengths, so we have to be fuzzy.. (this is UGLY, recode if u know better)
1128 */
1129 if (conn.getContentLength() != -1 && osize > -1 && Math.abs(conn.getContentLength() - osize) > 200) {
1130 Main.info("{0} is a mediawiki redirect", u);
1131 conn.disconnect();
1132 } else {
1133 Main.info("browsing to {0}", u);
1134 conn.disconnect();
1135
1136 OpenBrowser.displayUrl(u.toString());
1137 break;
1138 }
1139 }
1140 }
1141 } catch (Exception e) {
1142 Main.error(e);
1143 }
1144 }
1145 });
1146 } catch (URISyntaxException e1) {
1147 Main.error(e1);
1148 }
1149 }
1150 }
1151
1152 class TaginfoAction extends JosmAction {
1153
1154 final StringProperty TAGINFO_URL_PROP = new StringProperty("taginfo.url", "https://taginfo.openstreetmap.org/");
1155
1156 TaginfoAction() {
1157 super(tr("Go to Taginfo"), "dialogs/taginfo", tr("Launch browser with Taginfo statistics for selected object"), null, false);
1158 }
1159
1160 @Override
1161 @SuppressWarnings("unchecked")
1162 public void actionPerformed(ActionEvent e) {
1163 final String url;
1164 if (tagTable.getSelectedRowCount() == 1) {
1165 final int row = tagTable.getSelectedRow();
1166 final String key = Utils.encodeUrl(tagData.getValueAt(row, 0).toString());
1167 Map<String, Integer> values = (Map<String, Integer>) tagData.getValueAt(row, 1);
1168 if (values.size() == 1) {
1169 url = TAGINFO_URL_PROP.get() + "tags/" + key /* do not URL encode key, otherwise addr:street does not work */
1170 + '=' + Utils.encodeUrl(values.keySet().iterator().next());
1171 } else {
1172 url = TAGINFO_URL_PROP.get() + "keys/" + key; /* do not URL encode key, otherwise addr:street does not work */
1173 }
1174 } else if (membershipTable.getSelectedRowCount() == 1) {
1175 final String type = ((Relation) membershipData.getValueAt(membershipTable.getSelectedRow(), 0)).get("type");
1176 url = TAGINFO_URL_PROP.get() + "relations/" + type;
1177 } else {
1178 return;
1179 }
1180 OpenBrowser.displayUrl(url);
1181 }
1182 }
1183
1184 class PasteValueAction extends AbstractAction {
1185 PasteValueAction() {
1186 putValue(NAME, tr("Paste Value"));
1187 putValue(SHORT_DESCRIPTION, tr("Paste the value of the selected tag from clipboard"));
1188 }
1189
1190 @Override
1191 public void actionPerformed(ActionEvent ae) {
1192 if (tagTable.getSelectedRowCount() != 1)
1193 return;
1194 String key = tagData.getValueAt(tagTable.getSelectedRow(), 0).toString();
1195 Collection<OsmPrimitive> sel = Main.main.getInProgressSelection();
1196 String clipboard = Utils.getClipboardContent();
1197 if (sel.isEmpty() || clipboard == null)
1198 return;
1199 Main.main.undoRedo.add(new ChangePropertyCommand(sel, key, Utils.strip(clipboard)));
1200 }
1201 }
1202
1203 abstract class AbstractCopyAction extends AbstractAction {
1204
1205 protected abstract Collection<String> getString(OsmPrimitive p, String key);
1206
1207 @Override
1208 public void actionPerformed(ActionEvent ae) {
1209 int[] rows = tagTable.getSelectedRows();
1210 Set<String> values = new TreeSet<>();
1211 Collection<OsmPrimitive> sel = Main.main.getInProgressSelection();
1212 if (rows.length == 0 || sel.isEmpty()) return;
1213
1214 for (int row: rows) {
1215 String key = tagData.getValueAt(row, 0).toString();
1216 if (sel.isEmpty())
1217 return;
1218 for (OsmPrimitive p : sel) {
1219 Collection<String> s = getString(p, key);
1220 if (s != null) {
1221 values.addAll(s);
1222 }
1223 }
1224 }
1225 if (!values.isEmpty()) {
1226 Utils.copyToClipboard(Utils.join("\n", values));
1227 }
1228 }
1229 }
1230
1231 class CopyValueAction extends AbstractCopyAction {
1232
1233 /**
1234 * Constructs a new {@code CopyValueAction}.
1235 */
1236 CopyValueAction() {
1237 putValue(NAME, tr("Copy Value"));
1238 putValue(SHORT_DESCRIPTION, tr("Copy the value of the selected tag to clipboard"));
1239 }
1240
1241 @Override
1242 protected Collection<String> getString(OsmPrimitive p, String key) {
1243 String v = p.get(key);
1244 return v == null ? null : Collections.singleton(v);
1245 }
1246 }
1247
1248 class CopyKeyValueAction extends AbstractCopyAction {
1249
1250 CopyKeyValueAction() {
1251 putValue(NAME, tr("Copy selected Key(s)/Value(s)"));
1252 putValue(SHORT_DESCRIPTION, tr("Copy the key and value of the selected tag(s) to clipboard"));
1253 }
1254
1255 @Override
1256 protected Collection<String> getString(OsmPrimitive p, String key) {
1257 String v = p.get(key);
1258 return v == null ? null : Collections.singleton(new Tag(key, v).toString());
1259 }
1260 }
1261
1262 class CopyAllKeyValueAction extends AbstractCopyAction {
1263
1264 CopyAllKeyValueAction() {
1265 putValue(NAME, tr("Copy all Keys/Values"));
1266 putValue(SHORT_DESCRIPTION, tr("Copy the key and value of all the tags to clipboard"));
1267 }
1268
1269 @Override
1270 protected Collection<String> getString(OsmPrimitive p, String key) {
1271 List<String> r = new LinkedList<>();
1272 for (Entry<String, String> kv : p.getKeys().entrySet()) {
1273 r.add(new Tag(kv.getKey(), kv.getValue()).toString());
1274 }
1275 return r;
1276 }
1277 }
1278
1279 class SearchAction extends AbstractAction {
1280 private final boolean sameType;
1281
1282 SearchAction(boolean sameType) {
1283 this.sameType = sameType;
1284 if (sameType) {
1285 putValue(NAME, tr("Search Key/Value/Type"));
1286 putValue(SHORT_DESCRIPTION, tr("Search with the key and value of the selected tag, restrict to type (i.e., node/way/relation)"));
1287 } else {
1288 putValue(NAME, tr("Search Key/Value"));
1289 putValue(SHORT_DESCRIPTION, tr("Search with the key and value of the selected tag"));
1290 }
1291 }
1292
1293 @Override
1294 public void actionPerformed(ActionEvent e) {
1295 if (tagTable.getSelectedRowCount() != 1)
1296 return;
1297 String key = tagData.getValueAt(tagTable.getSelectedRow(), 0).toString();
1298 Collection<OsmPrimitive> sel = Main.main.getInProgressSelection();
1299 if (sel.isEmpty())
1300 return;
1301 String sep = "";
1302 StringBuilder s = new StringBuilder();
1303 for (OsmPrimitive p : sel) {
1304 String val = p.get(key);
1305 if (val == null) {
1306 continue;
1307 }
1308 String t = "";
1309 if (!sameType) {
1310 t = "";
1311 } else if (p instanceof Node) {
1312 t = "type:node ";
1313 } else if (p instanceof Way) {
1314 t = "type:way ";
1315 } else if (p instanceof Relation) {
1316 t = "type:relation ";
1317 }
1318 s.append(sep).append('(').append(t).append('"').append(
1319 org.openstreetmap.josm.actions.search.SearchAction.escapeStringForSearch(key)).append("\"=\"").append(
1320 org.openstreetmap.josm.actions.search.SearchAction.escapeStringForSearch(val)).append("\")");
1321 sep = " OR ";
1322 }
1323
1324 final SearchSetting ss = new SearchSetting();
1325 ss.text = s.toString();
1326 ss.caseSensitive = true;
1327 org.openstreetmap.josm.actions.search.SearchAction.searchWithoutHistory(ss);
1328 }
1329 }
1330
1331 @Override
1332 public void preferenceChanged(PreferenceChangeEvent e) {
1333 super.preferenceChanged(e);
1334 if ("display.discardable-keys".equals(e.getKey()) && Main.main.getCurrentDataSet() != null) {
1335 // Re-load data when display preference change
1336 updateSelection();
1337 }
1338 }
1339}
Note: See TracBrowser for help on using the repository browser.