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

Last change on this file since 12302 was 12302, checked in by michael2402, 7 years ago

Invalidate the validator layer after repairing the errors. Remove ds.fireSelectionChanged()

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