source: josm/trunk/src/org/openstreetmap/josm/gui/dialogs/ValidatorDialog.java@ 12643

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

see #15182 - deprecate Main.main.menu. Replacement: gui.MainApplication.getMenu()

  • Property svn:eol-style set to native
File size: 24.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;
5
6import java.awt.event.ActionEvent;
7import java.awt.event.KeyEvent;
8import java.awt.event.MouseEvent;
9import java.io.IOException;
10import java.lang.reflect.InvocationTargetException;
11import java.util.ArrayList;
12import java.util.Collection;
13import java.util.Enumeration;
14import java.util.HashSet;
15import java.util.LinkedList;
16import java.util.List;
17import java.util.Set;
18
19import javax.swing.AbstractAction;
20import javax.swing.JComponent;
21import javax.swing.JOptionPane;
22import javax.swing.JPopupMenu;
23import javax.swing.SwingUtilities;
24import javax.swing.event.TreeSelectionEvent;
25import javax.swing.event.TreeSelectionListener;
26import javax.swing.tree.DefaultMutableTreeNode;
27import javax.swing.tree.TreeNode;
28import javax.swing.tree.TreePath;
29
30import org.openstreetmap.josm.Main;
31import org.openstreetmap.josm.actions.AbstractSelectAction;
32import org.openstreetmap.josm.actions.AutoScaleAction;
33import org.openstreetmap.josm.actions.ValidateAction;
34import org.openstreetmap.josm.actions.relation.EditRelationAction;
35import org.openstreetmap.josm.command.Command;
36import org.openstreetmap.josm.data.SelectionChangedListener;
37import org.openstreetmap.josm.data.osm.DataSet;
38import org.openstreetmap.josm.data.osm.Node;
39import org.openstreetmap.josm.data.osm.OsmPrimitive;
40import org.openstreetmap.josm.data.osm.WaySegment;
41import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
42import org.openstreetmap.josm.data.validation.OsmValidator;
43import org.openstreetmap.josm.data.validation.TestError;
44import org.openstreetmap.josm.data.validation.ValidatorVisitor;
45import org.openstreetmap.josm.gui.MainApplication;
46import org.openstreetmap.josm.gui.MapFrame;
47import org.openstreetmap.josm.gui.PleaseWaitRunnable;
48import org.openstreetmap.josm.gui.PopupMenuHandler;
49import org.openstreetmap.josm.gui.SideButton;
50import org.openstreetmap.josm.gui.dialogs.validator.ValidatorTreePanel;
51import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeEvent;
52import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeListener;
53import org.openstreetmap.josm.gui.layer.OsmDataLayer;
54import org.openstreetmap.josm.gui.layer.ValidatorLayer;
55import org.openstreetmap.josm.gui.preferences.validator.ValidatorPreference;
56import org.openstreetmap.josm.gui.progress.ProgressMonitor;
57import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
58import org.openstreetmap.josm.io.OsmTransferException;
59import org.openstreetmap.josm.tools.ImageProvider;
60import org.openstreetmap.josm.tools.InputMapUtils;
61import org.openstreetmap.josm.tools.JosmRuntimeException;
62import org.openstreetmap.josm.tools.Shortcut;
63import org.xml.sax.SAXException;
64
65/**
66 * A small tool dialog for displaying the current errors. The selection manager
67 * respects clicks into the selection list. Ctrl-click will remove entries from
68 * the list while single click will make the clicked entry the only selection.
69 *
70 * @author frsantos
71 */
72public class ValidatorDialog extends ToggleDialog implements SelectionChangedListener, ActiveLayerChangeListener {
73
74 /** The display tree */
75 public ValidatorTreePanel tree;
76
77 /** The validate action */
78 public static final ValidateAction validateAction = new ValidateAction();
79
80 /** The fix button */
81 private final SideButton fixButton;
82 /** The ignore button */
83 private final SideButton ignoreButton;
84 /** The select button */
85 private final SideButton selectButton;
86 /** The lookup button */
87 private final SideButton lookupButton;
88
89 private final JPopupMenu popupMenu = new JPopupMenu();
90 private final transient PopupMenuHandler popupMenuHandler = new PopupMenuHandler(popupMenu);
91
92 /** Last selected element */
93 private DefaultMutableTreeNode lastSelectedNode;
94
95 /**
96 * Constructor
97 */
98 public ValidatorDialog() {
99 super(tr("Validation Results"), "validator", tr("Open the validation window."),
100 Shortcut.registerShortcut("subwindow:validator", tr("Toggle: {0}", tr("Validation results")),
101 KeyEvent.VK_V, Shortcut.ALT_SHIFT), 150, false, ValidatorPreference.class);
102
103 popupMenuHandler.addAction(MainApplication.getMenu().autoScaleActions.get("problem"));
104 popupMenuHandler.addAction(new EditRelationAction());
105
106 tree = new ValidatorTreePanel();
107 tree.addMouseListener(new MouseEventHandler());
108 addTreeSelectionListener(new SelectionWatch());
109 InputMapUtils.unassignCtrlShiftUpDown(tree, JComponent.WHEN_FOCUSED);
110
111 List<SideButton> buttons = new LinkedList<>();
112
113 selectButton = new SideButton(new AbstractSelectAction() {
114 @Override
115 public void actionPerformed(ActionEvent e) {
116 setSelectedItems();
117 }
118 });
119 InputMapUtils.addEnterAction(tree, selectButton.getAction());
120
121 selectButton.setEnabled(false);
122 buttons.add(selectButton);
123
124 lookupButton = new SideButton(new AbstractAction() {
125 {
126 putValue(NAME, tr("Lookup"));
127 putValue(SHORT_DESCRIPTION, tr("Looks up the selected primitives in the error list."));
128 new ImageProvider("dialogs", "search").getResource().attachImageIcon(this, true);
129 }
130
131 @Override
132 public void actionPerformed(ActionEvent e) {
133 final DataSet ds = MainApplication.getLayerManager().getEditDataSet();
134 if (ds == null) {
135 return;
136 }
137 tree.selectRelatedErrors(ds.getSelected());
138 }
139 });
140
141 buttons.add(lookupButton);
142
143 buttons.add(new SideButton(validateAction));
144
145 fixButton = new SideButton(new AbstractAction() {
146 {
147 putValue(NAME, tr("Fix"));
148 putValue(SHORT_DESCRIPTION, tr("Fix the selected issue."));
149 new ImageProvider("dialogs", "fix").getResource().attachImageIcon(this, true);
150 }
151 @Override
152 public void actionPerformed(ActionEvent e) {
153 fixErrors();
154 }
155 });
156 fixButton.setEnabled(false);
157 buttons.add(fixButton);
158
159 if (ValidatorPreference.PREF_USE_IGNORE.get()) {
160 ignoreButton = new SideButton(new AbstractAction() {
161 {
162 putValue(NAME, tr("Ignore"));
163 putValue(SHORT_DESCRIPTION, tr("Ignore the selected issue next time."));
164 new ImageProvider("dialogs", "fix").getResource().attachImageIcon(this, true);
165 }
166 @Override
167 public void actionPerformed(ActionEvent e) {
168 ignoreErrors();
169 }
170 });
171 ignoreButton.setEnabled(false);
172 buttons.add(ignoreButton);
173 } else {
174 ignoreButton = null;
175 }
176 createLayout(tree, true, buttons);
177 }
178
179 @Override
180 public void showNotify() {
181 DataSet.addSelectionListener(this);
182 DataSet ds = MainApplication.getLayerManager().getEditDataSet();
183 if (ds != null) {
184 updateSelection(ds.getAllSelected());
185 }
186 MainApplication.getLayerManager().addAndFireActiveLayerChangeListener(this);
187 }
188
189 @Override
190 public void hideNotify() {
191 MainApplication.getLayerManager().removeActiveLayerChangeListener(this);
192 DataSet.removeSelectionListener(this);
193 }
194
195 @Override
196 public void setVisible(boolean v) {
197 if (tree != null) {
198 tree.setVisible(v);
199 }
200 super.setVisible(v);
201 }
202
203 /**
204 * Fix selected errors
205 */
206 @SuppressWarnings("unchecked")
207 private void fixErrors() {
208 TreePath[] selectionPaths = tree.getSelectionPaths();
209 if (selectionPaths == null)
210 return;
211
212 Set<DefaultMutableTreeNode> processedNodes = new HashSet<>();
213
214 List<TestError> errorsToFix = new LinkedList<>();
215 for (TreePath path : selectionPaths) {
216 DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
217 if (node == null) {
218 continue;
219 }
220
221 Enumeration<TreeNode> children = node.breadthFirstEnumeration();
222 while (children.hasMoreElements()) {
223 DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) children.nextElement();
224 if (processedNodes.contains(childNode)) {
225 continue;
226 }
227
228 processedNodes.add(childNode);
229 Object nodeInfo = childNode.getUserObject();
230 if (nodeInfo instanceof TestError) {
231 errorsToFix.add((TestError) nodeInfo);
232 }
233 }
234 }
235
236 // run fix task asynchronously
237 //
238 FixTask fixTask = new FixTask(errorsToFix);
239 MainApplication.worker.submit(fixTask);
240 }
241
242 /**
243 * Set selected errors to ignore state
244 */
245 @SuppressWarnings("unchecked")
246 private void ignoreErrors() {
247 int asked = JOptionPane.DEFAULT_OPTION;
248 boolean changed = false;
249 TreePath[] selectionPaths = tree.getSelectionPaths();
250 if (selectionPaths == null)
251 return;
252
253 Set<DefaultMutableTreeNode> processedNodes = new HashSet<>();
254 for (TreePath path : selectionPaths) {
255 DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
256 if (node == null) {
257 continue;
258 }
259
260 Object mainNodeInfo = node.getUserObject();
261 if (!(mainNodeInfo instanceof TestError)) {
262 Set<String> state = new HashSet<>();
263 // ask if the whole set should be ignored
264 if (asked == JOptionPane.DEFAULT_OPTION) {
265 String[] a = new String[] {tr("Whole group"), tr("Single elements"), tr("Nothing")};
266 asked = JOptionPane.showOptionDialog(Main.parent, tr("Ignore whole group or individual elements?"),
267 tr("Ignoring elements"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
268 a, a[1]);
269 }
270 if (asked == JOptionPane.YES_NO_OPTION) {
271 Enumeration<TreeNode> children = node.breadthFirstEnumeration();
272 while (children.hasMoreElements()) {
273 DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) children.nextElement();
274 if (processedNodes.contains(childNode)) {
275 continue;
276 }
277
278 processedNodes.add(childNode);
279 Object nodeInfo = childNode.getUserObject();
280 if (nodeInfo instanceof TestError) {
281 TestError err = (TestError) nodeInfo;
282 err.setIgnored(true);
283 changed = true;
284 state.add(node.getDepth() == 1 ? err.getIgnoreSubGroup() : err.getIgnoreGroup());
285 }
286 }
287 for (String s : state) {
288 OsmValidator.addIgnoredError(s);
289 }
290 continue;
291 } else if (asked == JOptionPane.CANCEL_OPTION || asked == JOptionPane.CLOSED_OPTION) {
292 continue;
293 }
294 }
295
296 Enumeration<TreeNode> children = node.breadthFirstEnumeration();
297 while (children.hasMoreElements()) {
298 DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) children.nextElement();
299 if (processedNodes.contains(childNode)) {
300 continue;
301 }
302
303 processedNodes.add(childNode);
304 Object nodeInfo = childNode.getUserObject();
305 if (nodeInfo instanceof TestError) {
306 TestError error = (TestError) nodeInfo;
307 String state = error.getIgnoreState();
308 if (state != null) {
309 OsmValidator.addIgnoredError(state);
310 }
311 changed = true;
312 error.setIgnored(true);
313 }
314 }
315 }
316 if (changed) {
317 tree.resetErrors();
318 OsmValidator.saveIgnoredErrors();
319 MainApplication.getMap().repaint();
320 }
321 }
322
323 /**
324 * Sets the selection of the map to the current selected items.
325 */
326 @SuppressWarnings("unchecked")
327 private void setSelectedItems() {
328 if (tree == null)
329 return;
330
331 Collection<OsmPrimitive> sel = new HashSet<>(40);
332
333 TreePath[] selectedPaths = tree.getSelectionPaths();
334 if (selectedPaths == null)
335 return;
336
337 for (TreePath path : selectedPaths) {
338 DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
339 Enumeration<TreeNode> children = node.breadthFirstEnumeration();
340 while (children.hasMoreElements()) {
341 DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) children.nextElement();
342 Object nodeInfo = childNode.getUserObject();
343 if (nodeInfo instanceof TestError) {
344 TestError error = (TestError) nodeInfo;
345 error.getPrimitives().stream()
346 .filter(OsmPrimitive::isSelectable)
347 .forEach(sel::add);
348 }
349 }
350 }
351 DataSet ds = MainApplication.getLayerManager().getEditDataSet();
352 if (ds != null) {
353 ds.setSelected(sel);
354 }
355 }
356
357 /**
358 * Checks for fixes in selected element and, if needed, adds to the sel
359 * parameter all selected elements
360 *
361 * @param sel
362 * The collection where to add all selected elements
363 * @param addSelected
364 * if true, add all selected elements to collection
365 * @return whether the selected elements has any fix
366 */
367 @SuppressWarnings("unchecked")
368 private boolean setSelection(Collection<OsmPrimitive> sel, boolean addSelected) {
369 boolean hasFixes = false;
370
371 DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
372 if (lastSelectedNode != null && !lastSelectedNode.equals(node)) {
373 Enumeration<TreeNode> children = lastSelectedNode.breadthFirstEnumeration();
374 while (children.hasMoreElements()) {
375 DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) children.nextElement();
376 Object nodeInfo = childNode.getUserObject();
377 if (nodeInfo instanceof TestError) {
378 TestError error = (TestError) nodeInfo;
379 error.setSelected(false);
380 }
381 }
382 }
383
384 lastSelectedNode = node;
385 if (node == null)
386 return hasFixes;
387
388 Enumeration<TreeNode> children = node.breadthFirstEnumeration();
389 while (children.hasMoreElements()) {
390 DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) children.nextElement();
391 Object nodeInfo = childNode.getUserObject();
392 if (nodeInfo instanceof TestError) {
393 TestError error = (TestError) nodeInfo;
394 error.setSelected(true);
395
396 hasFixes = hasFixes || error.isFixable();
397 if (addSelected) {
398 error.getPrimitives().stream()
399 .filter(OsmPrimitive::isSelectable)
400 .forEach(sel::add);
401 }
402 }
403 }
404 selectButton.setEnabled(true);
405 if (ignoreButton != null) {
406 ignoreButton.setEnabled(true);
407 }
408
409 return hasFixes;
410 }
411
412 @Override
413 public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
414 OsmDataLayer editLayer = e.getSource().getEditLayer();
415 if (editLayer == null) {
416 tree.setErrorList(new ArrayList<TestError>());
417 } else {
418 tree.setErrorList(editLayer.validationErrors);
419 }
420 }
421
422 /**
423 * Add a tree selection listener to the validator tree.
424 * @param listener the TreeSelectionListener
425 * @since 5958
426 */
427 public void addTreeSelectionListener(TreeSelectionListener listener) {
428 tree.addTreeSelectionListener(listener);
429 }
430
431 /**
432 * Remove the given tree selection listener from the validator tree.
433 * @param listener the TreeSelectionListener
434 * @since 5958
435 */
436 public void removeTreeSelectionListener(TreeSelectionListener listener) {
437 tree.removeTreeSelectionListener(listener);
438 }
439
440 /**
441 * Replies the popup menu handler.
442 * @return The popup menu handler
443 * @since 5958
444 */
445 public PopupMenuHandler getPopupMenuHandler() {
446 return popupMenuHandler;
447 }
448
449 /**
450 * Replies the currently selected error, or {@code null}.
451 * @return The selected error, if any.
452 * @since 5958
453 */
454 public TestError getSelectedError() {
455 Object comp = tree.getLastSelectedPathComponent();
456 if (comp instanceof DefaultMutableTreeNode) {
457 Object object = ((DefaultMutableTreeNode) comp).getUserObject();
458 if (object instanceof TestError) {
459 return (TestError) object;
460 }
461 }
462 return null;
463 }
464
465 /**
466 * Watches for double clicks and launches the popup menu.
467 */
468 class MouseEventHandler extends PopupMenuLauncher {
469
470 MouseEventHandler() {
471 super(popupMenu);
472 }
473
474 @Override
475 public void mouseClicked(MouseEvent e) {
476 fixButton.setEnabled(false);
477 if (ignoreButton != null) {
478 ignoreButton.setEnabled(false);
479 }
480 selectButton.setEnabled(false);
481
482 boolean isDblClick = isDoubleClick(e);
483
484 Collection<OsmPrimitive> sel = isDblClick ? new HashSet<>(40) : null;
485
486 boolean hasFixes = setSelection(sel, isDblClick);
487 fixButton.setEnabled(hasFixes);
488
489 if (isDblClick) {
490 DataSet ds = MainApplication.getLayerManager().getEditDataSet();
491 if (ds != null) {
492 ds.setSelected(sel);
493 }
494 if (Main.pref.getBoolean("validator.autozoom", false)) {
495 AutoScaleAction.zoomTo(sel);
496 }
497 }
498 }
499
500 @Override public void launch(MouseEvent e) {
501 TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
502 if (selPath == null)
503 return;
504 DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath.getPathComponent(selPath.getPathCount() - 1);
505 if (!(node.getUserObject() instanceof TestError))
506 return;
507 super.launch(e);
508 }
509
510 }
511
512 /**
513 * Watches for tree selection.
514 */
515 public class SelectionWatch implements TreeSelectionListener {
516 @Override
517 public void valueChanged(TreeSelectionEvent e) {
518 fixButton.setEnabled(false);
519 if (ignoreButton != null) {
520 ignoreButton.setEnabled(false);
521 }
522 selectButton.setEnabled(false);
523
524 Collection<OsmPrimitive> sel = new HashSet<>();
525 boolean hasFixes = setSelection(sel, true);
526 fixButton.setEnabled(hasFixes);
527 popupMenuHandler.setPrimitives(sel);
528 MapFrame map = MainApplication.getMap();
529 if (map != null) {
530 map.repaint();
531 }
532 }
533 }
534
535 /**
536 * A visitor that is used to compute the bounds of an error.
537 */
538 public static class ValidatorBoundingXYVisitor extends BoundingXYVisitor implements ValidatorVisitor {
539 @Override
540 public void visit(OsmPrimitive p) {
541 if (p.isUsable()) {
542 p.accept(this);
543 }
544 }
545
546 @Override
547 public void visit(WaySegment ws) {
548 if (ws.lowerIndex < 0 || ws.lowerIndex + 1 >= ws.way.getNodesCount())
549 return;
550 visit(ws.way.getNodes().get(ws.lowerIndex));
551 visit(ws.way.getNodes().get(ws.lowerIndex + 1));
552 }
553
554 @Override
555 public void visit(List<Node> nodes) {
556 for (Node n: nodes) {
557 visit(n);
558 }
559 }
560
561 @Override
562 public void visit(TestError error) {
563 if (error != null) {
564 error.visitHighlighted(this);
565 }
566 }
567 }
568
569 /**
570 * Called when the selection was changed to update the list of displayed errors
571 * @param newSelection The new selection
572 */
573 public void updateSelection(Collection<? extends OsmPrimitive> newSelection) {
574 if (!Main.pref.getBoolean(ValidatorPreference.PREF_FILTER_BY_SELECTION, false))
575 return;
576 if (newSelection.isEmpty()) {
577 tree.setFilter(null);
578 }
579 tree.setFilter(new HashSet<>(newSelection));
580 }
581
582 @Override
583 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
584 updateSelection(newSelection);
585 }
586
587 /**
588 * Task for fixing a collection of {@link TestError}s. Can be run asynchronously.
589 *
590 *
591 */
592 class FixTask extends PleaseWaitRunnable {
593 private final Collection<TestError> testErrors;
594 private boolean canceled;
595
596 FixTask(Collection<TestError> testErrors) {
597 super(tr("Fixing errors ..."), false /* don't ignore exceptions */);
598 this.testErrors = testErrors == null ? new ArrayList<>() : testErrors;
599 }
600
601 @Override
602 protected void cancel() {
603 this.canceled = true;
604 }
605
606 @Override
607 protected void finish() {
608 // do nothing
609 }
610
611 protected void fixError(TestError error) throws InterruptedException, InvocationTargetException {
612 if (error.isFixable()) {
613 final Command fixCommand = error.getFix();
614 if (fixCommand != null) {
615 SwingUtilities.invokeAndWait(() -> MainApplication.undoRedo.addNoRedraw(fixCommand));
616 }
617 // It is wanted to ignore an error if it said fixable, even if fixCommand was null
618 // This is to fix #5764 and #5773:
619 // a delete command, for example, may be null if all concerned primitives have already been deleted
620 error.setIgnored(true);
621 }
622 }
623
624 @Override
625 protected void realRun() throws SAXException, IOException, OsmTransferException {
626 ProgressMonitor monitor = getProgressMonitor();
627 try {
628 monitor.setTicksCount(testErrors.size());
629 final DataSet ds = MainApplication.getLayerManager().getEditDataSet();
630 int i = 0;
631 SwingUtilities.invokeAndWait(ds::beginUpdate);
632 try {
633 for (TestError error: testErrors) {
634 i++;
635 monitor.subTask(tr("Fixing ({0}/{1}): ''{2}''", i, testErrors.size(), error.getMessage()));
636 if (this.canceled)
637 return;
638 fixError(error);
639 monitor.worked(1);
640 }
641 } finally {
642 SwingUtilities.invokeAndWait(ds::endUpdate);
643 }
644 monitor.subTask(tr("Updating map ..."));
645 SwingUtilities.invokeAndWait(() -> {
646 MainApplication.undoRedo.afterAdd();
647 MainApplication.getLayerManager().getLayersOfType(ValidatorLayer.class).forEach(ValidatorLayer::invalidate);
648 tree.resetErrors();
649 });
650 } catch (InterruptedException | InvocationTargetException e) {
651 // FIXME: signature of realRun should have a generic checked exception we could throw here
652 throw new JosmRuntimeException(e);
653 } finally {
654 monitor.finishTask();
655 }
656 }
657 }
658}
Note: See TracBrowser for help on using the repository browser.