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

Last change on this file since 12846 was 12846, checked in by bastiK, 7 years ago

see #15229 - use Config.getPref() wherever possible

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