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
009public class HelpBrowserHistory extends Observable {
010    private HelpBrowser browser;
011    private List<String> history;
012    private int historyPos;
013
014    public HelpBrowserHistory(HelpBrowser browser) {
015        this.browser = browser;
016        history = new ArrayList<>();
017    }
018
019    public void clear() {
020        history.clear();
021        historyPos = 0;
022        setChanged();
023        notifyObservers();
024    }
025
026    public boolean canGoBack() {
027        return historyPos > 0;
028    }
029
030    public boolean canGoForward() {
031        return historyPos + 1 < history.size();
032    }
033
034    public void back() {
035        historyPos--;
036        if (historyPos < 0) return;
037        String url = history.get(historyPos);
038        browser.openUrl(url);
039        setChanged();
040        notifyObservers();
041    }
042
043    public void forward() {
044        historyPos++;
045        if (historyPos >= history.size()) return;
046        String url = history.get(historyPos);
047        browser.openUrl(url);
048        setChanged();
049        notifyObservers();
050    }
051
052    public void setCurrentUrl(String url) {
053        boolean add = true;
054
055        if (historyPos >= 0 && historyPos < history.size() && history.get(historyPos).equals(url)) {
056            add = false;
057        } else if (historyPos == history.size() -1) {
058            // do nothing just append
059        } else if (historyPos == 0 && !history.isEmpty()) {
060            history = new ArrayList<>(Collections.singletonList(history.get(0)));
061        } else if (historyPos < history.size() -1 && historyPos > 0) {
062            history = new ArrayList<>(history.subList(0, historyPos));
063        } else {
064            history = new ArrayList<>();
065        }
066        if (add) {
067            history.add(url);
068            historyPos = history.size()-1;
069        }
070        setChanged();
071        notifyObservers();
072    }
073}