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;
007
008import org.openstreetmap.josm.gui.util.ChangeNotifier;
009
010/**
011 * Help browser history.
012 * @since 2274
013 */
014public class HelpBrowserHistory extends ChangeNotifier {
015    private final IHelpBrowser browser;
016    private List<String> history;
017    private int historyPos;
018
019    /**
020     * Constructs a new {@code HelpBrowserHistory}.
021     * @param browser help browser
022     */
023    public HelpBrowserHistory(IHelpBrowser browser) {
024        this.browser = browser;
025        history = new ArrayList<>();
026    }
027
028    /**
029     * Clears the history.
030     */
031    public void clear() {
032        history.clear();
033        historyPos = 0;
034        fireStateChanged();
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        fireStateChanged();
063    }
064
065    /**
066     * Go forward.
067     */
068    public void forward() {
069        historyPos++;
070        if (historyPos >= history.size())
071            return;
072        String url = history.get(historyPos);
073        browser.openUrl(url);
074        fireStateChanged();
075    }
076
077    /**
078     * Remembers the new current URL.
079     * @param url the new current URL
080     */
081    public void setCurrentUrl(String url) {
082        boolean add = true;
083
084        if (historyPos >= 0 && historyPos < history.size() && history.get(historyPos).equals(url)) {
085            add = false;
086        } else if (historyPos == history.size() -1) {
087            // do nothing just append
088        } else if (historyPos == 0 && !history.isEmpty()) {
089            history = new ArrayList<>(Collections.singletonList(history.get(0)));
090        } else if (historyPos < history.size() -1 && historyPos > 0) {
091            history = new ArrayList<>(history.subList(0, historyPos));
092        } else {
093            history = new ArrayList<>();
094        }
095        if (add) {
096            history.add(url);
097            historyPos = history.size()-1;
098        }
099        fireStateChanged();
100    }
101}