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

Last change on this file since 8811 was 8811, checked in by simon04, 9 years ago

see #11916 - Refactoring of SearchAction/SearchCompiler

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