source: josm/trunk/src/org/openstreetmap/josm/gui/dialogs/SelectionListDialog.java@ 12987

Last change on this file since 12987 was 12909, checked in by Don-vip, 7 years ago

see #15361 - add more debug info + update licence information

  • Property svn:eol-style set to native
File size: 34.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.dialogs;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.awt.Component;
8import java.awt.GraphicsEnvironment;
9import java.awt.Rectangle;
10import java.awt.datatransfer.Transferable;
11import java.awt.event.ActionEvent;
12import java.awt.event.ActionListener;
13import java.awt.event.KeyEvent;
14import java.awt.event.MouseEvent;
15import java.util.ArrayList;
16import java.util.Arrays;
17import java.util.Collection;
18import java.util.Collections;
19import java.util.Comparator;
20import java.util.HashSet;
21import java.util.Iterator;
22import java.util.LinkedList;
23import java.util.List;
24import java.util.Set;
25
26import javax.swing.AbstractAction;
27import javax.swing.AbstractListModel;
28import javax.swing.DefaultListSelectionModel;
29import javax.swing.JComponent;
30import javax.swing.JList;
31import javax.swing.JMenuItem;
32import javax.swing.JPopupMenu;
33import javax.swing.ListSelectionModel;
34import javax.swing.TransferHandler;
35import javax.swing.event.ListDataEvent;
36import javax.swing.event.ListDataListener;
37import javax.swing.event.ListSelectionEvent;
38import javax.swing.event.ListSelectionListener;
39
40import org.openstreetmap.josm.actions.AbstractSelectAction;
41import org.openstreetmap.josm.actions.AutoScaleAction;
42import org.openstreetmap.josm.actions.relation.DownloadSelectedIncompleteMembersAction;
43import org.openstreetmap.josm.actions.relation.EditRelationAction;
44import org.openstreetmap.josm.actions.relation.SelectInRelationListAction;
45import org.openstreetmap.josm.data.SelectionChangedListener;
46import org.openstreetmap.josm.data.coor.LatLon;
47import org.openstreetmap.josm.data.osm.DataSet;
48import org.openstreetmap.josm.data.osm.DefaultNameFormatter;
49import org.openstreetmap.josm.data.osm.Node;
50import org.openstreetmap.josm.data.osm.OsmPrimitive;
51import org.openstreetmap.josm.data.osm.OsmPrimitiveComparator;
52import org.openstreetmap.josm.data.osm.Relation;
53import org.openstreetmap.josm.data.osm.Way;
54import org.openstreetmap.josm.data.osm.event.AbstractDatasetChangedEvent;
55import org.openstreetmap.josm.data.osm.event.DataChangedEvent;
56import org.openstreetmap.josm.data.osm.event.DataSetListener;
57import org.openstreetmap.josm.data.osm.event.DatasetEventManager;
58import org.openstreetmap.josm.data.osm.event.DatasetEventManager.FireMode;
59import org.openstreetmap.josm.data.osm.event.NodeMovedEvent;
60import org.openstreetmap.josm.data.osm.event.PrimitivesAddedEvent;
61import org.openstreetmap.josm.data.osm.event.PrimitivesRemovedEvent;
62import org.openstreetmap.josm.data.osm.event.RelationMembersChangedEvent;
63import org.openstreetmap.josm.data.osm.event.SelectionEventManager;
64import org.openstreetmap.josm.data.osm.event.TagsChangedEvent;
65import org.openstreetmap.josm.data.osm.event.WayNodesChangedEvent;
66import org.openstreetmap.josm.data.osm.search.SearchSetting;
67import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
68import org.openstreetmap.josm.gui.MainApplication;
69import org.openstreetmap.josm.gui.MapFrame;
70import org.openstreetmap.josm.gui.OsmPrimitivRenderer;
71import org.openstreetmap.josm.gui.PopupMenuHandler;
72import org.openstreetmap.josm.gui.SideButton;
73import org.openstreetmap.josm.gui.datatransfer.PrimitiveTransferable;
74import org.openstreetmap.josm.gui.datatransfer.data.PrimitiveTransferData;
75import org.openstreetmap.josm.gui.history.HistoryBrowserDialogManager;
76import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeEvent;
77import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeListener;
78import org.openstreetmap.josm.gui.layer.OsmDataLayer;
79import org.openstreetmap.josm.gui.util.GuiHelper;
80import org.openstreetmap.josm.gui.util.HighlightHelper;
81import org.openstreetmap.josm.gui.widgets.ListPopupMenu;
82import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
83import org.openstreetmap.josm.spi.preferences.Config;
84import org.openstreetmap.josm.tools.ImageProvider;
85import org.openstreetmap.josm.tools.InputMapUtils;
86import org.openstreetmap.josm.tools.Shortcut;
87import org.openstreetmap.josm.tools.SubclassFilteredCollection;
88import org.openstreetmap.josm.tools.Utils;
89import org.openstreetmap.josm.tools.bugreport.BugReport;
90
91/**
92 * A small tool dialog for displaying the current selection.
93 * @since 8
94 */
95public class SelectionListDialog extends ToggleDialog {
96 private JList<OsmPrimitive> lstPrimitives;
97 private final DefaultListSelectionModel selectionModel = new DefaultListSelectionModel();
98 private final SelectionListModel model = new SelectionListModel(selectionModel);
99
100 private final SelectAction actSelect = new SelectAction();
101 private final SearchAction actSearch = new SearchAction();
102 private final ShowHistoryAction actShowHistory = new ShowHistoryAction();
103 private final ZoomToJOSMSelectionAction actZoomToJOSMSelection = new ZoomToJOSMSelectionAction();
104 private final ZoomToListSelection actZoomToListSelection = new ZoomToListSelection();
105 private final SelectInRelationListAction actSetRelationSelection = new SelectInRelationListAction();
106 private final EditRelationAction actEditRelationSelection = new EditRelationAction();
107 private final DownloadSelectedIncompleteMembersAction actDownloadSelIncompleteMembers = new DownloadSelectedIncompleteMembersAction();
108
109 /** the popup menu and its handler */
110 private final ListPopupMenu popupMenu;
111 private final transient PopupMenuHandler popupMenuHandler;
112
113 /**
114 * Builds the content panel for this dialog
115 */
116 protected void buildContentPanel() {
117 lstPrimitives = new JList<>(model);
118 lstPrimitives.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
119 lstPrimitives.setSelectionModel(selectionModel);
120 lstPrimitives.setCellRenderer(new OsmPrimitivRenderer());
121 lstPrimitives.setTransferHandler(new SelectionTransferHandler());
122 if (!GraphicsEnvironment.isHeadless()) {
123 lstPrimitives.setDragEnabled(true);
124 }
125
126 lstPrimitives.getSelectionModel().addListSelectionListener(actSelect);
127 lstPrimitives.getSelectionModel().addListSelectionListener(actShowHistory);
128
129 // the select action
130 final SideButton selectButton = new SideButton(actSelect);
131 selectButton.createArrow(e -> SelectionHistoryPopup.launch(selectButton, model.getSelectionHistory()));
132
133 // the search button
134 final SideButton searchButton = new SideButton(actSearch);
135 searchButton.createArrow(e -> SearchPopupMenu.launch(searchButton));
136
137 createLayout(lstPrimitives, true, Arrays.asList(
138 selectButton, searchButton, new SideButton(actShowHistory)
139 ));
140 }
141
142 /**
143 * Constructs a new {@code SelectionListDialog}.
144 */
145 public SelectionListDialog() {
146 super(tr("Selection"), "selectionlist", tr("Open a selection list window."),
147 Shortcut.registerShortcut("subwindow:selection", tr("Toggle: {0}",
148 tr("Current Selection")), KeyEvent.VK_T, Shortcut.ALT_SHIFT),
149 150, // default height
150 true // default is "show dialog"
151 );
152
153 buildContentPanel();
154 model.addListDataListener(new TitleUpdater());
155 model.addListDataListener(actZoomToJOSMSelection);
156
157 popupMenu = new ListPopupMenu(lstPrimitives);
158 popupMenuHandler = setupPopupMenuHandler();
159
160 lstPrimitives.addListSelectionListener(e -> {
161 actZoomToListSelection.valueChanged(e);
162 popupMenuHandler.setPrimitives(model.getSelected());
163 });
164
165 lstPrimitives.addMouseListener(new MouseEventHandler());
166
167 InputMapUtils.addEnterAction(lstPrimitives, actZoomToListSelection);
168 }
169
170 @Override
171 public void showNotify() {
172 SelectionEventManager.getInstance().addSelectionListener(actShowHistory, FireMode.IN_EDT_CONSOLIDATED);
173 SelectionEventManager.getInstance().addSelectionListener(model, FireMode.IN_EDT_CONSOLIDATED);
174 DatasetEventManager.getInstance().addDatasetListener(model, FireMode.IN_EDT);
175 MainApplication.getLayerManager().addActiveLayerChangeListener(actSearch);
176 // editLayerChanged also gets the selection history of the level. Listener calls setJOSMSelection when fired.
177 MainApplication.getLayerManager().addAndFireActiveLayerChangeListener(model);
178 actSearch.updateEnabledState();
179 }
180
181 @Override
182 public void hideNotify() {
183 MainApplication.getLayerManager().removeActiveLayerChangeListener(actSearch);
184 MainApplication.getLayerManager().removeActiveLayerChangeListener(model);
185 SelectionEventManager.getInstance().removeSelectionListener(actShowHistory);
186 SelectionEventManager.getInstance().removeSelectionListener(model);
187 DatasetEventManager.getInstance().removeDatasetListener(model);
188 }
189
190 /**
191 * Responds to double clicks on the list of selected objects and launches the popup menu
192 */
193 class MouseEventHandler extends PopupMenuLauncher {
194 private final HighlightHelper helper = new HighlightHelper();
195 private final boolean highlightEnabled = Config.getPref().getBoolean("draw.target-highlight", true);
196
197 MouseEventHandler() {
198 super(popupMenu);
199 }
200
201 @Override
202 public void mouseClicked(MouseEvent e) {
203 int idx = lstPrimitives.locationToIndex(e.getPoint());
204 if (idx < 0) return;
205 if (isDoubleClick(e)) {
206 OsmDataLayer layer = MainApplication.getLayerManager().getEditLayer();
207 if (layer == null) return;
208 OsmPrimitive osm = model.getElementAt(idx);
209 Collection<OsmPrimitive> sel = layer.data.getSelected();
210 if (sel.size() != 1 || !sel.iterator().next().equals(osm)) {
211 // Select primitive if it's not the whole current selection
212 layer.data.setSelected(Collections.singleton(osm));
213 } else if (osm instanceof Relation) {
214 // else open relation editor if applicable
215 actEditRelationSelection.actionPerformed(null);
216 }
217 } else if (highlightEnabled && MainApplication.isDisplayingMapView() && helper.highlightOnly(model.getElementAt(idx))) {
218 MainApplication.getMap().mapView.repaint();
219 }
220 }
221
222 @Override
223 public void mouseExited(MouseEvent me) {
224 if (highlightEnabled) helper.clear();
225 super.mouseExited(me);
226 }
227 }
228
229 private PopupMenuHandler setupPopupMenuHandler() {
230 PopupMenuHandler handler = new PopupMenuHandler(popupMenu);
231 handler.addAction(actZoomToJOSMSelection);
232 handler.addAction(actZoomToListSelection);
233 handler.addSeparator();
234 handler.addAction(actSetRelationSelection);
235 handler.addAction(actEditRelationSelection);
236 handler.addSeparator();
237 handler.addAction(actDownloadSelIncompleteMembers);
238 return handler;
239 }
240
241 /**
242 * Replies the popup menu handler.
243 * @return The popup menu handler
244 */
245 public PopupMenuHandler getPopupMenuHandler() {
246 return popupMenuHandler;
247 }
248
249 /**
250 * Replies the selected OSM primitives.
251 * @return The selected OSM primitives
252 */
253 public Collection<OsmPrimitive> getSelectedPrimitives() {
254 return model.getSelected();
255 }
256
257 /**
258 * Updates the dialog title with a summary of the current JOSM selection
259 */
260 class TitleUpdater implements ListDataListener {
261 protected void updateTitle() {
262 setTitle(model.getJOSMSelectionSummary());
263 }
264
265 @Override
266 public void contentsChanged(ListDataEvent e) {
267 updateTitle();
268 }
269
270 @Override
271 public void intervalAdded(ListDataEvent e) {
272 updateTitle();
273 }
274
275 @Override
276 public void intervalRemoved(ListDataEvent e) {
277 updateTitle();
278 }
279 }
280
281 /**
282 * Launches the search dialog
283 */
284 static class SearchAction extends AbstractAction implements ActiveLayerChangeListener {
285 /**
286 * Constructs a new {@code SearchAction}.
287 */
288 SearchAction() {
289 putValue(NAME, tr("Search"));
290 putValue(SHORT_DESCRIPTION, tr("Search for objects"));
291 new ImageProvider("dialogs", "search").getResource().attachImageIcon(this, true);
292 updateEnabledState();
293 }
294
295 @Override
296 public void actionPerformed(ActionEvent e) {
297 if (!isEnabled()) return;
298 org.openstreetmap.josm.actions.search.SearchAction.search();
299 }
300
301 protected void updateEnabledState() {
302 setEnabled(MainApplication.getLayerManager().getEditLayer() != null);
303 }
304
305 @Override
306 public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
307 updateEnabledState();
308 }
309 }
310
311 /**
312 * Sets the current JOSM selection to the OSM primitives selected in the list
313 * of this dialog
314 */
315 class SelectAction extends AbstractSelectAction implements ListSelectionListener {
316 /**
317 * Constructs a new {@code SelectAction}.
318 */
319 SelectAction() {
320 updateEnabledState();
321 }
322
323 @Override
324 public void actionPerformed(ActionEvent e) {
325 Collection<OsmPrimitive> sel = model.getSelected();
326 if (sel.isEmpty()) return;
327 OsmDataLayer editLayer = MainApplication.getLayerManager().getEditLayer();
328 if (editLayer == null) return;
329 editLayer.data.setSelected(sel);
330 model.selectionModel.setSelectionInterval(0, sel.size()-1);
331 }
332
333 protected void updateEnabledState() {
334 setEnabled(!model.isSelectionEmpty());
335 }
336
337 @Override
338 public void valueChanged(ListSelectionEvent e) {
339 updateEnabledState();
340 }
341 }
342
343 /**
344 * The action for showing history information of the current history item.
345 */
346 class ShowHistoryAction extends AbstractAction implements ListSelectionListener, SelectionChangedListener {
347 /**
348 * Constructs a new {@code ShowHistoryAction}.
349 */
350 ShowHistoryAction() {
351 putValue(NAME, tr("History"));
352 putValue(SHORT_DESCRIPTION, tr("Display the history of the selected objects."));
353 new ImageProvider("dialogs", "history").getResource().attachImageIcon(this, true);
354 updateEnabledState(model.getSize());
355 }
356
357 @Override
358 public void actionPerformed(ActionEvent e) {
359 Collection<OsmPrimitive> sel = model.getSelected();
360 if (sel.isEmpty() && model.getSize() != 1) {
361 return;
362 } else if (sel.isEmpty()) {
363 sel = Collections.singleton(model.getElementAt(0));
364 }
365 HistoryBrowserDialogManager.getInstance().showHistory(sel);
366 }
367
368 protected void updateEnabledState(int osmSelectionSize) {
369 // See #10830 - allow to click on history button is a single object is selected, even if not selected again in the list
370 setEnabled(!model.isSelectionEmpty() || osmSelectionSize == 1);
371 }
372
373 @Override
374 public void valueChanged(ListSelectionEvent e) {
375 updateEnabledState(model.getSize());
376 }
377
378 @Override
379 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
380 updateEnabledState(newSelection.size());
381 }
382 }
383
384 /**
385 * The action for zooming to the primitives in the current JOSM selection
386 *
387 */
388 class ZoomToJOSMSelectionAction extends AbstractAction implements ListDataListener {
389
390 ZoomToJOSMSelectionAction() {
391 putValue(NAME, tr("Zoom to selection"));
392 putValue(SHORT_DESCRIPTION, tr("Zoom to selection"));
393 new ImageProvider("dialogs/autoscale", "selection").getResource().attachImageIcon(this, true);
394 updateEnabledState();
395 }
396
397 @Override
398 public void actionPerformed(ActionEvent e) {
399 AutoScaleAction.autoScale("selection");
400 }
401
402 public void updateEnabledState() {
403 setEnabled(model.getSize() > 0);
404 }
405
406 @Override
407 public void contentsChanged(ListDataEvent e) {
408 updateEnabledState();
409 }
410
411 @Override
412 public void intervalAdded(ListDataEvent e) {
413 updateEnabledState();
414 }
415
416 @Override
417 public void intervalRemoved(ListDataEvent e) {
418 updateEnabledState();
419 }
420 }
421
422 /**
423 * The action for zooming to the primitives which are currently selected in
424 * the list displaying the JOSM selection
425 *
426 */
427 class ZoomToListSelection extends AbstractAction implements ListSelectionListener {
428 /**
429 * Constructs a new {@code ZoomToListSelection}.
430 */
431 ZoomToListSelection() {
432 putValue(NAME, tr("Zoom to selected element(s)"));
433 putValue(SHORT_DESCRIPTION, tr("Zoom to selected element(s)"));
434 new ImageProvider("dialogs/autoscale", "selection").getResource().attachImageIcon(this, true);
435 updateEnabledState();
436 }
437
438 @Override
439 public void actionPerformed(ActionEvent e) {
440 BoundingXYVisitor box = new BoundingXYVisitor();
441 Collection<OsmPrimitive> sel = model.getSelected();
442 if (sel.isEmpty()) return;
443 box.computeBoundingBox(sel);
444 if (box.getBounds() == null)
445 return;
446 box.enlargeBoundingBox();
447 MainApplication.getMap().mapView.zoomTo(box);
448 }
449
450 protected void updateEnabledState() {
451 setEnabled(!model.isSelectionEmpty());
452 }
453
454 @Override
455 public void valueChanged(ListSelectionEvent e) {
456 updateEnabledState();
457 }
458 }
459
460 /**
461 * The list model for the list of OSM primitives in the current JOSM selection.
462 *
463 * The model also maintains a history of the last {@link SelectionListModel#SELECTION_HISTORY_SIZE}
464 * JOSM selection.
465 *
466 */
467 static class SelectionListModel extends AbstractListModel<OsmPrimitive>
468 implements ActiveLayerChangeListener, SelectionChangedListener, DataSetListener {
469
470 private static final int SELECTION_HISTORY_SIZE = 10;
471
472 // Variable to store history from currentDataSet()
473 private LinkedList<Collection<? extends OsmPrimitive>> history;
474 private final transient List<OsmPrimitive> selection = new ArrayList<>();
475 private final DefaultListSelectionModel selectionModel;
476
477 /**
478 * Constructor
479 * @param selectionModel the selection model used in the list
480 */
481 SelectionListModel(DefaultListSelectionModel selectionModel) {
482 this.selectionModel = selectionModel;
483 }
484
485 /**
486 * Replies a summary of the current JOSM selection
487 *
488 * @return a summary of the current JOSM selection
489 */
490 public synchronized String getJOSMSelectionSummary() {
491 if (selection.isEmpty()) return tr("Selection");
492 int numNodes = 0;
493 int numWays = 0;
494 int numRelations = 0;
495 for (OsmPrimitive p: selection) {
496 switch(p.getType()) {
497 case NODE: numNodes++; break;
498 case WAY: numWays++; break;
499 case RELATION: numRelations++; break;
500 default: throw new AssertionError();
501 }
502 }
503 return tr("Sel.: Rel.:{0} / Ways:{1} / Nodes:{2}", numRelations, numWays, numNodes);
504 }
505
506 /**
507 * Remembers a JOSM selection the history of JOSM selections
508 *
509 * @param selection the JOSM selection. Ignored if null or empty.
510 */
511 public void remember(Collection<? extends OsmPrimitive> selection) {
512 if (selection == null) return;
513 if (selection.isEmpty()) return;
514 if (history == null) return;
515 if (history.isEmpty()) {
516 history.add(selection);
517 return;
518 }
519 if (history.getFirst().equals(selection)) return;
520 history.addFirst(selection);
521 for (int i = 1; i < history.size(); ++i) {
522 if (history.get(i).equals(selection)) {
523 history.remove(i);
524 break;
525 }
526 }
527 int maxsize = Config.getPref().getInt("select.history-size", SELECTION_HISTORY_SIZE);
528 while (history.size() > maxsize) {
529 history.removeLast();
530 }
531 }
532
533 /**
534 * Replies the history of JOSM selections
535 *
536 * @return history of JOSM selections
537 */
538 public List<Collection<? extends OsmPrimitive>> getSelectionHistory() {
539 return history;
540 }
541
542 @Override
543 public synchronized OsmPrimitive getElementAt(int index) {
544 return selection.get(index);
545 }
546
547 @Override
548 public synchronized int getSize() {
549 return selection.size();
550 }
551
552 /**
553 * Determines if no OSM primitives are currently selected.
554 * @return {@code true} if no OSM primitives are currently selected
555 * @since 10383
556 */
557 public boolean isSelectionEmpty() {
558 return selectionModel.isSelectionEmpty();
559 }
560
561 /**
562 * Replies the collection of OSM primitives currently selected in the view of this model
563 *
564 * @return choosen elements in the view
565 */
566 public synchronized Collection<OsmPrimitive> getSelected() {
567 Set<OsmPrimitive> sel = new HashSet<>();
568 for (int i = 0; i < getSize(); i++) {
569 if (selectionModel.isSelectedIndex(i)) {
570 sel.add(selection.get(i));
571 }
572 }
573 return sel;
574 }
575
576 /**
577 * Sets the OSM primitives to be selected in the view of this model
578 *
579 * @param sel the collection of primitives to select
580 */
581 public synchronized void setSelected(Collection<OsmPrimitive> sel) {
582 selectionModel.setValueIsAdjusting(true);
583 selectionModel.clearSelection();
584 if (sel != null) {
585 for (OsmPrimitive p: sel) {
586 int i = selection.indexOf(p);
587 if (i >= 0) {
588 selectionModel.addSelectionInterval(i, i);
589 }
590 }
591 }
592 selectionModel.setValueIsAdjusting(false);
593 }
594
595 @Override
596 protected void fireContentsChanged(Object source, int index0, int index1) {
597 Collection<OsmPrimitive> sel = getSelected();
598 super.fireContentsChanged(source, index0, index1);
599 setSelected(sel);
600 }
601
602 /**
603 * Sets the collection of currently selected OSM objects
604 *
605 * @param selection the collection of currently selected OSM objects
606 */
607 public void setJOSMSelection(final Collection<? extends OsmPrimitive> selection) {
608 synchronized (this) {
609 this.selection.clear();
610 if (selection != null) {
611 this.selection.addAll(selection);
612 sort();
613 }
614 }
615 GuiHelper.runInEDTAndWait(new Runnable() {
616 @Override public void run() {
617 fireContentsChanged(this, 0, getSize());
618 if (selection != null) {
619 remember(selection);
620 MapFrame map = MainApplication.getMap();
621 if (selection.size() == 2) {
622 Iterator<? extends OsmPrimitive> it = selection.iterator();
623 OsmPrimitive n1 = it.next();
624 OsmPrimitive n2 = it.next();
625 // show distance between two selected nodes with coordinates
626 if (n1 instanceof Node && n2 instanceof Node) {
627 LatLon c1 = ((Node) n1).getCoor();
628 LatLon c2 = ((Node) n2).getCoor();
629 if (c1 != null && c2 != null) {
630 map.statusLine.setDist(c1.greatCircleDistance(c2));
631 return;
632 }
633 }
634 }
635 map.statusLine.setDist(
636 new SubclassFilteredCollection<OsmPrimitive, Way>(selection, Way.class::isInstance));
637 }
638 }
639 });
640 }
641
642 /**
643 * Triggers a refresh of the view for all primitives in {@code toUpdate}
644 * which are currently displayed in the view
645 *
646 * @param toUpdate the collection of primitives to update
647 */
648 public synchronized void update(Collection<? extends OsmPrimitive> toUpdate) {
649 if (toUpdate == null) return;
650 if (toUpdate.isEmpty()) return;
651 Collection<OsmPrimitive> sel = getSelected();
652 for (OsmPrimitive p: toUpdate) {
653 int i = selection.indexOf(p);
654 if (i >= 0) {
655 super.fireContentsChanged(this, i, i);
656 }
657 }
658 setSelected(sel);
659 }
660
661 /**
662 * Sorts the current elements in the selection
663 */
664 public synchronized void sort() {
665 int size = selection.size();
666 if (size > 1 && size <= Config.getPref().getInt("selection.no_sort_above", 100_000)) {
667 boolean quick = size > Config.getPref().getInt("selection.fast_sort_above", 10_000);
668 Comparator<OsmPrimitive> c = Config.getPref().getBoolean("selection.sort_relations_before_ways", true)
669 ? OsmPrimitiveComparator.orderingRelationsWaysNodes()
670 : OsmPrimitiveComparator.orderingWaysRelationsNodes();
671 try {
672 selection.sort(c.thenComparing(quick
673 ? OsmPrimitiveComparator.comparingUniqueId()
674 : OsmPrimitiveComparator.comparingNames()));
675 } catch (IllegalArgumentException e) {
676 throw BugReport.intercept(e).put("size", size).put("quick", quick).put("selection", selection);
677 }
678 }
679 }
680
681 /* ------------------------------------------------------------------------ */
682 /* interface ActiveLayerChangeListener */
683 /* ------------------------------------------------------------------------ */
684 @Override
685 public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
686 DataSet newData = e.getSource().getEditDataSet();
687 if (newData == null) {
688 setJOSMSelection(null);
689 history = null;
690 } else {
691 history = newData.getSelectionHistory();
692 setJOSMSelection(newData.getAllSelected());
693 }
694 }
695
696 /* ------------------------------------------------------------------------ */
697 /* interface SelectionChangeListener */
698 /* ------------------------------------------------------------------------ */
699 @Override
700 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
701 setJOSMSelection(newSelection);
702 }
703
704 /* ------------------------------------------------------------------------ */
705 /* interface DataSetListener */
706 /* ------------------------------------------------------------------------ */
707 @Override
708 public void dataChanged(DataChangedEvent event) {
709 // refresh the whole list
710 fireContentsChanged(this, 0, getSize());
711 }
712
713 @Override
714 public void nodeMoved(NodeMovedEvent event) {
715 // may influence the display name of primitives, update the data
716 update(event.getPrimitives());
717 }
718
719 @Override
720 public void otherDatasetChange(AbstractDatasetChangedEvent event) {
721 // may influence the display name of primitives, update the data
722 update(event.getPrimitives());
723 }
724
725 @Override
726 public void relationMembersChanged(RelationMembersChangedEvent event) {
727 // may influence the display name of primitives, update the data
728 update(event.getPrimitives());
729 }
730
731 @Override
732 public void tagsChanged(TagsChangedEvent event) {
733 // may influence the display name of primitives, update the data
734 update(event.getPrimitives());
735 }
736
737 @Override
738 public void wayNodesChanged(WayNodesChangedEvent event) {
739 // may influence the display name of primitives, update the data
740 update(event.getPrimitives());
741 }
742
743 @Override
744 public void primitivesAdded(PrimitivesAddedEvent event) {
745 /* ignored - handled by SelectionChangeListener */
746 }
747
748 @Override
749 public void primitivesRemoved(PrimitivesRemovedEvent event) {
750 /* ignored - handled by SelectionChangeListener*/
751 }
752 }
753
754 /**
755 * A specialized {@link JMenuItem} for presenting one entry of the search history
756 *
757 * @author Jan Peter Stotz
758 */
759 protected static class SearchMenuItem extends JMenuItem implements ActionListener {
760 protected final transient SearchSetting s;
761
762 public SearchMenuItem(SearchSetting s) {
763 super(Utils.shortenString(s.toString(),
764 org.openstreetmap.josm.actions.search.SearchAction.MAX_LENGTH_SEARCH_EXPRESSION_DISPLAY));
765 this.s = s;
766 addActionListener(this);
767 }
768
769 @Override
770 public void actionPerformed(ActionEvent e) {
771 org.openstreetmap.josm.actions.search.SearchAction.searchWithoutHistory(s);
772 }
773 }
774
775 /**
776 * The popup menu for the search history entries
777 *
778 */
779 protected static class SearchPopupMenu extends JPopupMenu {
780 public static void launch(Component parent) {
781 if (org.openstreetmap.josm.actions.search.SearchAction.getSearchHistory().isEmpty())
782 return;
783 JPopupMenu menu = new SearchPopupMenu();
784 Rectangle r = parent.getBounds();
785 menu.show(parent, r.x, r.y + r.height);
786 }
787
788 /**
789 * Constructs a new {@code SearchPopupMenu}.
790 */
791 public SearchPopupMenu() {
792 for (SearchSetting ss: org.openstreetmap.josm.actions.search.SearchAction.getSearchHistory()) {
793 add(new SearchMenuItem(ss));
794 }
795 }
796 }
797
798 /**
799 * A specialized {@link JMenuItem} for presenting one entry of the selection history
800 *
801 * @author Jan Peter Stotz
802 */
803 protected static class SelectionMenuItem extends JMenuItem implements ActionListener {
804 protected transient Collection<? extends OsmPrimitive> sel;
805
806 public SelectionMenuItem(Collection<? extends OsmPrimitive> sel) {
807 this.sel = sel;
808 int ways = 0;
809 int nodes = 0;
810 int relations = 0;
811 for (OsmPrimitive o : sel) {
812 if (!o.isSelectable()) continue; // skip unselectable primitives
813 if (o instanceof Way) {
814 ways++;
815 } else if (o instanceof Node) {
816 nodes++;
817 } else if (o instanceof Relation) {
818 relations++;
819 }
820 }
821 StringBuilder text = new StringBuilder();
822 if (ways != 0) {
823 text.append(text.length() > 0 ? ", " : "")
824 .append(trn("{0} way", "{0} ways", ways, ways));
825 }
826 if (nodes != 0) {
827 text.append(text.length() > 0 ? ", " : "")
828 .append(trn("{0} node", "{0} nodes", nodes, nodes));
829 }
830 if (relations != 0) {
831 text.append(text.length() > 0 ? ", " : "")
832 .append(trn("{0} relation", "{0} relations", relations, relations));
833 }
834 if (ways + nodes + relations == 0) {
835 text.append(tr("Unselectable now"));
836 this.sel = new ArrayList<>(); // empty selection
837 }
838 DefaultNameFormatter df = DefaultNameFormatter.getInstance();
839 if (ways + nodes + relations == 1) {
840 text.append(": ");
841 for (OsmPrimitive o : sel) {
842 text.append(o.getDisplayName(df));
843 }
844 setText(text.toString());
845 } else {
846 setText(tr("Selection: {0}", text));
847 }
848 addActionListener(this);
849 }
850
851 @Override
852 public void actionPerformed(ActionEvent e) {
853 MainApplication.getLayerManager().getEditDataSet().setSelected(sel);
854 }
855 }
856
857 /**
858 * The popup menu for the JOSM selection history entries
859 */
860 protected static class SelectionHistoryPopup extends JPopupMenu {
861 public static void launch(Component parent, Collection<Collection<? extends OsmPrimitive>> history) {
862 if (history == null || history.isEmpty()) return;
863 JPopupMenu menu = new SelectionHistoryPopup(history);
864 Rectangle r = parent.getBounds();
865 menu.show(parent, r.x, r.y + r.height);
866 }
867
868 public SelectionHistoryPopup(Collection<Collection<? extends OsmPrimitive>> history) {
869 for (Collection<? extends OsmPrimitive> sel : history) {
870 add(new SelectionMenuItem(sel));
871 }
872 }
873 }
874
875 /**
876 * A transfer handler class for drag-and-drop support.
877 */
878 protected class SelectionTransferHandler extends TransferHandler {
879
880 @Override
881 public int getSourceActions(JComponent c) {
882 return COPY;
883 }
884
885 @Override
886 protected Transferable createTransferable(JComponent c) {
887 return new PrimitiveTransferable(PrimitiveTransferData.getData(getSelectedPrimitives()));
888 }
889 }
890}
Note: See TracBrowser for help on using the repository browser.