Ghidra is a software reverse engineering (SRE) framework
add bundlepathmanager for scripting
Jason P. Leasure931a9e823008
diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/PickPathsDialog.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/BundlePathSelectionDialog.javasimilarity index 66%rename from Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/PickPathsDialog.javarename to Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/BundlePathSelectionDialog.javaindex 2e4cf56503..b602ef8500 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/PickPathsDialog.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/BundlePathSelectionDialog.java@@ -20,25 +20,25 @@ import javax.swing.JComponent;import docking.DialogComponentProvider;import docking.DockingWindowManager;-import docking.widgets.pathmanager.PathManager;-import docking.widgets.pathmanager.PathManagerListener;+import docking.widgets.bundlemanager.BundlePathManager;+import docking.widgets.bundlemanager.BundlePathManagerListener;-public class PickPathsDialog extends DialogComponentProvider implements PathManagerListener {+public class BundlePathSelectionDialog extends DialogComponentProvider implements BundlePathManagerListener {private JComponent parent;- private PathManager pathMgr;+ private BundlePathManager bundlePathMgr;private boolean changed = false;- public PickPathsDialog(JComponent parent, PathManager pathMgr) {- super("Script Directories");+ public BundlePathSelectionDialog(JComponent parent, BundlePathManager bundleManager) {+ super("Script Bundles");this.parent = parent;- this.pathMgr = pathMgr;- pathMgr.addListener(this);- addWorkPanel(pathMgr.getComponent());+ this.bundlePathMgr = bundleManager;+ bundleManager.addListener(this);+ addWorkPanel(bundleManager.getComponent());addDismissButton();}- PathManager getPathManager() {- return pathMgr;+ BundlePathManager getBundleManager() {+ return bundlePathMgr;}@Override@@ -47,7 +47,7 @@ public class PickPathsDialog extends DialogComponentProvider implements PathMana}@Override- public void pathsChanged() {+ public void bundlesChanged() {changed = true;}@@ -61,7 +61,7 @@ public class PickPathsDialog extends DialogComponentProvider implements PathMana@Overrideprotected void dismissCallback() {- pathMgr.removeListener(this);+ bundlePathMgr.removeListener(this);close();}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.javaindex 6c96879a62..60d908926f 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptActionManager.java@@ -353,7 +353,7 @@ class GhidraScriptActionManager {scriptDirsAction = new DockingAction("Script Directories", plugin.getName()) {@Overridepublic void actionPerformed(ActionContext context) {- provider.pickPaths();+ provider.showBundlePathSelectionDialog();}@Overridediff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptComponentProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptComponentProvider.javaindex 0f5cb4331d..5a2778a311 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptComponentProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptComponentProvider.java@@ -33,9 +33,7 @@ import docking.ActionContext;import docking.action.KeyBindingData;import docking.event.mouse.GMouseListenerAdapter;import docking.widgets.OptionDialog;-import docking.widgets.filechooser.GhidraFileChooserMode;-import docking.widgets.pathmanager.PathManager;-import docking.widgets.pathmanager.PathManagerListener;+import docking.widgets.bundlemanager.*;import docking.widgets.table.*;import docking.widgets.tree.GTree;import docking.widgets.tree.GTreeNode;@@ -47,10 +45,10 @@ import ghidra.app.services.ConsoleService;import ghidra.framework.options.SaveState;import ghidra.framework.plugintool.ComponentProviderAdapter;import ghidra.program.model.listing.Program;-import ghidra.util.HelpLocation;-import ghidra.util.Msg;+import ghidra.util.*;import ghidra.util.datastruct.WeakDataStructureFactory;import ghidra.util.datastruct.WeakSet;+import ghidra.util.exception.CancelledException;import ghidra.util.table.GhidraTableFilterPanel;import ghidra.util.task.*;import resources.ResourceManager;@@ -72,7 +70,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {private GTree scriptCategoryTree;private DraggableScriptTable scriptTable;private GhidraScriptTableModel tableModel;- private PathManager pathManager;+ private BundlePathManager bundlePathManager;private TaskListener taskListener = new ScriptTaskListener();private GhidraScriptActionManager actionManager;private GhidraTableFilterPanel<ResourceFile> tableFilterPanel;@@ -120,7 +118,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {scriptTable.dispose();tableFilterPanel.dispose();actionManager.dispose();- pathManager.dispose();+ bundlePathManager.dispose();}GhidraScriptActionManager getActionManager() {@@ -131,8 +129,9 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {return editorMap;}- void pickPaths() {- PickPathsDialog pd = new PickPathsDialog(getComponent(), pathManager);+ void showBundlePathSelectionDialog() {+ BundlePathSelectionDialog pd =+ new BundlePathSelectionDialog(getComponent(), bundlePathManager);pd.setHelpLocation(actionManager.getPathHelpLocation());pd.show();if (pd.hasChanged()) {@@ -149,9 +148,8 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}private void performRefresh() {-- GhidraScriptUtil.setScriptDirectories(pathManager.getPaths());- GhidraScriptUtil.clean();+ GhidraScriptUtil.setScriptDirectories(bundlePathManager.getPaths());+ GhidraScriptUtil.clearMetadata();refresh();}@@ -207,7 +205,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {return;}- checkNewScriptDirectoryEnablement(renameFile);+ enableScriptDirectory(renameFile.getParentFile());renameScriptByCopying(script, provider, renameFile);}@@ -354,15 +352,15 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}}- public List<Path> getScriptDirectories() {- return pathManager.getPaths();+ public List<BundlePath> getScriptDirectories() {+ return bundlePathManager.getPaths();}- public void checkNewScriptDirectoryEnablement(ResourceFile scriptFile) {- if (pathManager.addPath(scriptFile.getParentFile(), true)) {+ public void enableScriptDirectory(ResourceFile scriptDir) {+ if (bundlePathManager.enablePath(scriptDir)) {Msg.showInfo(this, getComponent(), "Script Path Added/Enabled",- "The directory containing the new script has been automatically enabled for use:\n" +- scriptFile.getParentFile().getAbsolutePath());+ "The directory has been automatically enabled for use:\n" ++ scriptDir.getAbsolutePath());}}@@ -386,7 +384,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}newFile = dialog.getFile();- checkNewScriptDirectoryEnablement(newFile);+ enableScriptDirectory(newFile.getParentFile());String category = StringUtils.join(getSelectedCategoryPath(), ScriptInfo.DELIMITTER);provider.createNewScript(newFile, category);@@ -410,7 +408,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}void runScript(String scriptName, TaskListener listener) {- List<Path> dirPaths = pathManager.getPaths();+ List<BundlePath> dirPaths = bundlePathManager.getPaths();for (Path dir : dirPaths) {ResourceFile scriptSource = new ResourceFile(dir.getPath(), scriptName);if (scriptSource.exists()) {@@ -427,7 +425,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {void runScript(ResourceFile scriptFile, TaskListener listener) {if (SystemUtilities.isEventDispatchThread()) {- new TaskLauncher(new Task("compiling script", true, true, true, true) {+ new TaskLauncher(new Task("compiling script directory", true, false, true, true) {@Overridepublic void run(TaskMonitor monitor) throws CancelledException {doRunScript(scriptFile, listener);@@ -532,7 +530,6 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}void refresh() {-hasBeenRefreshed = true;TreePath preRefreshSelectionPath = scriptCategoryTree.getSelectionPath();@@ -550,13 +547,14 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}private void updateAvailableScriptFilesForAllPaths() {-List<ResourceFile> scriptsToRemove = tableModel.getScripts();List<ResourceFile> scriptAccumulator = new ArrayList<>();- List<Path> dirPaths = pathManager.getPaths();- for (Path dirPath : dirPaths) {- updateAvailableScriptFilesForDirectory(scriptsToRemove, scriptAccumulator,- dirPath.getPath());+ List<BundlePath> bundlePaths = bundlePathManager.getPaths();+ for (BundlePath bundlePath : bundlePaths) {+ if (bundlePath.isDirectory()) {+ updateAvailableScriptFilesForDirectory(scriptsToRemove, scriptAccumulator,+ bundlePath.getPath());+ }}// note: do this after the loop to prevent a flurry of table model update events@@ -719,7 +717,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}actionManager.removeAction(script);- GhidraScriptUtil.unloadScript(script);+ GhidraScriptUtil.removeMetadata(script);return true;}@@ -747,13 +745,13 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}private void build() {- pathManager = new PathManager(GhidraScriptUtil.getDefaultScriptDirectories(), true, false);- pathManager.setFileChooserProperties("Select Script Directory", "LastGhidraScriptDirectory",- GhidraFileChooserMode.DIRECTORIES_ONLY, false, null);+ bundlePathManager = new BundlePathManager(GhidraScriptUtil.getDefaultScriptBundles());+ bundlePathManager.setFileChooserProperties("Select Script Bundle",+ "LastGhidraScriptBundle");- pathManager.addListener(new PathManagerListener() {+ bundlePathManager.addListener(new BundlePathManagerListener() {@Override- public void pathsChanged() {+ public void bundlesChanged() {if (isVisible()) { // we will be refreshed when first shownperformRefresh();}@@ -795,9 +793,8 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}});- scriptCategoryTree.getSelectionModel()- .setSelectionMode(- TreeSelectionModel.SINGLE_TREE_SELECTION);+ scriptCategoryTree.getSelectionModel().setSelectionMode(+ TreeSelectionModel.SINGLE_TREE_SELECTION);tableModel = new GhidraScriptTableModel(this);@@ -1031,10 +1028,10 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}public void readConfigState(SaveState saveState) {- pathManager.restoreState(saveState);+ bundlePathManager.restoreState(saveState);// pull in the just-loaded paths- List<Path> paths = pathManager.getPaths();+ List<BundlePath> paths = bundlePathManager.getPaths();GhidraScriptUtil.setScriptDirectories(paths);actionManager.restoreUserDefinedKeybindings(saveState);actionManager.restoreScriptsThatAreInTool(saveState);@@ -1058,7 +1055,7 @@ public class GhidraScriptComponentProvider extends ComponentProviderAdapter {}public void writeConfigState(SaveState saveState) {- pathManager.saveState(saveState);+ bundlePathManager.saveState(saveState);actionManager.saveUserDefinedKeybindings(saveState);actionManager.saveScriptsThatAreInTool(saveState);diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptEditorComponentProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptEditorComponentProvider.javaindex c6936ed36b..f3aab26e7b 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptEditorComponentProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptEditorComponentProvider.java@@ -600,7 +600,7 @@ public class GhidraScriptEditorComponentProvider extends ComponentProvider {}}- provider.checkNewScriptDirectoryEnablement(saveAsFile);+ provider.enableScriptDirectory(saveAsFile.getParentFile());try {String str = textArea.getText();diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptMgrPlugin.java b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptMgrPlugin.javaindex 498772040a..1ee5f68774 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptMgrPlugin.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/script/GhidraScriptMgrPlugin.java@@ -26,6 +26,8 @@ import ghidra.app.plugin.ProgramPlugin;import ghidra.app.plugin.core.eclipse.EclipseConnection;import ghidra.app.plugin.core.eclipse.EclipseIntegrationOptionsPlugin;import ghidra.app.script.GhidraState;+import ghidra.app.script.osgi.BundleHost;+import ghidra.app.script.osgi.OSGiException;import ghidra.app.services.*;import ghidra.framework.options.SaveState;import ghidra.framework.options.ToolOptions;@@ -48,6 +50,22 @@ import ghidra.util.task.TaskListener;//@formatter:onpublic class GhidraScriptMgrPlugin extends ProgramPlugin implements GhidraScriptService {+ // XXX embedded OSGi should be a service, but ScriptProviders don't have any way to access services+ static private BundleHost _bundle_host;++ static public BundleHost getBundleHost() {+ if (_bundle_host == null) {+ _bundle_host = new BundleHost();+ try {+ _bundle_host.startFelix();+ }+ catch (OSGiException | IOException e) {+ throw new RuntimeException(e);+ }+ }+ return _bundle_host;+ }+private GhidraScriptComponentProvider provider;public GhidraScriptMgrPlugin(PluginTool tool) {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptProvider.javaindex 673f5c2c60..6e6496ccd8 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptProvider.java@@ -62,7 +62,7 @@ public abstract class GhidraScriptProvider implements ExtensionPoint,public boolean deleteScript(ResourceFile scriptSource) {boolean deleted = !scriptSource.exists() || scriptSource.delete();if (deleted) {- GhidraScriptUtil.unloadScript(scriptSource);+ GhidraScriptUtil.removeMetadata(scriptSource);}return deleted;}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptUtil.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptUtil.javaindex 5a0f19ebb1..0b75c1e831 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptUtil.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/GhidraScriptUtil.java@@ -16,12 +16,15 @@package ghidra.app.script;import java.io.*;+import java.nio.file.Files;+import java.nio.file.Path;import java.util.*;+import java.util.stream.Collectors;import org.apache.commons.collections4.map.LazyMap;+import docking.widgets.bundlemanager.BundlePath;import generic.jar.ResourceFile;-import generic.util.Path;import ghidra.app.script.osgi.SourceBundleInfo;import ghidra.framework.Application;import ghidra.program.model.listing.Program;@@ -46,19 +49,7 @@ public class GhidraScriptUtil {*/public static String USER_SCRIPTS_DIR = buildUserScriptsDirectory();- /**- * The default compile output directory- */- //@formatter:off- @Deprecated- public static String USER_SCRIPTS_BIN_DIR =- Application.getUserSettingsDirectory() + File.separator +- "dev" + File.separator +- SCRIPTS_SUBDIR_NAME + File.separator +- BIN_DIR_NAME;- //@formatter:on-- private static List<Path> scriptDirectoryPaths = new ArrayList<>();+ private static List<BundlePath> scriptBundlePaths = new ArrayList<>();private static Map<ResourceFile, ScriptInfo> scriptFileToInfoMap = new HashMap<>();@@ -66,7 +57,7 @@ public class GhidraScriptUtil {LazyMap.lazyMap(new HashMap<String, List<ResourceFile>>(), () -> new ArrayList<>());static {- scriptDirectoryPaths = getDefaultScriptDirectories();+ scriptBundlePaths = getDefaultScriptBundles();}/** The last time a request was made to refresh */@@ -106,9 +97,9 @@ public class GhidraScriptUtil {* Returns a list of the default script directories.* @return a list of the default script directories*/- public static List<Path> getDefaultScriptDirectories() {+ public static List<BundlePath> getDefaultScriptBundles() {- List<Path> pathsList = new ArrayList<>();+ List<BundlePath> pathsList = new ArrayList<>();addScriptPaths(pathsList, SCRIPTS_SUBDIR_NAME);addScriptPaths(pathsList, DEV_SCRIPTS_SUBDIR_NAME);@@ -116,14 +107,14 @@ public class GhidraScriptUtil {Collections.sort(pathsList);// this one should always be first- pathsList.add(0, new Path(new ResourceFile(USER_SCRIPTS_DIR), true, false, false));+ pathsList.add(0, new BundlePath(new ResourceFile(USER_SCRIPTS_DIR), true, false, false));return pathsList;}- private static void addScriptPaths(List<Path> pathsList, String directoryName) {+ private static void addScriptPaths(List<BundlePath> pathsList, String directoryName) {Iterable<ResourceFile> files = Application.findModuleSubDirectories(directoryName);for (ResourceFile file : files) {- pathsList.add(new Path(file, true, false, true));+ pathsList.add(new BundlePath(file, true, false, true));}}@@ -170,7 +161,7 @@ public class GhidraScriptUtil {*/public static List<ResourceFile> getScriptSourceDirectories() {ArrayList<ResourceFile> dirs = new ArrayList<>();- for (Path path : scriptDirectoryPaths) {+ for (BundlePath path : scriptBundlePaths) {dirs.add(path.getPath());}return dirs;@@ -180,8 +171,8 @@ public class GhidraScriptUtil {* Sets the script directories to the new paths.* @param newPaths the new script directories*/- public static void setScriptDirectories(List<Path> newPaths) {- scriptDirectoryPaths = new ArrayList<>(newPaths);+ public static void setScriptDirectories(List<BundlePath> newPaths) {+ scriptBundlePaths = new ArrayList<>(newPaths);}/**@@ -189,9 +180,9 @@ public class GhidraScriptUtil {* @param directory the directory* @return the path for the specified directory*/- public static Path getScriptPath(ResourceFile directory) {+ public static BundlePath getScriptPath(ResourceFile directory) {if (directory.isDirectory()) {- for (Path path : scriptDirectoryPaths) {+ for (BundlePath path : scriptBundlePaths) {if (path.getPath().equals(directory)) {return path;}@@ -210,143 +201,13 @@ public class GhidraScriptUtil {return new ResourceFile(SourceBundleInfo.getBindirFromScriptFile(scriptFile).toFile());}- @Deprecated- static ResourceFile getClassFile(ResourceFile sourceFile, String rawName) {- if (sourceFile != null) {- // prefer resource files when they exist, as we know exactly which file we want to load- return GhidraScriptUtil.getClassFileByResourceFile(sourceFile, rawName);- }-- return getClassFileByName(rawName);+ public static Path getOsgiDir() {+ Path usersettings = Application.getUserSettingsDirectory().toPath();+ return usersettings.resolve("osgi");}- /**- * Uses the given {@link ResourceFile} to find its class file. This method is needed- * due to the fact that we sometimes can find a class file in more than one location,- * such as when using an installation version of Ghidra in the same environment as- * a development version of Ghidra. We get better debugging when we use the class file- * that is associated with the given source file.- *- * @param sourceFile the source file for which to find the generated class file.- * @param rawName the name of the class, without file extension or path info.- * @return the class file generated from the given source file.- *- * @deprecated the bundle class loader will take care of this, no classpath pollution- */- @Deprecated- static ResourceFile getClassFileByResourceFile(ResourceFile sourceFile, String rawName) {- String javaAbsolutePath = sourceFile.getAbsolutePath();- String classAbsolutePath = javaAbsolutePath.replace(".java", ".class");-- String path = rawName.replace('.', '/');- String className = path + ".class";-- ResourceFile classFile =- findClassFile(getDevelopmentScriptBinDirectories(), classAbsolutePath, className);- if (classFile != null) {- Msg.trace(GhidraScriptUtil.class,- "Resource file " + sourceFile + " class found at " + classFile);- return classFile;- }-- ResourceFile defaultCompilerDirectory = getScriptCompileOutputDirectory(sourceFile);- classFile =- new ResourceFile(new File(defaultCompilerDirectory.getAbsolutePath(), className));- if (classFile.exists()) {- // This should always exist when we compile the script ourselves- Msg.trace(GhidraScriptUtil.class,- "Resource file " + sourceFile + " class found at " + classFile);- return classFile;- }-- classFile = findClassFile(getScriptBinDirectories(), classAbsolutePath, className);- if (classFile != null) {- Msg.trace(GhidraScriptUtil.class,- "Resource file " + sourceFile + " class found at " + classFile);- return classFile;- }-- // default to a non-existent file- return new ResourceFile(GhidraScriptUtil.getScriptCompileOutputDirectory(sourceFile), className);- }-- private static ResourceFile getClassFileByName(String rawName) {- String path = rawName.replace('.', '/');- String className = path + ".class";-- //- // Note: in this case, we *only* want to search the script bin dirs, as we do not want- // to find other class elements that may be in the development environment. For- // example, we do not want to find non-script classes in the development bin dirs,- // as those are loaded by our parent class loader. If we load them, then they will- // not be the same class instances.- //- Set<ResourceFile> matchingClassFiles = new HashSet<>();- Collection<ResourceFile> userBinDirectories = GhidraScriptUtil.getScriptBinDirectories();- for (ResourceFile file : userBinDirectories) {- ResourceFile testFile = new ResourceFile(file, className);- if (testFile.exists()) {- matchingClassFiles.add(testFile);- }- }-- return maybeWarnAboutNameConflict(className, matchingClassFiles);- }-- private static ResourceFile findClassFile(Collection<ResourceFile> binDirs,- String classAbsolutePath, String className) {-- Set<ResourceFile> matchingClassFiles = new HashSet<>();- for (ResourceFile binDir : binDirs) {- ResourceFile binParentFile = binDir.getParentFile();- String absoluteParentPath = binParentFile.getAbsolutePath();- if (classAbsolutePath.startsWith(absoluteParentPath)) {- ResourceFile potentialFile = new ResourceFile(binDir, className);- if (potentialFile.exists()) {- matchingClassFiles.add(potentialFile);- }- }- }-- return maybeWarnAboutNameConflict(className, matchingClassFiles);- }-- private static ResourceFile maybeWarnAboutNameConflict(String className,- Set<ResourceFile> matchingClassFiles) {- int matchCount = matchingClassFiles.size();- if (matchCount == 1) {- return matchingClassFiles.iterator().next();- }- else if (matchCount > 1) {-- //- // Unusual Code: When running from Eclipse we need to use the class file that is- // in the Eclipse project's bin. If not, then users cannot debug- // the scripts, as Eclipse doesn't know how to find the source. This- // can happen when users link source into the scripts project.- // We don't know if we are running from Eclipse, which means that this- // will give out the wrong file in the case where we are not, but there- // happen to be two different class files with the same name.- //- ResourceFile preferredFile = null;- for (ResourceFile file : matchingClassFiles) {- if (file.getParentFile().getAbsolutePath().equals(- GhidraScriptUtil.USER_SCRIPTS_BIN_DIR)) {- preferredFile = file;- break;- }- }-- if (preferredFile == null) {- // just pick one- preferredFile = matchingClassFiles.iterator().next();- }-- Msg.warn(GhidraScriptUtil.class, "Found " + matchCount + " class files named " +- className + ". Using: " + preferredFile);- return preferredFile;- }- return null;+ public static Path getCompiledBundlesDir() {+ return getOsgiDir().resolve("compiled-bundles");}/**@@ -354,10 +215,20 @@ public class GhidraScriptUtil {* @return the list** @see #getScriptCompileOutputDirectory(ResourceFile)+ *+ * @deprecated class files shouldn't be accessed directly*/@Deprecatedpublic static List<ResourceFile> getScriptBinDirectories() {- return Collections.emptyList();+ try {+ return Files.list(getOsgiDir()).filter(Files::isDirectory).map(+ x -> new ResourceFile(x.toFile())).collect(Collectors.toList());+ }+ catch (IOException e) {+ Msg.showError(GhidraScriptUtil.class, null, "error",+ "error listing user osgi directory", e);+ return Collections.emptyList();+ }}/**@@ -373,7 +244,7 @@ public class GhidraScriptUtil {}Set<ResourceFile> dirs = new HashSet<>();- for (Path path : scriptDirectoryPaths) {+ for (BundlePath path : scriptBundlePaths) {//// Assumed structure of script dir path:// /some/path/Ghidra/Features/Module/ghidra_scripts@@ -389,18 +260,11 @@ public class GhidraScriptUtil {}/**- * Deletes all script class files.+ * clear ScriptInfo metadata cached by GhidraScriptUtil*/- public static void clean() {+ public static void clearMetadata() {scriptFileToInfoMap.clear(); // clear our cache of old filesscriptNameToFilesMap.clear();-- File userdir = new File(USER_SCRIPTS_DIR);- File[] classFiles = userdir.listFiles(- (FileFilter) pathname -> pathname.getName().toLowerCase().endsWith(".class"));- for (File classFile : classFiles) {- classFile.delete();- }}/**@@ -425,7 +289,7 @@ public class GhidraScriptUtil {* @param scriptFile the script file* @return true if a ScriptInfo object exists*/- public static boolean contains(ResourceFile scriptFile) {+ public static boolean containsMetadata(ResourceFile scriptFile) {return scriptFileToInfoMap.containsKey(scriptFile);}@@ -433,7 +297,7 @@ public class GhidraScriptUtil {* Removes the ScriptInfo object for the specified file* @param scriptFile the script file*/- public static void unloadScript(ResourceFile scriptFile) {+ public static void removeMetadata(ResourceFile scriptFile) {scriptFileToInfoMap.remove(scriptFile);Iterator<ResourceFile> iter = scriptNameToFilesMap.get(scriptFile.getName()).iterator();@@ -543,14 +407,14 @@ public class GhidraScriptUtil {* @throws IOException if an i/o error occurs*/public static ResourceFile createNewScript(GhidraScriptProvider provider,- ResourceFile parentDirectory, List<Path> scriptDirectories) throws IOException {+ ResourceFile parentDirectory, List<BundlePath> scriptDirectories) throws IOException {String baseName = GhidraScriptConstants.DEFAULT_SCRIPT_NAME;String extension = provider.getExtension();return createNewScript(baseName, extension, parentDirectory, scriptDirectories);}private static ResourceFile createNewScript(String scriptName, String extension,- ResourceFile parentDirctory, List<Path> scriptDirectories) throws IOException {+ ResourceFile parentDirctory, List<BundlePath> scriptDirectories) throws IOException {String baseName = scriptName;String className = baseName + extension;@@ -571,15 +435,18 @@ public class GhidraScriptUtil {}/** Returns true if the given filename exists in any of the given directories */- private static ResourceFile findScriptFileInPaths(List<Path> scriptDirectories,+ private static ResourceFile findScriptFileInPaths(List<BundlePath> scriptDirectories,String filename) {String validatedName = fixupName(filename);- for (Path path : scriptDirectories) {- ResourceFile file = new ResourceFile(path.getPath(), validatedName);- if (file.exists()) {- return file;+ for (BundlePath path : scriptDirectories) {+ ResourceFile resourceFile = path.getPath();+ if (resourceFile.isDirectory()) {+ ResourceFile file = new ResourceFile(resourceFile, validatedName);+ if (file.exists()) {+ return file;+ }}}return null;@@ -626,7 +493,7 @@ public class GhidraScriptUtil {return info;}- ResourceFile file = findScriptFileInPaths(scriptDirectoryPaths, name);+ ResourceFile file = findScriptFileInPaths(scriptBundlePaths, name);if (file == null) {return null;}@@ -636,7 +503,7 @@ public class GhidraScriptUtil {public static List<ResourceFile> getAllScripts() {List<ResourceFile> scriptList = new ArrayList<>();- for (Path dirPath : scriptDirectoryPaths) {+ for (BundlePath dirPath : scriptBundlePaths) {updateAvailableScriptFilesForDirectory(scriptList, dirPath.getPath());}return scriptList;@@ -727,4 +594,5 @@ public class GhidraScriptUtil {files.forEach(file -> scriptFileToInfoMap.get(file).setDuplicate(isDuplicate));});}+}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptClassLoader.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptClassLoader.javadeleted file mode 100644index b45621f10e..0000000000--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptClassLoader.java+++ /dev/null@@ -1,117 +0,0 @@-/* ###- * IP: GHIDRA- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */-package ghidra.app.script;--import java.io.File;-import java.io.IOException;-import java.util.*;--import generic.jar.ResourceFile;-import ghidra.util.Msg;-import utilities.util.FileUtilities;--@Deprecated-public class JavaScriptClassLoader extends ClassLoader {- private Map<File, Long> lastModifiedMap = new HashMap<>();-- public JavaScriptClassLoader() {- super();- }-- @Override- protected synchronized Class<?> loadClass(String name, boolean resolve)- throws ClassNotFoundException, GhidraScriptUnsupportedClassVersionError {-- ResourceFile sourceFile = getScriptSourceFile(name);- ResourceFile classFile = getClassFile(sourceFile, name);- if (classFile == null || !classFile.exists()) {- return super.loadClass(name, resolve);- }-- try {- byte[] classBytes = FileUtilities.getBytesFromFile(classFile);- Class<?> clazz = defineClass(name, classBytes, 0, classBytes.length);- saveClassModifiedTime(classFile);- return clazz;- }- catch (UnsupportedClassVersionError ucve) {- throw new GhidraScriptUnsupportedClassVersionError(ucve, classFile);- }- catch (IOException ioe) {- throw new ClassNotFoundException("Unable to load class bytes: " + name);- }- }-- private void saveClassModifiedTime(ResourceFile classFile) {- File file = classFile.getFile(false);- if (file != null) {- lastModifiedMap.put(file, file.lastModified());- }- }-- public Long lastModified(File file) {- return lastModifiedMap.get(file);- }-- protected ResourceFile getClassFile(ResourceFile sourceFile, String rawName) {- return GhidraScriptUtil.getClassFile(sourceFile, rawName);- }-- /**- * Attempt to find a source file for the given class. If we find it, then we want to use- * the class that is relative to that file. Sometimes there exists multiple classes for- * a given name in the classpath. In that case, we want to use the one associated with the- * source file, as that gives us better debugging in our development environment.- *- * @param name The name of the class for which to find a source file- * @return a source file from which a class file can be located.- */- private ResourceFile getScriptSourceFile(String name) {- String path = name.replace('.', '/');- int innerClassIndex = path.indexOf('$');- if (innerClassIndex != -1) {- path = path.substring(0, innerClassIndex);- }- String sourceFilePath = path + ".java";-- // Create set to store the discovered scripts that match the provided script name.- // Use a LinkedHashSet to preserve the order the scripts were found in so we can properly- // choose the matching script with the highest path precedence.- Set<ResourceFile> matchingFiles = new LinkedHashSet<ResourceFile>();-- List<ResourceFile> scriptSourceDirs = GhidraScriptUtil.getScriptSourceDirectories();- for (ResourceFile sourceDir : scriptSourceDirs) {- ResourceFile potentialFile = new ResourceFile(sourceDir, sourceFilePath);- if (potentialFile.exists()) {- matchingFiles.add(potentialFile);- }- }-- int matchCount = matchingFiles.size();- if (matchCount == 1) {- return matchingFiles.iterator().next();- }- else if (matchCount > 1) {- ResourceFile match = matchingFiles.iterator().next();- Msg.warn(this,- "Found " + matchCount + " source files named " + name + ". Using: " + match);- return match;- }-- return null;- }--}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptProvider.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptProvider.javaindex 87f5fe7740..18805595c7 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptProvider.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/JavaScriptProvider.java@@ -22,32 +22,17 @@ import org.osgi.framework.Bundle;import generic.io.NullPrintWriter;import generic.jar.ResourceFile;+import ghidra.app.plugin.core.script.GhidraScriptMgrPlugin;import ghidra.app.script.osgi.*;import ghidra.util.Msg;public class JavaScriptProvider extends GhidraScriptProvider {- // XXX embedded OSGi should be a service- BundleHost _bundle_host;-- private BundleHost getBundleHost() {- if (_bundle_host == null) {- _bundle_host = new BundleHost();- try {- _bundle_host.startFelix();- }- catch (OSGiException | IOException e) {- throw new RuntimeException(e);- }- }- return _bundle_host;- }-- public SourceBundleInfo getBundleInfoForScript(ResourceFile sourceFile) {- ResourceFile sourceDir = getSourceDirectoryForScript(sourceFile);+ public SourceBundleInfo getBundleInfoForSource(ResourceFile sourceFile) {+ ResourceFile sourceDir = getSourceDirectoryContaining(sourceFile);if (sourceDir == null) {return null;}- return getBundleHost().getSourceBundleInfo(sourceDir);+ return GhidraScriptMgrPlugin.getBundleHost().getSourceBundleInfo(sourceDir);}@Override@@ -62,10 +47,10 @@ public class JavaScriptProvider extends GhidraScriptProvider {@Overridepublic boolean deleteScript(ResourceFile sourceFile) {- Bundle b = getBundleInfoForScript(sourceFile).getBundle();+ Bundle b = getBundleInfoForSource(sourceFile).getBundle();if (b != null) {try {- getBundleHost().synchronousUninstall(b);+ GhidraScriptMgrPlugin.getBundleHost().synchronousUninstall(b);}catch (GhidraBundleException | InterruptedException e) {e.printStackTrace();@@ -80,122 +65,109 @@ public class JavaScriptProvider extends GhidraScriptProvider {public GhidraScript getScriptInstance(ResourceFile sourceFile, PrintWriter writer)throws ClassNotFoundException, InstantiationException, IllegalAccessException {+ try {+ Class<?> clazz = loadClass(sourceFile, writer);+ Object object;+ object = clazz.getDeclaredConstructor().newInstance();++ if (object instanceof GhidraScript) {+ GhidraScript script = (GhidraScript) object;+ script.setSourceFile(sourceFile);+ return script;+ }++ String message = "Not a valid Ghidra script: " + sourceFile.getName();+ writer.println(message);+ Msg.error(this, message);+ return null; // class is not GhidraScript++ }+ catch (OSGiException | IOException | InterruptedException | IllegalArgumentException+ | InvocationTargetException | NoSuchMethodException | SecurityException e) {+ throw new ClassNotFoundException("", e);+ }+ }++ public Class<?> loadClass(ResourceFile sourceFile, PrintWriter writer)+ throws IOException, OSGiException, ClassNotFoundException, InterruptedException {+if (writer == null) {writer = new NullPrintWriter();}- try {-- SourceBundleInfo bi = getBundleInfoForScript(sourceFile);+ SourceBundleInfo bi = getBundleInfoForSource(sourceFile);- bi.updateFromFilesystem(writer);+ bi.updateFromFilesystem(writer);- // needsCompile => needsBundleActivate- boolean needsCompile = false;- boolean needsBundleActivate = false;+ // needsCompile => needsBundleActivate+ boolean needsCompile = false;+ boolean needsBundleActivate = false;- int failing = bi.getFailingSourcesCount();- int newSourcecount = bi.getNewSourcesCount();+ int failing = bi.getFailingSourcesCount();+ int newSourcecount = bi.getNewSourcesCount();- long lastBundleActivation = 0; // XXX record last bundle activation in pathmanager- if (failing > 0 && (lastBundleActivation > bi.getLastCompileAttempt())) {- needsCompile = true;- }+ long lastBundleActivation = 0; // XXX record last bundle activation in pathmanager+ if (failing > 0 && (lastBundleActivation > bi.getLastCompileAttempt())) {+ needsCompile = true;+ }- if (newSourcecount == 0) {- if (failing > 0) {- writer.printf(- "%s hasn't changed, with %d file%s failing in previous build(s):\n",- bi.getSourceDir().toString(), failing, failing > 1 ? "s" : "");- writer.printf("%s\n", bi.getPreviousBuildErrors());- }- if (bi.newManifestFile()) {- needsCompile = true;- }+ if (newSourcecount == 0) {+ if (failing > 0) {+ writer.printf("%s hasn't changed, with %d file%s failing in previous build(s):\n",+ bi.getSourceDir().toString(), failing, failing > 1 ? "s" : "");+ writer.printf("%s\n", bi.getPreviousBuildErrors());}- else {+ if (bi.newManifestFile()) {needsCompile = true;}+ }+ else {+ needsCompile = true;+ }- needsBundleActivate |= needsCompile;-- BundleHost bundle_host = getBundleHost();- if (needsBundleActivate) {- writer.printf("%s has %d new/updated %d failed in previous build(s)%s\n",- bi.getSourceDir().toString(), newSourcecount, failing,- bi.newManifestFile() ? " and the manifest is new" : "");-- // if there a bundle is currently active, uninstall it- Bundle b = bi.getBundle();- if (b != null) {- bundle_host.synchronousUninstall(b);- }-- // once we've committed to recompile and regenerate generated classes, delete the old stuff- if (needsCompile) {- bi.deleteOldBinaries();+ needsBundleActivate |= needsCompile;- BundleCompiler bc = new BundleCompiler(bundle_host);+ BundleHost bundle_host = GhidraScriptMgrPlugin.getBundleHost();+ if (needsBundleActivate) {+ writer.printf("%s has %d new/updated %d failed in previous build(s)%s\n",+ bi.getSourceDir().toString(), newSourcecount, failing,+ bi.newManifestFile() ? " and the manifest is new" : "");- long startTime = System.nanoTime();- bc.compileToExplodedBundle(bi, writer);- long endTime = System.nanoTime();- writer.printf("%3.2f seconds compile time.\n", (endTime - startTime) / 1e9);- }- }- // as much source as possible built, install bundle and start it if necessary+ // if there a bundle is currently active, uninstall itBundle b = bi.getBundle();- if (b == null) {- b = bi.install();- needsBundleActivate = true;+ if (b != null) {+ bundle_host.synchronousUninstall(b);}- if (needsBundleActivate) {- bundle_host.synchronousStart(b);- }+ // once we've committed to recompile and regenerate generated classes, delete the old stuff+ if (needsCompile) {+ bi.deleteOldBinaries();- String classname = bi.classNameForScript(sourceFile);- Object object;- Class<?> clazz = b.loadClass(classname); // throws ClassNotFoundException- object = clazz.getDeclaredConstructor().newInstance();+ BundleCompiler bc = new BundleCompiler(bundle_host);- if (object instanceof GhidraScript) {- GhidraScript script = (GhidraScript) object;- script.setSourceFile(sourceFile);- return script;+ long startTime = System.nanoTime();+ bc.compileToExplodedBundle(bi, writer);+ long endTime = System.nanoTime();+ writer.printf("%3.2f seconds compile time.\n", (endTime - startTime) / 1e9);}-- String message = "Not a valid Ghidra script: " + sourceFile.getName();- writer.println(message);- Msg.error(this, message);- return null; // class is not GhidraScript}- catch (NoSuchMethodException | IOException | IllegalArgumentException- | InvocationTargetException | SecurityException | InterruptedException- | OSGiException e) {- // XXX getScriptInstance only distinguishes exception to print one of three messages.- throw new ClassNotFoundException("", e);+ // as much source as possible built, install bundle and start it if necessary+ Bundle b = bi.getBundle();+ if (b == null) {+ b = bi.install();+ needsBundleActivate = true;}- }- /**- * Gets the class file corresponding to the given source file and class name. If the class is in a package, the- * class name should include the full package name.- *- * @param sourceFile The class's source file.- * @param className The class's name (including package if applicable).- * @return The class file corresponding to the given source file and class name.- */- @Deprecated- protected File getClassFile(ResourceFile sourceFile, String className) {- ResourceFile resourceFile =- GhidraScriptUtil.getClassFileByResourceFile(sourceFile, className);-- File file = resourceFile.getFile(false);- return file;- }+ if (needsBundleActivate) {+ bundle_host.synchronousStart(b);+ }- public static ResourceFile getSourceDirectoryForScript(ResourceFile sourceFile) {+ String classname = bi.classNameForScript(sourceFile);+ Class<?> clazz = b.loadClass(classname); // throws ClassNotFoundException+ return clazz;+ }++ public static ResourceFile getSourceDirectoryContaining(ResourceFile sourceFile) {String sourcePath = sourceFile.getAbsolutePath();for (ResourceFile sourceDir : GhidraScriptUtil.getScriptSourceDirectories()) {if (sourcePath.startsWith(sourceDir.getAbsolutePath())) {@@ -245,29 +217,4 @@ public class JavaScriptProvider extends GhidraScriptProvider {return "//";}- /**- * compile sourcefile and test that the corresponding class is loadable.- *- * @param sourceFile path to Java source file- * @param writer for messages to user- * @return true if compilation succeeded and script can be loaded- * @deprecated compilation of a single script doesn't make sense anymore, directories are compiled to bundles.- *- */- @Deprecated- protected boolean compile(ResourceFile sourceFile, final PrintWriter writer) {- try {- return getScriptInstance(sourceFile, writer) != null;- }- catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {- e.printStackTrace();- return false;- }- }-- @Deprecated- protected boolean needsCompile(ResourceFile sourceFile, File classFile) {- return true;- }-}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleCompiler.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleCompiler.javaindex c18b11974c..a53ad0e88d 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleCompiler.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleCompiler.java@@ -130,7 +130,7 @@ public class BundleCompiler {if (compilationUnits.remove(sf)) {writer.printf("skipping %s\n", sf.toString());// if it's a script, mark it for having compile errors- if (GhidraScriptUtil.contains(rf)) {+ if (GhidraScriptUtil.containsMetadata(rf)) {ScriptInfo info = GhidraScriptUtil.getScriptInfo(rf);info.setCompileErrors(true);}@@ -140,7 +140,7 @@ public class BundleCompiler {// mark the successful compilationsfor (ResourceFileJavaFileObject sf : compilationUnits) {ResourceFile rf = sf.getFile();- if (GhidraScriptUtil.contains(rf)) {+ if (GhidraScriptUtil.containsMetadata(rf)) {ScriptInfo info = GhidraScriptUtil.getScriptInfo(rf);info.setCompileErrors(false);}@@ -158,7 +158,7 @@ public class BundleCompiler {Analyzer analyzer = new Analyzer();analyzer.setJar(new Jar(bindir.toFile())); // give bnd the contentsStream<Object> bjars =- Files.list(bh.getCompiledBundlesDir()).filter(f -> f.toString().endsWith(".jar")).map(+ Files.list(GhidraScriptUtil.getCompiledBundlesDir()).filter(f -> f.toString().endsWith(".jar")).map(f -> {try {return new Jar(f.toFile());diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleHost.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleHost.javaindex 1892763a17..4170110d8b 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleHost.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/BundleHost.java@@ -36,7 +36,7 @@ import org.osgi.framework.wiring.*;import org.osgi.service.log.*;import generic.jar.ResourceFile;-import ghidra.framework.Application;+import ghidra.app.script.GhidraScriptUtil;import ghidra.util.exception.CancelledException;import ghidra.util.task.*;@@ -59,7 +59,7 @@ public class BundleHost {return file2sbi.computeIfAbsent(sourceDir, sd -> new SourceBundleInfo(this, sd));}- // XXX consumers should clean up after themselves+ // XXX consumers must clean up after themselvespublic void removeSourceBundleInfo(ResourceFile sourceDir) {file2sbi.remove(sourceDir);}@@ -306,24 +306,15 @@ public class BundleHost {}- static private Path getOsgiDir() {- Path usersettings = Application.getUserSettingsDirectory().toPath();- return usersettings.resolve("osgi");- }-private String makeCacheDir() throws IOException {- Path cache_dir = getOsgiDir().resolve("felixcache");+ Path cache_dir = GhidraScriptUtil.getOsgiDir().resolve("felixcache");Files.createDirectories(cache_dir);return cache_dir.toAbsolutePath().toString();}/** comma separated list of directories watched for bundles by fileinstaller */private String getWatchedBundleDirs() {- return getCompiledBundlesDir().toAbsolutePath().toString();- }-- static public Path getCompiledBundlesDir() {- return getOsgiDir().resolve("compiled-bundles");+ return GhidraScriptUtil.getCompiledBundlesDir().toAbsolutePath().toString();}public Bundle getBundle(String bundleLoc) {@@ -434,6 +425,7 @@ public class BundleHost {return false;}+public interface NewSourceCallback {void found(ResourceFile source_file, Collection<Path> class_files) throws Throwable;}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/SourceBundleInfo.java b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/SourceBundleInfo.javaindex c321ddeedc..c78e0525f0 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/SourceBundleInfo.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/script/osgi/SourceBundleInfo.java@@ -35,7 +35,7 @@ public class SourceBundleInfo {bundle_host = bundleHost;this.sourceDir = sourceDir;this.symbolicName = BundleHost.getSymbolicNameFromSourceDir(sourceDir);- this.binDir = BundleHost.getCompiledBundlesDir().resolve(symbolicName);+ this.binDir = GhidraScriptUtil.getCompiledBundlesDir().resolve(symbolicName);this.bundleLoc = "reference:file://" + getBinDir().toAbsolutePath().normalize().toString();@@ -44,7 +44,7 @@ public class SourceBundleInfo {static public Path getBindirFromScriptFile(ResourceFile sourceFile) {ResourceFile tmpSourceDir = sourceFile.getParentFile();String tmpSymbolicName = BundleHost.getSymbolicNameFromSourceDir(tmpSourceDir);- return BundleHost.getCompiledBundlesDir().resolve(tmpSymbolicName);+ return GhidraScriptUtil.getCompiledBundlesDir().resolve(tmpSymbolicName);}public String classNameForScript(ResourceFile sourceFile) {diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/headless/GhidraScriptRunner.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/headless/GhidraScriptRunner.javaindex d6724c1eda..55bc048df0 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/headless/GhidraScriptRunner.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/headless/GhidraScriptRunner.java@@ -19,8 +19,8 @@ import java.io.*;import java.util.ArrayList;import java.util.List;+import docking.widgets.bundlemanager.BundlePath;import generic.jar.ResourceFile;-import generic.util.Path;import ghidra.GhidraApplicationLayout;import ghidra.GhidraLaunchable;import ghidra.app.script.*;@@ -192,16 +192,16 @@ public class GhidraScriptRunner implements GhidraLaunchable {* Gather paths where scripts may be found.*/private void initializeScriptPaths() {- List<Path> paths;+ List<BundlePath> paths;if (scriptPaths == null || scriptPaths.isEmpty()) {- paths = GhidraScriptUtil.getDefaultScriptDirectories();+ paths = GhidraScriptUtil.getDefaultScriptBundles();}else {- paths = new ArrayList<Path>();+ paths = new ArrayList<>();for (String path : scriptPaths) {- paths.add(new Path(path, true, false, true));+ paths.add(new BundlePath(path, true, false, true));}- for (Path path : GhidraScriptUtil.getDefaultScriptDirectories()) {+ for (BundlePath path : GhidraScriptUtil.getDefaultScriptBundles()) {if (path.isEnabled() && !paths.contains(path)) {paths.add(path);}diff --git a/Ghidra/Features/Base/src/main/java/ghidra/app/util/headless/HeadlessAnalyzer.java b/Ghidra/Features/Base/src/main/java/ghidra/app/util/headless/HeadlessAnalyzer.javaindex 1090f51193..8367179853 100644--- a/Ghidra/Features/Base/src/main/java/ghidra/app/util/headless/HeadlessAnalyzer.java+++ b/Ghidra/Features/Base/src/main/java/ghidra/app/util/headless/HeadlessAnalyzer.java@@ -20,6 +20,7 @@ import java.net.*;import java.util.*;import java.util.regex.Pattern;+import docking.widgets.bundlemanager.BundlePath;import generic.jar.ResourceFile;import generic.stl.Pair;import generic.util.Path;@@ -660,16 +661,16 @@ public class HeadlessAnalyzer {*/private void initializeScriptPaths() {- List<Path> paths;+ List<BundlePath> paths;if (options.scriptPaths == null || options.scriptPaths.isEmpty()) {- paths = GhidraScriptUtil.getDefaultScriptDirectories();+ paths = GhidraScriptUtil.getDefaultScriptBundles();}else {paths = new ArrayList<>();for (String path : options.scriptPaths) {- paths.add(new Path(path, true, false, true));+ paths.add(new BundlePath(path, true, false, true));}- for (Path path : GhidraScriptUtil.getDefaultScriptDirectories()) {+ for (BundlePath path : GhidraScriptUtil.getDefaultScriptBundles()) {if (path.isEnabled() && !paths.contains(path)) {paths.add(path);}diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/bundlemanager/BundlePath.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/bundlemanager/BundlePath.javanew file mode 100644index 0000000000..3f6f091e3f--- /dev/null+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/bundlemanager/BundlePath.java@@ -0,0 +1,81 @@+package docking.widgets.bundlemanager;++import java.io.File;++import generic.jar.ResourceFile;+import generic.util.Path;++public class BundlePath extends Path {+ boolean active = false;++ public static enum Type {+ BndScript, Jar, SourceDir, INVALID+ }+++ static public Type getType(File f) {+ if (f.isDirectory()) {+ return Type.SourceDir;+ }+ String n = f.getName().toLowerCase();+ if (n.endsWith(".bnd")) {+ return Type.BndScript;+ }+ if (n.endsWith(".jar")) {+ return Type.Jar;+ }+ return Type.INVALID;+ }++ static public Type getType(ResourceFile rf) {+ if (rf.isDirectory()) {+ return Type.SourceDir;+ }+ String n = rf.getName().toLowerCase();+ if (n.endsWith(".bnd")) {+ return Type.BndScript;+ }+ if (n.endsWith(".jar")) {+ return Type.Jar;+ }+ return Type.INVALID;+ }+ final Type type;++ public BundlePath(File path) {+ super(path);+ type = getType(getPath());+ }++ public Type getType() {+ return type;+ }++ public BundlePath(ResourceFile rf) {+ super(rf);+ type = getType(getPath());+ }++ public BundlePath(String absolutePath) {+ super(absolutePath);+ type = getType(getPath());+ }++ public BundlePath(String a, boolean b, boolean c, boolean d) {+ super(a, b, c, d);+ type = getType(getPath());+ }++ public BundlePath(ResourceFile a, boolean b, boolean c, boolean d) {+ super(a, b, c, d);+ type = getType(getPath());+ }++ public boolean isActive() {+ return active;+ }+ public boolean isDirectory() {+ return getPath().isDirectory();+ }++}diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/bundlemanager/BundlePathManager.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/bundlemanager/BundlePathManager.javanew file mode 100644index 0000000000..8e3048dd30--- /dev/null+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/bundlemanager/BundlePathManager.java@@ -0,0 +1,432 @@+/* ###+ * IP: GHIDRA+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package docking.widgets.bundlemanager;++import java.awt.*;+import java.io.File;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.List;++import javax.swing.*;+import javax.swing.event.TableModelListener;+import javax.swing.table.TableColumn;++import docking.widgets.filechooser.GhidraFileChooser;+import docking.widgets.filechooser.GhidraFileChooserMode;+import docking.widgets.table.*;+import generic.jar.ResourceFile;+import ghidra.framework.options.SaveState;+import ghidra.framework.preferences.Preferences;+import ghidra.util.filechooser.GhidraFileChooserModel;+import ghidra.util.filechooser.GhidraFileFilter;+import resources.ResourceManager;++/**+ * Component that has a table to show pathnames; the panel includes buttons to control+ * the order of the paths, and to add and remove paths. The add button brings up a+ * file chooser. Call the setFileChooser() method to control how the file chooser should+ * behave. If the table entries should not be edited, call setEditingEnabled(false).+ */+public class BundlePathManager {+ private JPanel panel;+ private GTable bundlePathTable;+ private BundlePathManagerModel bundlePathModel;+ private TableModelListener bundlePathModelListener;+ private JButton addButton;+ private JButton removeButton;+ private Color selectionColor;+ private GhidraFileChooser fileChooser;+ private String preferenceForLastSelectedBundle = Preferences.LAST_IMPORT_DIRECTORY;+ private String title = "Select File";+ private GhidraFileFilter filter;+ private ArrayList<BundlePathManagerListener> listeners = new ArrayList<>();++ /**+ * Construct a new BundlePathManager.+ * @param paths list of paths to show; may be null+ * if new paths are to be added to the end of the table+ */+ public BundlePathManager(List<BundlePath> paths) {+ create(paths);+ }++ /**+ * Set properties on the file chooser that is displayed when the "Add" button is pressed.+ * @param title title of the file chooser+ * @param preferenceForLastSelectedBundle Preference to use as the starting selection in the+ * file chooser+ */++ public void setFileChooserProperties(String title, String preferenceForLastSelectedBundle) {+ this.title = title;+ this.preferenceForLastSelectedBundle = preferenceForLastSelectedBundle;+ this.filter = new GhidraFileFilter() {+ @Override+ public String getDescription() {+ return "Source code directory, bundle (*.jar), or bnd script (*.bnd)";+ }++ @Override+ public boolean accept(File path, GhidraFileChooserModel model) {+ return BundlePath.getType(path) != BundlePath.Type.INVALID;+ }+ };+ this.fileChooser = null;+ }++ /**+ * Return enabled paths in the table.+ * @return enabled paths+ */+ public List<BundlePath> getPaths() {+ return bundlePathModel.getPaths();+ }++ /**+ * (add and) enable a path+ * @param file path to enable+ * @return true if the path is new+ */+ public boolean enablePath(ResourceFile file) {+ ResourceFile dir = file.isDirectory() ? file : file.getParentFile();+ for (BundlePath path : bundlePathModel.getAllPaths()) {+ if (path.getPath().equals(dir)) {+ if (!path.isEnabled()) {+ path.setEnabled(true);+ bundlePathModel.fireTableDataChanged();+ fireBundlesChanged();+ return true;+ }+ return false;+ }+ }+ BundlePath p = new BundlePath(dir);+ p.setEnabled(true);+ bundlePathModel.addPath(p);+ Preferences.setProperty(preferenceForLastSelectedBundle, dir.getAbsolutePath());+ fireBundlesChanged();+ return true;+ }++ public void setPaths(List<BundlePath> paths) {+ bundlePathModel.setPaths(paths);+ }++ /**+ * Clear the paths in the table.+ */+ public void clear() {+ bundlePathModel.clear();+ }++ public void addListener(BundlePathManagerListener listener) {+ if (!listeners.contains(listener)) {+ listeners.add(listener);+ }+ }++ public void removeListener(BundlePathManagerListener listener) {+ listeners.remove(listener);+ }++ public List<BundlePathManagerListener> getListeners() {+ return new ArrayList<>(listeners);+ }++ private void fireBundlesChanged() {+ for (BundlePathManagerListener listener : listeners) {+ listener.bundlesChanged();+ }+ }++ private void create(List<BundlePath> paths) {+ panel = new JPanel(new BorderLayout(5, 5));++ selectionColor = new Color(204, 204, 255);++ addButton = new JButton(ResourceManager.loadImage("images/Plus.png"));+ addButton.setName("AddBundle");+ addButton.setToolTipText("Display file chooser to add bundles to list");+ addButton.addActionListener(e -> add());+ addButton.setFocusable(false);++ removeButton = new JButton(ResourceManager.loadImage("images/edit-delete.png"));+ removeButton.setName("RemoveBundle");+ removeButton.setToolTipText("Remove selected bundle(s) from list");+ removeButton.addActionListener(e -> remove());+ removeButton.setFocusable(false);++ JPanel buttonPanel = new JPanel(new GridBagLayout());+ GridBagConstraints gbc = new GridBagConstraints();+ gbc.anchor = GridBagConstraints.CENTER;+ gbc.insets = new Insets(0, 0, 0, 0);+ gbc.gridx = 0;+ gbc.gridy = 0;++ buttonPanel.add(addButton, gbc);+ ++gbc.gridy;+ buttonPanel.add(removeButton, gbc);++ bundlePathModelListener = e -> fireBundlesChanged();++ bundlePathModel = new BundlePathManagerModel(this, paths);+ bundlePathModel.addTableModelListener(bundlePathModelListener);++ bundlePathTable = new GTable(bundlePathModel);+ bundlePathTable.setName("BUNDLEPATH_TABLE");+ bundlePathTable.setSelectionBackground(selectionColor);+ bundlePathTable.setSelectionForeground(Color.BLACK);+ bundlePathTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);++ int skinnyWidth = 50;++ TableColumn column =+ bundlePathTable.getColumnModel().getColumn(BundlePathManagerModel.COLUMN.Enabled.index);+ column.setPreferredWidth(skinnyWidth);+ column.setMinWidth(skinnyWidth);+ column.setMaxWidth(skinnyWidth);+ column.setWidth(skinnyWidth);++ column =+ bundlePathTable.getColumnModel().getColumn(BundlePathManagerModel.COLUMN.Active.index);+ column.setPreferredWidth(skinnyWidth);+ column.setMinWidth(skinnyWidth);+ column.setMaxWidth(skinnyWidth);+ column.setWidth(skinnyWidth);++ column =+ bundlePathTable.getColumnModel().getColumn(BundlePathManagerModel.COLUMN.Type.index);++ FontMetrics fontmetrics = panel.getFontMetrics(panel.getFont());+ column.setMaxWidth(10 ++ SwingUtilities.computeStringWidth(fontmetrics, BundlePath.Type.SourceDir.toString()));++ column =+ bundlePathTable.getColumnModel().getColumn(BundlePathManagerModel.COLUMN.Path.index);+ column.setCellRenderer(new GTableCellRenderer() {+ @Override+ public Component getTableCellRendererComponent(GTableCellRenderingData data) {+ JLabel renderer = (JLabel) super.getTableCellRendererComponent(data);++ BundlePath path = (BundlePath) data.getValue();+ if (!path.exists()) {+ renderer.setForeground(Color.RED);+ }+ return renderer;+ }+ });++ GTableFilterPanel<BundlePath> filterPanel =+ new GTableFilterPanel<>(bundlePathTable, bundlePathModel);++ JScrollPane scrollPane = new JScrollPane(bundlePathTable);+ scrollPane.getViewport().setBackground(bundlePathTable.getBackground());++ ListSelectionModel selModel = bundlePathTable.getSelectionModel();+ selModel.addListSelectionListener(e -> {+ if (e.getValueIsAdjusting()) {+ return;+ }+ updateButtonsEnabled();+ });+ updateButtonsEnabled();++ JPanel centerPanel = new JPanel(new BorderLayout());+ centerPanel.add(scrollPane, BorderLayout.CENTER);+ centerPanel.add(filterPanel, BorderLayout.SOUTH);+ panel.add(centerPanel, BorderLayout.CENTER);+ panel.add(buttonPanel, BorderLayout.EAST);+ panel.setPreferredSize(new Dimension(800, 400));+ }++ private void updateButtonsEnabled() {+ int[] rows = bundlePathTable.getSelectedRows();+ removeButton.setEnabled(rows.length > 0);+ }++ private void remove() {+ int[] selectedRows = bundlePathTable.getSelectedRows();+ if (selectedRows == null) {+ return;+ }+ bundlePathModel.remove(selectedRows);++ // select the next row based on what was selected+ Arrays.sort(selectedRows);+ int row = selectedRows[selectedRows.length - 1] + 1 - selectedRows.length;+ int count = bundlePathModel.getRowCount();+ if (row >= count) {+ row = count - 1;+ }+ if (row >= 0) {+ bundlePathTable.setRowSelectionInterval(row, row);+ }+ updateButtonsEnabled();+ }++ private void add() {+ if (fileChooser == null) {+ fileChooser = new GhidraFileChooser(panel);+ // XXX bad behavior w/ text box when multiselection is enabled+ fileChooser.setMultiSelectionEnabled(true);+ fileChooser.setFileSelectionMode(GhidraFileChooserMode.FILES_AND_DIRECTORIES);+ fileChooser.setTitle(title);+ // fileChooser.setApproveButtonToolTipText(title);+ if (filter != null) {+ fileChooser.addFileFilter(new GhidraFileFilter() {+ @Override+ public String getDescription() {+ return filter.getDescription();+ }++ @Override+ public boolean accept(File f, GhidraFileChooserModel l_model) {+ return filter.accept(f, l_model);+ }+ });+ }+ String lastSelected = Preferences.getProperty(preferenceForLastSelectedBundle);+ if (lastSelected != null) {+ File f = new File(lastSelected);+ fileChooser.setSelectedFile(f);+ }+ }+ else {+ String lastSelected = Preferences.getProperty(preferenceForLastSelectedBundle);+ if (lastSelected != null) {+ File f = new File(lastSelected);+ fileChooser.setSelectedFile(f);+ }+ fileChooser.rescanCurrentDirectory();+ }++ List<File> files = fileChooser.getSelectedFiles();+ if (!files.isEmpty()) {+ Preferences.setProperty(preferenceForLastSelectedBundle,+ files.get(0).getAbsolutePath());+ for (File element : files) {+ BundlePath p = new BundlePath(element);+ bundlePathModel.addPath(p);+ }+ }+ }++ /**+ * Returns the GUI component for the path manager.+ * @return the GUI component for the path manager+ */+ public JComponent getComponent() {+ return panel;+ }++ /**+ * Saves the paths to the specified SaveState object.+ * @param ss the SaveState object+ */+ public void saveState(SaveState ss) {+ List<BundlePath> paths = bundlePathModel.getAllPaths();++ String[] pathArr = new String[paths.size()];+ boolean[] enableArr = new boolean[paths.size()];+ boolean[] editArr = new boolean[paths.size()];+ boolean[] readArr = new boolean[paths.size()];++ int index = 0;+ for (BundlePath path : paths) {+ pathArr[index] = path.getPathAsString();+ enableArr[index] = path.isEnabled();+ editArr[index] = path.isEditable();+ readArr[index] = path.isReadOnly();+ ++index;+ }++ ss.putStrings("BundleManagerPanel_PATH", pathArr);+ ss.putBooleans("BundleManagerPanel_ENABLE", enableArr);+ ss.putBooleans("BundleManagerPanel_EDIT", editArr);+ ss.putBooleans("BundleManagerPanel_READ", readArr);+ }++ /**+ * Restores the paths from the specified SaveState object.+ * @param ss the SaveState object+ */+ public void restoreState(SaveState ss) {+ String[] pathArr = ss.getStrings("BundleManagerPanel_PATH", new String[0]);++ if (pathArr.length == 0) {+ return;+ }++ /*+ * Temporarily remove the listener to prevent too many+ * notifications from being sent.+ */+ bundlePathModel.removeTableModelListener(bundlePathModelListener);++ boolean[] enableArr =+ ss.getBooleans("BundleManagerPanel_ENABLE", new boolean[pathArr.length]);+ boolean[] editArr = ss.getBooleans("BundleManagerPanel_EDIT", new boolean[pathArr.length]);+ boolean[] readArr = ss.getBooleans("BundleManagerPanel_READ", new boolean[pathArr.length]);++ List<BundlePath> oldPaths = bundlePathModel.getAllPaths();+ bundlePathModel.clear();++ for (int i = 0; i < pathArr.length; i++) {+ BundlePath path = new BundlePath(pathArr[i], enableArr[i], editArr[i], readArr[i]);+ BundlePath oldPath = getPath(path.getPathAsString(), oldPaths);+ if (oldPath != null) {+ if (!oldPath.isEditable()) {+ boolean enabled = path.isEnabled();+ path = oldPath;+ path.setEnabled(enabled);+ }+ oldPaths.remove(oldPath);+ }+ else if (path.isReadOnly()) {+ // skip read-only paths which are not present in the current config+ // This is needed to thin-out old default entries+ continue;+ }+ bundlePathModel.addPath(path);+ }++ for (BundlePath path : oldPaths) {+ if (!path.isEditable()) {+ bundlePathModel.addPath(path);+ }+ }++ /*+ * Reinstall the listener then fire the update.+ */+ bundlePathModel.addTableModelListener(bundlePathModelListener);+ fireBundlesChanged();+ }++ private static BundlePath getPath(String filepath, List<BundlePath> paths) {+ for (BundlePath path : paths) {+ if (filepath.equals(path.getPathAsString())) {+ return path;+ }+ }+ return null;+ }++ public void dispose() {+ bundlePathTable.dispose();+ }+}diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/bundlemanager/BundlePathManagerListener.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/bundlemanager/BundlePathManagerListener.javanew file mode 100644index 0000000000..ca97a11cd6--- /dev/null+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/bundlemanager/BundlePathManagerListener.java@@ -0,0 +1,29 @@+/* ###+ * IP: GHIDRA+ * REVIEWED: YES+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package docking.widgets.bundlemanager;+++public interface BundlePathManagerListener {++ public void pathMessage(String message);++ /**+ * Notified when the user changes the paths in the PathManager. This could be the addition+ * or removal of Path objects, or a simple reordering of the paths.+ */+ public void bundlesChanged();+}diff --git a/Ghidra/Framework/Docking/src/main/java/docking/widgets/bundlemanager/BundlePathManagerModel.java b/Ghidra/Framework/Docking/src/main/java/docking/widgets/bundlemanager/BundlePathManagerModel.javanew file mode 100644index 0000000000..e4bc47e51a--- /dev/null+++ b/Ghidra/Framework/Docking/src/main/java/docking/widgets/bundlemanager/BundlePathManagerModel.java@@ -0,0 +1,291 @@+/* ###+ * IP: GHIDRA+ * REVIEWED: YES+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package docking.widgets.bundlemanager;++import java.util.*;++import org.apache.commons.lang3.NotImplementedException;++import docking.widgets.table.AbstractSortedTableModel;++class BundlePathManagerModel extends AbstractSortedTableModel<BundlePath> {+ private static int column_counter = 0;++ static enum COLUMN {+ Enabled(Boolean.class) {+ @Override+ Object getValue(BundlePath path) {+ return path.isEnabled();+ }++ @Override+ void setValue(BundlePath path, Object aValue) {+ path.setEnabled((Boolean) aValue);+ }+ },+ Active(Boolean.class) {+ @Override+ Object getValue(BundlePath path) {+ return path.isActive();+ }++ @Override+ void setValue(BundlePath path, Object aValue) {+ throw new NotImplementedException("TODO!");+ }+ },+ Type(String.class) {+ @Override+ boolean editable(BundlePath path) {+ return false;+ }++ @Override+ Object getValue(BundlePath path) {+ return path.getType().toString();+ }++ },+ Path(BundlePath.class) {+ @Override+ boolean editable(BundlePath path) {+ return true;+ }++ @Override+ void setValue(BundlePath path, Object aValue) {+ if (path.isEditable()) {+ BundlePath newpath = (BundlePath) aValue;+ path.setPath(newpath.getPath());+ }+ }+ },+ __badcolumnindex__(Object.class);++ final Class<?> clazz;+ final int index;++ boolean editable(BundlePath path) {+ return true;+ }++ Object getValue(BundlePath path) {+ return path;+ }++ COLUMN(Class<?> clazz) {+ this.index = column_counter++;+ this.clazz = clazz;+ }++ static COLUMN[] vals = values();+ static {+ vals = Arrays.copyOf(vals, vals.length - 1);+ }++ static COLUMN val(int i) {+ if (i >= 0 && i < vals.length) {+ return vals[i];+ }+ return __badcolumnindex__;+ }++ void setValue(BundlePath path, Object aValue) {+ // do nothing+ }+ }++ private BundlePathManager mgr;+ private List<BundlePath> paths = new ArrayList<>();++ BundlePathManagerModel(BundlePathManager mgr, List<BundlePath> paths) {+ super();+ this.mgr = mgr;+ this.paths.addAll(dedupPaths(paths));+ fireTableDataChanged();+ }++ private List<BundlePath> dedupPaths(List<BundlePath> newPaths) {+ List<BundlePath> dedupedPaths = new ArrayList<>();+ for (BundlePath path : newPaths) {+ if (!dedupedPaths.contains(path)) {+ dedupedPaths.add(path);+ }+ }+ return dedupedPaths;+ }++ void clear() {+ paths.clear();+ }++ List<BundlePath> getAllPaths() {+ return new ArrayList<BundlePath>(paths);+ }++ List<BundlePath> getPaths() {+ List<BundlePath> list = new ArrayList<>();+ for (BundlePath path : paths) {+ if (path.isEnabled()) {+ list.add(path);+ }+ }+ return list;+ }++ void setPaths(List<BundlePath> paths) {+ this.paths = new ArrayList<>(paths);+ fireTableDataChanged();+ }++ void setPaths(BundlePath[] pathsArr) {+ paths.clear();+ paths = new ArrayList<>();+ for (BundlePath element : pathsArr) {+ paths.add(element);+ }+ fireTableDataChanged();+ }++ void addPath(BundlePath path) {+ if (paths.contains(path)) {+ return;+ }+ int index = paths.size();+ paths.add(path);+ fireTableRowsInserted(index, index);+ }++ void removePath(BundlePath path) {+ int index = paths.indexOf(path);+ if (path.isEditable()) {+ paths.remove(path);+ }+ else {+ List<BundlePathManagerListener> listeners = mgr.getListeners();+ for (BundlePathManagerListener listener : listeners) {+ listener.pathMessage("Unable to remove path.");+ }+ }+ fireTableRowsDeleted(index, index);+ }++ void remove(int[] selectedRows) {+ List<BundlePath> list = new ArrayList<>();+ for (int selectedRow : selectedRows) {+ list.add(paths.get(selectedRow));+ }+ for (BundlePath path : list) {+ if (path.isEditable()) {+ paths.remove(path);+ }+ else {+ List<BundlePathManagerListener> listeners = mgr.getListeners();+ for (BundlePathManagerListener listener : listeners) {+ listener.pathMessage("Unable to remove path.");+ }+ }+ }+ fireTableDataChanged();+ }++ int moveUp(int index) {+ if (index < 0 || index >= paths.size()) {+ return -1;+ }+ BundlePath path = paths.remove(index);+ if (index == 0) {+ paths.add(path);//place it last in the list+ }+ else {+ paths.add(index - 1, path);+ }+ fireTableDataChanged();+ return paths.indexOf(path);+ }++ int moveDown(int index) {+ if (index < 0 || index >= paths.size()) {+ return -1;+ }+ int size = paths.size();+ BundlePath path = paths.remove(index);+ if (index == size - 1) {+ paths.add(0, path);//move to the top of the list+ }+ else {+ paths.add(index + 1, path);+ }+ fireTableDataChanged();+ return paths.indexOf(path);+ }++ /***************************************************/++ @Override+ public java.lang.Class<?> getColumnClass(int columnIndex) {+ return COLUMN.val(columnIndex).clazz;+ }++ @Override+ public int getColumnCount() {+ return COLUMN.vals.length;+ }++ @Override+ public int getRowCount() {+ return paths.size();+ }++ @Override+ public boolean isCellEditable(int rowIndex, int columnIndex) {+ BundlePath path = paths.get(rowIndex);+ return COLUMN.val(columnIndex).editable(path);+ }++ @Override+ public String getColumnName(int columnIndex) {+ return COLUMN.val(columnIndex).toString();+ }++ @Override+ public void setValueAt(Object aValue, int rowIndex, int columnIndex) {+ BundlePath path = paths.get(rowIndex);+ COLUMN.val(columnIndex).setValue(path, aValue);+ fireTableDataChanged();+ }++ @Override+ public boolean isSortable(int columnIndex) {+ return true;+ }++ @Override+ public String getName() {+ return "BundlePathManagerModel";+ }++ @Override+ public List<BundlePath> getModelData() {+ return paths;+ }++ @Override+ public Object getColumnValueForRow(BundlePath path, int columnIndex) {+ return COLUMN.val(columnIndex).getValue(path);+ }+}