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 if (url != null) { 083 boolean add = true; 084 085 if (historyPos >= 0 && historyPos < history.size() && history.get(historyPos).equals(url)) { 086 add = false; 087 } else if (historyPos == history.size() -1) { 088 // do nothing just append 089 } else if (historyPos == 0 && !history.isEmpty()) { 090 history = new ArrayList<>(Collections.singletonList(history.get(0))); 091 } else if (historyPos < history.size() -1 && historyPos > 0) { 092 history = new ArrayList<>(history.subList(0, historyPos)); 093 } else { 094 history = new ArrayList<>(); 095 } 096 if (add) { 097 history.add(url); 098 historyPos = history.size()-1; 099 } 100 fireStateChanged(); 101 } 102 } 103}