source: josm/trunk/src/org/openstreetmap/josm/gui/dialogs/ConflictDialog.java@ 16967

Last change on this file since 16967 was 16967, checked in by simon04, 4 years ago

fix #19510 - Add "Zoom to layer" in context menu of layers in the Layers panel

  • Property svn:eol-style set to native
File size: 22.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.dialogs;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.marktr;
6import static org.openstreetmap.josm.tools.I18n.tr;
7import static org.openstreetmap.josm.tools.I18n.trn;
8
9import java.awt.Color;
10import java.awt.Graphics;
11import java.awt.Point;
12import java.awt.event.ActionEvent;
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.HashSet;
19import java.util.LinkedList;
20import java.util.List;
21import java.util.Set;
22import java.util.concurrent.CopyOnWriteArrayList;
23import java.util.stream.IntStream;
24
25import javax.swing.AbstractAction;
26import javax.swing.JList;
27import javax.swing.JMenuItem;
28import javax.swing.JOptionPane;
29import javax.swing.JPopupMenu;
30import javax.swing.ListModel;
31import javax.swing.ListSelectionModel;
32import javax.swing.event.ListDataEvent;
33import javax.swing.event.ListDataListener;
34import javax.swing.event.ListSelectionEvent;
35import javax.swing.event.ListSelectionListener;
36import javax.swing.event.PopupMenuEvent;
37import javax.swing.event.PopupMenuListener;
38
39import org.openstreetmap.josm.actions.AbstractSelectAction;
40import org.openstreetmap.josm.actions.AutoScaleAction;
41import org.openstreetmap.josm.actions.ExpertToggleAction;
42import org.openstreetmap.josm.command.Command;
43import org.openstreetmap.josm.command.SequenceCommand;
44import org.openstreetmap.josm.data.UndoRedoHandler;
45import org.openstreetmap.josm.data.conflict.Conflict;
46import org.openstreetmap.josm.data.conflict.ConflictCollection;
47import org.openstreetmap.josm.data.conflict.IConflictListener;
48import org.openstreetmap.josm.data.osm.DataSelectionListener;
49import org.openstreetmap.josm.data.osm.DataSet;
50import org.openstreetmap.josm.data.osm.Node;
51import org.openstreetmap.josm.data.osm.OsmPrimitive;
52import org.openstreetmap.josm.data.osm.Relation;
53import org.openstreetmap.josm.data.osm.RelationMember;
54import org.openstreetmap.josm.data.osm.Way;
55import org.openstreetmap.josm.data.osm.visitor.OsmPrimitiveVisitor;
56import org.openstreetmap.josm.data.preferences.NamedColorProperty;
57import org.openstreetmap.josm.gui.HelpAwareOptionPane;
58import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
59import org.openstreetmap.josm.gui.MainApplication;
60import org.openstreetmap.josm.gui.NavigatableComponent;
61import org.openstreetmap.josm.gui.PopupMenuHandler;
62import org.openstreetmap.josm.gui.PrimitiveRenderer;
63import org.openstreetmap.josm.gui.SideButton;
64import org.openstreetmap.josm.gui.conflict.pair.ConflictResolver;
65import org.openstreetmap.josm.gui.conflict.pair.MergeDecisionType;
66import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeEvent;
67import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeListener;
68import org.openstreetmap.josm.gui.layer.OsmDataLayer;
69import org.openstreetmap.josm.gui.util.GuiHelper;
70import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;
71import org.openstreetmap.josm.tools.ImageProvider;
72import org.openstreetmap.josm.tools.Logging;
73import org.openstreetmap.josm.tools.Shortcut;
74
75/**
76 * This dialog displays the {@link ConflictCollection} of the active {@link OsmDataLayer} in a toggle
77 * dialog on the right of the main frame.
78 * @since 86
79 */
80public final class ConflictDialog extends ToggleDialog implements ActiveLayerChangeListener, IConflictListener, DataSelectionListener {
81
82 private static final NamedColorProperty CONFLICT_COLOR = new NamedColorProperty(marktr("conflict"), Color.GRAY);
83 private static final NamedColorProperty BACKGROUND_COLOR = new NamedColorProperty(marktr("background"), Color.BLACK);
84
85 /** the collection of conflicts displayed by this conflict dialog */
86 private transient ConflictCollection conflicts;
87
88 /** the model for the list of conflicts */
89 private transient ConflictListModel model;
90 /** the list widget for the list of conflicts */
91 private JList<OsmPrimitive> lstConflicts;
92
93 private final JPopupMenu popupMenu = new JPopupMenu();
94 private final transient PopupMenuHandler popupMenuHandler = new PopupMenuHandler(popupMenu);
95
96 private final ResolveAction actResolve = new ResolveAction();
97 private final SelectAction actSelect = new SelectAction();
98
99 /**
100 * Constructs a new {@code ConflictDialog}.
101 */
102 public ConflictDialog() {
103 super(tr("Conflict"), "conflict", tr("Resolve conflicts"),
104 Shortcut.registerShortcut("subwindow:conflict", tr("Toggle: {0}", tr("Conflict")),
105 KeyEvent.VK_C, Shortcut.ALT_SHIFT), 100);
106
107 build();
108 refreshView();
109 }
110
111 /**
112 * Replies the color used to paint conflicts.
113 *
114 * @return the color used to paint conflicts
115 * @see #paintConflicts
116 * @since 1221
117 */
118 public static Color getColor() {
119 return CONFLICT_COLOR.get();
120 }
121
122 /**
123 * builds the GUI
124 */
125 private void build() {
126 synchronized (this) {
127 model = new ConflictListModel();
128
129 lstConflicts = new JList<>(model);
130 lstConflicts.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
131 lstConflicts.setCellRenderer(new PrimitiveRenderer());
132 lstConflicts.addMouseListener(new MouseEventHandler());
133 }
134 addListSelectionListener(e -> MainApplication.getMap().mapView.repaint());
135
136 SideButton btnResolve = new SideButton(actResolve);
137 addListSelectionListener(actResolve);
138
139 SideButton btnSelect = new SideButton(actSelect);
140 addListSelectionListener(actSelect);
141
142 createLayout(lstConflicts, true, Arrays.asList(btnResolve, btnSelect));
143
144 popupMenuHandler.addAction(MainApplication.getMenu().autoScaleActions.get(AutoScaleAction.AutoScaleMode.CONFLICT));
145
146 ResolveToMyVersionAction resolveToMyVersionAction = new ResolveToMyVersionAction();
147 ResolveToTheirVersionAction resolveToTheirVersionAction = new ResolveToTheirVersionAction();
148 addListSelectionListener(resolveToMyVersionAction);
149 addListSelectionListener(resolveToTheirVersionAction);
150 JMenuItem btnResolveMy = popupMenuHandler.addAction(resolveToMyVersionAction);
151 JMenuItem btnResolveTheir = popupMenuHandler.addAction(resolveToTheirVersionAction);
152
153 popupMenuHandler.addListener(new ResolveButtonsPopupMenuListener(btnResolveTheir, btnResolveMy));
154 }
155
156 @Override
157 public void showNotify() {
158 MainApplication.getLayerManager().addAndFireActiveLayerChangeListener(this);
159 }
160
161 @Override
162 public void hideNotify() {
163 MainApplication.getLayerManager().removeActiveLayerChangeListener(this);
164 removeDataLayerListeners(MainApplication.getLayerManager().getEditLayer());
165 }
166
167 /**
168 * Add a list selection listener to the conflicts list.
169 * @param listener the ListSelectionListener
170 * @since 5958
171 */
172 public synchronized void addListSelectionListener(ListSelectionListener listener) {
173 lstConflicts.getSelectionModel().addListSelectionListener(listener);
174 }
175
176 /**
177 * Remove the given list selection listener from the conflicts list.
178 * @param listener the ListSelectionListener
179 * @since 5958
180 */
181 public synchronized void removeListSelectionListener(ListSelectionListener listener) {
182 lstConflicts.getSelectionModel().removeListSelectionListener(listener);
183 }
184
185 /**
186 * Replies the popup menu handler.
187 * @return The popup menu handler
188 * @since 5958
189 */
190 public PopupMenuHandler getPopupMenuHandler() {
191 return popupMenuHandler;
192 }
193
194 /**
195 * Launches a conflict resolution dialog for the first selected conflict
196 */
197 private void resolve() {
198 synchronized (this) {
199 if (conflicts == null || model.getSize() == 0)
200 return;
201
202 int index = lstConflicts.getSelectedIndex();
203 if (index < 0) {
204 index = 0;
205 }
206
207 Conflict<? extends OsmPrimitive> c = conflicts.get(index);
208 ConflictResolutionDialog dialog = new ConflictResolutionDialog(MainApplication.getMainFrame());
209 dialog.getConflictResolver().populate(c);
210 dialog.showDialog();
211
212 if (index < conflicts.size() - 1) {
213 lstConflicts.setSelectedIndex(index);
214 } else {
215 lstConflicts.setSelectedIndex(index - 1);
216 }
217 }
218 MainApplication.getMap().mapView.repaint();
219 }
220
221 /**
222 * refreshes the view of this dialog
223 */
224 public void refreshView() {
225 DataSet editDs = MainApplication.getLayerManager().getEditDataSet();
226 synchronized (this) {
227 conflicts = editDs == null ? new ConflictCollection() : editDs.getConflicts();
228 }
229 GuiHelper.runInEDT(() -> {
230 model.fireContentChanged();
231 updateTitle();
232 });
233 }
234
235 private synchronized void updateTitle() {
236 int conflictsCount = conflicts.size();
237 if (conflictsCount > 0) {
238 setTitle(trn("Conflict: {0} unresolved", "Conflicts: {0} unresolved", conflictsCount, conflictsCount) +
239 " ("+tr("Rel.:{0} / Ways:{1} / Nodes:{2}",
240 conflicts.getRelationConflicts().size(),
241 conflicts.getWayConflicts().size(),
242 conflicts.getNodeConflicts().size())+')');
243 } else {
244 setTitle(tr("Conflict"));
245 }
246 }
247
248 /**
249 * Paints all conflicts that can be expressed on the main window.
250 *
251 * @param g The {@code Graphics} used to paint
252 * @param nc The {@code NavigatableComponent} used to get screen coordinates of nodes
253 * @since 86
254 */
255 public void paintConflicts(final Graphics g, final NavigatableComponent nc) {
256 Color preferencesColor = getColor();
257 if (preferencesColor.equals(BACKGROUND_COLOR.get()))
258 return;
259 g.setColor(preferencesColor);
260 OsmPrimitiveVisitor conflictPainter = new ConflictPainter(nc, g);
261 synchronized (this) {
262 for (OsmPrimitive o : lstConflicts.getSelectedValuesList()) {
263 if (conflicts == null || !conflicts.hasConflictForMy(o)) {
264 continue;
265 }
266 conflicts.getConflictForMy(o).getTheir().accept(conflictPainter);
267 }
268 }
269 }
270
271 @Override
272 public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
273 removeDataLayerListeners(e.getPreviousDataLayer());
274 addDataLayerListeners(e.getSource().getActiveDataLayer());
275 refreshView();
276 }
277
278 private void addDataLayerListeners(OsmDataLayer newLayer) {
279 if (newLayer != null) {
280 newLayer.getConflicts().addConflictListener(this);
281 newLayer.data.addSelectionListener(this);
282 }
283 }
284
285 private void removeDataLayerListeners(OsmDataLayer oldLayer) {
286 if (oldLayer != null) {
287 oldLayer.getConflicts().removeConflictListener(this);
288 oldLayer.data.removeSelectionListener(this);
289 }
290 }
291
292 /**
293 * replies the conflict collection currently held by this dialog; may be null
294 *
295 * @return the conflict collection currently held by this dialog; may be null
296 */
297 public synchronized ConflictCollection getConflicts() {
298 return conflicts;
299 }
300
301 /**
302 * returns the first selected item of the conflicts list
303 *
304 * @return Conflict
305 */
306 public synchronized Conflict<? extends OsmPrimitive> getSelectedConflict() {
307 if (conflicts == null || model.getSize() == 0)
308 return null;
309
310 int index = lstConflicts.getSelectedIndex();
311
312 return index >= 0 && index < conflicts.size() ? conflicts.get(index) : null;
313 }
314
315 private synchronized boolean isConflictSelected() {
316 final ListSelectionModel selModel = lstConflicts.getSelectionModel();
317 return selModel.getMinSelectionIndex() >= 0 && selModel.getMaxSelectionIndex() >= selModel.getMinSelectionIndex();
318 }
319
320 @Override
321 public void onConflictsAdded(ConflictCollection conflicts) {
322 refreshView();
323 }
324
325 @Override
326 public void onConflictsRemoved(ConflictCollection conflicts) {
327 Logging.debug("1 conflict has been resolved.");
328 refreshView();
329 }
330
331 @Override
332 public synchronized void selectionChanged(SelectionChangeEvent event) {
333 lstConflicts.setValueIsAdjusting(true);
334 lstConflicts.clearSelection();
335 for (OsmPrimitive osm : event.getSelection()) {
336 if (conflicts != null && conflicts.hasConflictForMy(osm)) {
337 int pos = model.indexOf(osm);
338 if (pos >= 0) {
339 lstConflicts.addSelectionInterval(pos, pos);
340 }
341 }
342 }
343 lstConflicts.setValueIsAdjusting(false);
344 }
345
346 @Override
347 public String helpTopic() {
348 return ht("/Dialog/ConflictList");
349 }
350
351 static final class ResolveButtonsPopupMenuListener implements PopupMenuListener {
352 private final JMenuItem btnResolveTheir;
353 private final JMenuItem btnResolveMy;
354
355 ResolveButtonsPopupMenuListener(JMenuItem btnResolveTheir, JMenuItem btnResolveMy) {
356 this.btnResolveTheir = btnResolveTheir;
357 this.btnResolveMy = btnResolveMy;
358 }
359
360 @Override
361 public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
362 btnResolveMy.setVisible(ExpertToggleAction.isExpert());
363 btnResolveTheir.setVisible(ExpertToggleAction.isExpert());
364 }
365
366 @Override
367 public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
368 // Do nothing
369 }
370
371 @Override
372 public void popupMenuCanceled(PopupMenuEvent e) {
373 // Do nothing
374 }
375 }
376
377 class MouseEventHandler extends PopupMenuLauncher {
378 /**
379 * Constructs a new {@code MouseEventHandler}.
380 */
381 MouseEventHandler() {
382 super(popupMenu);
383 }
384
385 @Override public void mouseClicked(MouseEvent e) {
386 if (isDoubleClick(e)) {
387 resolve();
388 }
389 }
390 }
391
392 /**
393 * The {@link ListModel} for conflicts
394 *
395 */
396 class ConflictListModel implements ListModel<OsmPrimitive> {
397
398 private final CopyOnWriteArrayList<ListDataListener> listeners;
399
400 /**
401 * Constructs a new {@code ConflictListModel}.
402 */
403 ConflictListModel() {
404 listeners = new CopyOnWriteArrayList<>();
405 }
406
407 @Override
408 public void addListDataListener(ListDataListener l) {
409 if (l != null) {
410 listeners.addIfAbsent(l);
411 }
412 }
413
414 @Override
415 public void removeListDataListener(ListDataListener l) {
416 listeners.remove(l);
417 }
418
419 protected void fireContentChanged() {
420 ListDataEvent evt = new ListDataEvent(
421 this,
422 ListDataEvent.CONTENTS_CHANGED,
423 0,
424 getSize()
425 );
426 for (ListDataListener listener : listeners) {
427 listener.contentsChanged(evt);
428 }
429 }
430
431 @Override
432 public synchronized OsmPrimitive getElementAt(int index) {
433 if (index < 0 || index >= getSize())
434 return null;
435 return conflicts.get(index).getMy();
436 }
437
438 @Override
439 public synchronized int getSize() {
440 return conflicts != null ? conflicts.size() : 0;
441 }
442
443 public synchronized int indexOf(OsmPrimitive my) {
444 if (conflicts != null) {
445 return IntStream.range(0, conflicts.size())
446 .filter(i -> conflicts.get(i).isMatchingMy(my))
447 .findFirst().orElse(-1);
448 }
449 return -1;
450 }
451
452 public synchronized OsmPrimitive get(int idx) {
453 return conflicts != null ? conflicts.get(idx).getMy() : null;
454 }
455 }
456
457 class ResolveAction extends AbstractAction implements ListSelectionListener {
458 ResolveAction() {
459 putValue(NAME, tr("Resolve"));
460 putValue(SHORT_DESCRIPTION, tr("Open a merge dialog of all selected items in the list above."));
461 new ImageProvider("dialogs", "conflict").getResource().attachImageIcon(this, true);
462 putValue("help", ht("/Dialog/ConflictList#ResolveAction"));
463 }
464
465 @Override
466 public void actionPerformed(ActionEvent e) {
467 resolve();
468 }
469
470 @Override
471 public void valueChanged(ListSelectionEvent e) {
472 setEnabled(isConflictSelected());
473 }
474 }
475
476 final class SelectAction extends AbstractSelectAction implements ListSelectionListener {
477 private SelectAction() {
478 putValue("help", ht("/Dialog/ConflictList#SelectAction"));
479 }
480
481 @Override
482 public void actionPerformed(ActionEvent e) {
483 Collection<OsmPrimitive> sel = new LinkedList<>();
484 synchronized (this) {
485 for (OsmPrimitive o : lstConflicts.getSelectedValuesList()) {
486 sel.add(o);
487 }
488 }
489 DataSet ds = MainApplication.getLayerManager().getEditDataSet();
490 if (ds != null) { // Can't see how it is possible but it happened in #7942
491 ds.setSelected(sel);
492 }
493 }
494
495 @Override
496 public void valueChanged(ListSelectionEvent e) {
497 setEnabled(isConflictSelected());
498 }
499 }
500
501 abstract class ResolveToAction extends ResolveAction {
502 private final String name;
503 private final MergeDecisionType type;
504
505 ResolveToAction(String name, String description, MergeDecisionType type) {
506 this.name = name;
507 this.type = type;
508 putValue(NAME, name);
509 putValue(SHORT_DESCRIPTION, description);
510 }
511
512 @Override
513 public void actionPerformed(ActionEvent e) {
514 final ConflictResolver resolver = new ConflictResolver();
515 final List<Command> commands = new ArrayList<>();
516 synchronized (this) {
517 for (OsmPrimitive osmPrimitive : lstConflicts.getSelectedValuesList()) {
518 Conflict<? extends OsmPrimitive> c = conflicts.getConflictForMy(osmPrimitive);
519 if (c != null) {
520 resolver.populate(c);
521 resolver.decideRemaining(type);
522 commands.add(resolver.buildResolveCommand());
523 }
524 }
525 }
526 UndoRedoHandler.getInstance().add(new SequenceCommand(name, commands));
527 refreshView();
528 }
529 }
530
531 class ResolveToMyVersionAction extends ResolveToAction {
532 ResolveToMyVersionAction() {
533 super(tr("Resolve to my versions"), tr("Resolves all unresolved conflicts to ''my'' version"),
534 MergeDecisionType.KEEP_MINE);
535 }
536 }
537
538 class ResolveToTheirVersionAction extends ResolveToAction {
539 ResolveToTheirVersionAction() {
540 super(tr("Resolve to their versions"), tr("Resolves all unresolved conflicts to ''their'' version"),
541 MergeDecisionType.KEEP_THEIR);
542 }
543 }
544
545 /**
546 * Paints conflicts.
547 */
548 public static class ConflictPainter implements OsmPrimitiveVisitor {
549 // Manage a stack of visited relations to avoid infinite recursion with cyclic relations (fix #7938)
550 private final Set<Relation> visited = new HashSet<>();
551 private final NavigatableComponent nc;
552 private final Graphics g;
553
554 ConflictPainter(NavigatableComponent nc, Graphics g) {
555 this.nc = nc;
556 this.g = g;
557 }
558
559 @Override
560 public void visit(Node n) {
561 Point p = nc.getPoint(n);
562 g.drawRect(p.x-1, p.y-1, 2, 2);
563 }
564
565 private void visit(Node n1, Node n2) {
566 Point p1 = nc.getPoint(n1);
567 Point p2 = nc.getPoint(n2);
568 g.drawLine(p1.x, p1.y, p2.x, p2.y);
569 }
570
571 @Override
572 public void visit(Way w) {
573 Node lastN = null;
574 for (Node n : w.getNodes()) {
575 if (lastN == null) {
576 lastN = n;
577 continue;
578 }
579 visit(lastN, n);
580 lastN = n;
581 }
582 }
583
584 @Override
585 public void visit(Relation e) {
586 if (!visited.contains(e)) {
587 visited.add(e);
588 try {
589 for (RelationMember em : e.getMembers()) {
590 em.getMember().accept(this);
591 }
592 } finally {
593 visited.remove(e);
594 }
595 }
596 }
597 }
598
599 /**
600 * Warns the user about the number of detected conflicts
601 *
602 * @param numNewConflicts the number of detected conflicts
603 * @since 5775
604 */
605 public void warnNumNewConflicts(int numNewConflicts) {
606 if (numNewConflicts == 0)
607 return;
608
609 String msg1 = trn(
610 "There was {0} conflict detected.",
611 "There were {0} conflicts detected.",
612 numNewConflicts,
613 numNewConflicts
614 );
615
616 final StringBuilder sb = new StringBuilder();
617 sb.append("<html>").append(msg1).append("</html>");
618 if (numNewConflicts > 0) {
619 final ButtonSpec[] options = {
620 new ButtonSpec(
621 tr("OK"),
622 new ImageProvider("ok"),
623 tr("Click to close this dialog and continue editing"),
624 null /* no specific help */
625 )
626 };
627 GuiHelper.runInEDT(() -> {
628 HelpAwareOptionPane.showOptionDialog(
629 MainApplication.getMainFrame(),
630 sb.toString(),
631 tr("Conflicts detected"),
632 JOptionPane.WARNING_MESSAGE,
633 null, /* no icon */
634 options,
635 options[0],
636 ht("/Concepts/Conflict#WarningAboutDetectedConflicts")
637 );
638 unfurlDialog();
639 MainApplication.getMap().repaint();
640 });
641 }
642 }
643}
Note: See TracBrowser for help on using the repository browser.