001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.help;
003
004import java.util.ArrayList;
005import java.util.Collections;
006import java.util.List;
007import java.util.Observable;
008
009/**
010 * Help browser history.
011 * @since 2274
012 */
013public class HelpBrowserHistory extends Observable {
014    private final IHelpBrowser browser;
015    private List<String> history;
016    private int historyPos;
017
018    /**
019     * Constructs a new {@code HelpBrowserHistory}.
020     * @param browser help browser
021     */
022    public HelpBrowserHistory(IHelpBrowser browser) {
023        this.browser = browser;
024        history = new ArrayList<>();
025    }
026
027    /**
028     * Clears the history.
029     */
030    public void clear() {
031        history.clear();
032        historyPos = 0;
033        setChanged();
034        notifyObservers();
035    }
036
037    /**
038     * Determines if the help browser can go back.
039     * @return {@code true} if a previous history position exists
040     */
041    public boolean canGoBack() {
042        return historyPos > 0;
043    }
044
045    /**
046     * Determines if the help browser can go forward.
047     * @return {@code true} if a following history position exists
048     */
049    public boolean canGoForward() {
050        return historyPos + 1 < history.size();
051    }
052
053    /**
054     * Go back.
055     */
056    public void back() {
057        historyPos--;
058        if (historyPos < 0)
059            return;
060        String url = history.get(historyPos);
061        browser.openUrl(url);
062        setChanged();
063        notifyObservers();
064    }
065
066    /**
067     * Go forward.
068     */
069    public void forward() {
070        historyPos++;
071        if (historyPos >= history.size())
072            return;
073        String url = history.get(historyPos);
074        browser.openUrl(url);
075        setChanged();
076        notifyObservers();
077    }
078
079    /**
080     * Remembers the new current URL.
081     * @param url the new current URL
082     */
083    public void setCurrentUrl(String url) {
084        boolean add = true;
085
086        if (historyPos >= 0 && historyPos < history.size() && history.get(historyPos).equals(url)) {
087            add = false;
088        } else if (historyPos == history.size() -1) {
089            // do nothing just append
090        } else if (historyPos == 0 && !history.isEmpty()) {
091            history = new ArrayList<>(Collections.singletonList(history.get(0)));
092        } else if (historyPos < history.size() -1 && historyPos > 0) {
093            history = new ArrayList<>(history.subList(0, historyPos));
094        } else {
095            history = new ArrayList<>();
096        }
097        if (add) {
098            history.add(url);
099            historyPos = history.size()-1;
100        }
101        setChanged();
102        notifyObservers();
103    }
104}