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

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

fix #14665 - Validator incorrectly folds first-level categories when ignoring elements + avoid repaint of complete mapview, invalidate validator layer instead

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