package es.iiia.sgi.tools;
import java.beans.PropertyChangeListener;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.swt.events.MouseListener;
import es.iiia.sgi.Activator;
import es.iiia.sgi.actions.OpenRecentFileAction;
public class RecentFilesTools {
private IMenuManager menu;
public RecentFilesTools(IMenuManager menu) {
this.menu = menu;
}
public void addRecentFile(String fileName, String menuID, String recentMenuID, String recentFilesKey, String menuLabel, PropertyChangeListener listener) {
Plugin plugin = Activator.getDefault();
Preferences prefs = plugin.getPluginPreferences();
String recentFiles = prefs.getString(recentFilesKey);
if (recentFiles == null) {
recentFiles = "";
}
String[] recentFilesArray = recentFiles.split(";");
String[] newFilesArray = new String[10];
// put new file
newFilesArray[0] = fileName;
// move files
for (int i = 0; i < 9; i++) {
// check files
if (i >= recentFilesArray.length) {
break;
}
// check if file has not been already added
if (!fileName.equals(recentFilesArray[i])) {
newFilesArray[i + 1] = recentFilesArray[i];
}
}
// now join
recentFiles = "";
for (String file : newFilesArray) {
if (file != null && file != "") {
recentFiles += file + ";";
}
}
// store preference
prefs.setValue(recentFilesKey, recentFiles);
plugin.savePluginPreferences();
// rebuild menu
rebuildRecentFiles(menuID, recentMenuID, recentFilesKey, menuLabel, listener);
}
public void rebuildRecentFiles(String menuID, String recentMenuID, String recentFilesKey, String menuLabel, PropertyChangeListener listener) {
// Get list of grammars
MenuManager fileMenu = (MenuManager) menu.find(menuID);
MenuManager viewMenu = (MenuManager) fileMenu.find(recentMenuID); //"recentGrammars"
if (viewMenu != null) {
fileMenu.remove(viewMenu);
}
viewMenu = new MenuManager(menuLabel, recentMenuID);
String[] recentFiles = getRecentFiles(recentFilesKey);
for (String file : recentFiles) {
if (file == "")
break;
viewMenu.add(new OpenRecentFileAction(file, listener));
}
// insert it before exit
fileMenu.insert(fileMenu.getSize() - 1, new Separator());
fileMenu.insert(fileMenu.getSize() - 1, viewMenu);
}
public String[] getRecentFiles(String recentFilesKey) {
Plugin plugin = Activator.getDefault();
Preferences prefs = plugin.getPluginPreferences();
String recentFiles = prefs.getString(recentFilesKey);
return recentFiles.split(";");
}
}