001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.history;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005import static org.openstreetmap.josm.tools.I18n.trn;
006
007import java.awt.Component;
008import java.awt.Dimension;
009import java.awt.Point;
010import java.util.ArrayList;
011import java.util.Collection;
012import java.util.Iterator;
013import java.util.LinkedHashMap;
014import java.util.LinkedList;
015import java.util.List;
016import java.util.Map.Entry;
017import java.util.Objects;
018
019import javax.swing.JOptionPane;
020import javax.swing.SwingUtilities;
021import javax.swing.event.ChangeEvent;
022
023import org.openstreetmap.josm.data.osm.PrimitiveId;
024import org.openstreetmap.josm.data.osm.history.History;
025import org.openstreetmap.josm.data.osm.history.HistoryDataSet;
026import org.openstreetmap.josm.gui.MainApplication;
027import org.openstreetmap.josm.gui.layer.LayerManager.LayerAddEvent;
028import org.openstreetmap.josm.gui.layer.LayerManager.LayerChangeListener;
029import org.openstreetmap.josm.gui.layer.LayerManager.LayerOrderChangeEvent;
030import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent;
031import org.openstreetmap.josm.gui.util.WindowGeometry;
032import org.openstreetmap.josm.spi.preferences.Config;
033import org.openstreetmap.josm.tools.JosmRuntimeException;
034import org.openstreetmap.josm.tools.Logging;
035import org.openstreetmap.josm.tools.SubclassFilteredCollection;
036import org.openstreetmap.josm.tools.bugreport.BugReportExceptionHandler;
037
038/**
039 * Manager allowing to show/hide history dialogs.
040 * @since 2019
041 */
042public final class HistoryBrowserDialogManager implements LayerChangeListener {
043
044    private static boolean isUnloaded(PrimitiveId p) {
045        History h = HistoryDataSet.getInstance().getHistory(p);
046        if (h == null)
047            // reload if the history is not in the cache yet
048            return true;
049        else
050            // reload if the history object of the selected object is not in the cache yet
051            return !p.isNew() && h.getByVersion(p.getUniqueId()) == null;
052    }
053
054    private static final String WINDOW_GEOMETRY_PREF = HistoryBrowserDialogManager.class.getName() + ".geometry";
055
056    private static HistoryBrowserDialogManager instance;
057
058    private final LinkedHashMap<Long, HistoryBrowserDialog> dialogs = new LinkedHashMap<>();
059
060    private static final List<HistoryHook> hooks = new ArrayList<>();
061
062    private HistoryBrowserDialogManager() {
063        MainApplication.getLayerManager().addLayerChangeListener(this);
064    }
065
066    /**
067     * Replies the unique instance.
068     * @return the unique instance
069     */
070    public static synchronized HistoryBrowserDialogManager getInstance() {
071        if (instance == null) {
072            instance = new HistoryBrowserDialogManager();
073        }
074        return instance;
075    }
076
077    /**
078     * Determines if an history dialog exists for the given object id.
079     * @param id the object id
080     * @return {@code true} if an history dialog exists for the given object id, {@code false} otherwise
081     */
082    public boolean existsDialog(long id) {
083        return dialogs.containsKey(id);
084    }
085
086    private boolean hasDialogWithCloseUpperLeftCorner(Point p) {
087        return dialogs.values().stream()
088                .map(Component::getLocation)
089                .anyMatch(corner -> p.x >= corner.x - 5 && corner.x + 5 >= p.x && p.y >= corner.y - 5 && corner.y + 5 >= p.y);
090    }
091
092    private void placeOnScreen(HistoryBrowserDialog dialog) {
093        WindowGeometry geometry = new WindowGeometry(WINDOW_GEOMETRY_PREF, WindowGeometry.centerOnScreen(new Dimension(850, 500)));
094        geometry.applySafe(dialog);
095        Point p = dialog.getLocation();
096        while (hasDialogWithCloseUpperLeftCorner(p)) {
097            p.x += 20;
098            p.y += 20;
099        }
100        dialog.setLocation(p);
101    }
102
103    /**
104     * Hides the specified history dialog and cleans associated resources.
105     * @param dialog History dialog to hide
106     */
107    public void hide(HistoryBrowserDialog dialog) {
108        for (Iterator<Entry<Long, HistoryBrowserDialog>> it = dialogs.entrySet().iterator(); it.hasNext();) {
109            if (Objects.equals(it.next().getValue(), dialog)) {
110                it.remove();
111                if (dialogs.isEmpty()) {
112                    new WindowGeometry(dialog).remember(WINDOW_GEOMETRY_PREF);
113                }
114                break;
115            }
116        }
117        dialog.setVisible(false);
118        dialog.dispose();
119
120        if (!dialogs.isEmpty()) {
121            // see #17270: set focus to last dialog
122            new LinkedList<>(dialogs.values()).getLast().toFront();
123        } else {
124            // we always reload the history, so there is no need to keep it in the cache.
125            HistoryDataSet.getInstance().clear();
126        }
127    }
128
129    /**
130     * Hides and destroys all currently visible history browser dialogs
131     * @since 2448
132     */
133    public void hideAll() {
134        new ArrayList<>(dialogs.values()).forEach(this::hide);
135    }
136
137    /**
138     * Show history dialog for the given history.
139     * @param h History to show
140     * @since 2448
141     */
142    public void show(History h) {
143        if (h == null)
144            return;
145        if (existsDialog(h.getId())) {
146            dialogs.get(h.getId()).toFront();
147        } else {
148            HistoryBrowserDialog dialog = new HistoryBrowserDialog(h);
149            placeOnScreen(dialog);
150            dialog.setVisible(true);
151            dialog.getHistoryBrowser().stateChanged(new ChangeEvent(this));
152            dialogs.put(h.getId(), dialog);
153        }
154    }
155
156    /* ----------------------------------------------------------------------------- */
157    /* LayerChangeListener                                                           */
158    /* ----------------------------------------------------------------------------- */
159    @Override
160    public void layerAdded(LayerAddEvent e) {
161        // Do nothing
162    }
163
164    @Override
165    public void layerRemoving(LayerRemoveEvent e) {
166        // remove all history browsers if the number of layers drops to 0
167        if (e.getSource().getLayers().isEmpty()) {
168            hideAll();
169        }
170    }
171
172    @Override
173    public void layerOrderChanged(LayerOrderChangeEvent e) {
174        // Do nothing
175    }
176
177    /**
178     * Adds a new {@code HistoryHook}.
179     * @param hook hook to add
180     * @return {@code true} (as specified by {@link Collection#add})
181     * @since 13947
182     */
183    public static boolean addHistoryHook(HistoryHook hook) {
184        return hooks.add(Objects.requireNonNull(hook));
185    }
186
187    /**
188     * Removes an existing {@code HistoryHook}.
189     * @param hook hook to remove
190     * @return {@code true} if this list contained the specified element
191     * @since 13947
192     */
193    public static boolean removeHistoryHook(HistoryHook hook) {
194        return hooks.remove(Objects.requireNonNull(hook));
195    }
196
197    /**
198     * Show history dialog(s) for the given primitive(s).
199     * @param primitives The primitive(s) for which history will be displayed
200     */
201    public void showHistory(final Collection<? extends PrimitiveId> primitives) {
202        showHistory(MainApplication.getMainFrame(), primitives);
203    }
204
205    /**
206     * Show history dialog(s) for the given primitive(s).
207     * @param parent Parent component for displayed dialog boxes
208     * @param primitives The primitive(s) for which history will be displayed
209     * @since 16123
210     */
211    public void showHistory(Component parent, final Collection<? extends PrimitiveId> primitives) {
212        final List<PrimitiveId> realPrimitives = new ArrayList<>(primitives);
213        hooks.forEach(h -> h.modifyRequestedIds(realPrimitives));
214        final Collection<? extends PrimitiveId> notNewPrimitives = SubclassFilteredCollection.filter(realPrimitives, p1 -> !p1.isNew());
215        if (notNewPrimitives.isEmpty()) {
216            JOptionPane.showMessageDialog(
217                    parent,
218                    tr("Please select at least one already uploaded node, way, or relation."),
219                    tr("Warning"),
220                    JOptionPane.WARNING_MESSAGE);
221            return;
222        }
223        if (notNewPrimitives.size() > Config.getPref().getInt("warn.open.maxhistory", 5) &&
224                /* I18N english text for value 1 makes no real sense, never called for values <= maxhistory (usually 5) */
225                JOptionPane.OK_OPTION != JOptionPane.showConfirmDialog(MainApplication.getMainFrame(),
226                        "<html>" + trn(
227                                "You are about to open <b>{0}</b> history dialog.<br/>Do you want to continue?",
228                                "You are about to open <b>{0}</b> different history dialogs simultaneously.<br/>Do you want to continue?",
229                                notNewPrimitives.size(), notNewPrimitives.size()) + "</html>",
230                        tr("Confirmation"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE)) {
231            return;
232        }
233
234        Collection<? extends PrimitiveId> toLoad = SubclassFilteredCollection.filter(notNewPrimitives, HistoryBrowserDialogManager::isUnloaded);
235        if (!toLoad.isEmpty()) {
236            MainApplication.worker.submit(new HistoryLoadTask(parent).addPrimitiveIds(toLoad));
237        }
238
239        Runnable r = () -> {
240            try {
241                for (PrimitiveId p : notNewPrimitives) {
242                    final History h = HistoryDataSet.getInstance().getHistory(p);
243                    if (h == null) {
244                        Logging.warn("{0} not found in HistoryDataSet", p);
245                        continue;
246                    }
247                    SwingUtilities.invokeLater(() -> show(h));
248                }
249            } catch (final JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
250                BugReportExceptionHandler.handleException(e);
251            }
252        };
253        MainApplication.worker.submit(r);
254    }
255}